Class: Amarillo

Inherits:
Object
  • Object
show all
Defined in:
lib/amarillo.rb

Defined Under Namespace

Classes: Environment

Instance Method Summary collapse

Constructor Details

#initialize(amarilloHome) ⇒ Amarillo

Returns a new instance of Amarillo.



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/amarillo.rb', line 37

def initialize(amarilloHome)

  @environment = Amarillo::Environment.new(amarilloHome:  amarilloHome)

  if not @environment.verify then raise "Cannot initialize amarillo" end

  @environment.load_config

  @certificatePath = @environment.certificatePath
  @keyPath         = @environment.keyPath
  @config          = @environment.config
  @awsEnvFile      = @environment.awsEnvFile
  @configsPath     = @environment.configsPath

  @logger = Logger.new(STDOUT)
  @logger.level = Logger::INFO

end

Instance Method Details

#check_dns(domainName, nameservers, value) ⇒ Object



56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/amarillo.rb', line 56

def check_dns(domainName, nameservers, value)
  valid = true

  nameservers.each do |nameserver|
    begin
      records = Resolv::DNS.open(nameserver: nameserver) do |dns|
        dns.getresources(
          "_acme-challenge.#{domainName}", 
          Resolv::DNS::Resource::IN::TXT
          )
      end
      records = records.map(&:strings).flatten
      valid = value == records.first
    rescue Resolv::ResolvError
      return false
    end
    return false if !valid
  end

  valid
end

#cleanup(label, record_type, challengeValue) ⇒ Object



255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
# File 'lib/amarillo.rb', line 255

def cleanup(label, record_type, challengeValue)
  @logger.info "Cleaning up..."

  change = {
    action: 'DELETE',
    resource_record_set: {
      name: label,
      type: record_type,
      ttl: 1,
      resource_records: [
        { value: "\"#{challengeValue}\"" }
      ]
    }
  }

  options = {
    hosted_zone_id: @hzone.id,
    change_batch: {
      changes: [change]
    }
  }

  @route53.change_resource_record_sets(options)
end

#deleteCertificate(commonName) ⇒ Object



302
303
304
305
306
307
308
309
310
311
# File 'lib/amarillo.rb', line 302

def deleteCertificate(commonName)
  @logger.info "Deleting certificate #{commonName}"

  certConfigFile = @configsPath + "/#{commonName}.yml"
  certificatePath = @certificatePath + "/#{commonName}.crt"
  keyPath         = @keyPath         + "/#{commonName}.key"

  `rm -f #{certConfigFile} #{certificatePath} #{keyPath}`

end

#doRenewalAction(renewal_action) ⇒ Object



345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
# File 'lib/amarillo.rb', line 345

def doRenewalAction(renewal_action)

  if renewal_action

      @logger.info "Executing certificate renewal action:  #{renewal_action}"

      begin
        %x( #{renewal_action} )
        @logger.info "Renewal action returned:  #{$?}"
      rescue
        @logger.error("Error executing certificate renewal action")
        raise
      end 

  end

end

#get_route53Object



78
79
80
81
82
83
84
85
86
87
# File 'lib/amarillo.rb', line 78

def get_route53
  shared_creds = Aws::SharedCredentials.new(path: "#{@awsEnvFile}")

  Aws.config.update(credentials: shared_creds)

  region  = @config["defaults"]["region"] ? @config["defaults"]["region"] : 'us-east-2'
  @route53 = Aws::Route53::Client.new(region: region)
  @hzone   = @route53.list_hosted_zones(max_items: 100).hosted_zones.detect { |z| z.name == "#{@zone}." }

end

#listCertificatesObject



280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
# File 'lib/amarillo.rb', line 280

def listCertificates

  rows = []

  Dir["#{@configsPath}/*.yml"].each do |c|
    config = YAML.load(File.read(c))

    cn = config["commonName"]

    certificatePath = "#{@certificatePath}/#{cn}.crt"
    raw = File.read certificatePath
    certificate = OpenSSL::X509::Certificate.new raw      

    rows <<  [config["commonName"], config["email"],
              config["zone"], config["key_type"], certificate.not_after]

  end

  t = Terminal::Table.new :headings => ['commonName','email','zone','keytype','expiration'], :rows => rows
  puts t
end

#renewCertificate(commonName) ⇒ Object

Renew specific certificate, implied force



338
339
340
341
342
343
# File 'lib/amarillo.rb', line 338

def renewCertificate(commonName)

  configPath = "#{@configsPath}/#{commonName}.yml"
  self.requestCertificate configPath:  configPath

end

#renewCertificatesObject

Renew all certificates



314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
# File 'lib/amarillo.rb', line 314

def renewCertificates
  t = Time.now
  @logger.info "Renewing certificates"

  Dir["#{@configsPath}/*.yml"].each do |c|
    config = YAML.load(File.read(c))

    cn = config["commonName"]

    certificatePath = "#{@certificatePath}/#{cn}.crt"
    raw = File.read certificatePath
    certificate = OpenSSL::X509::Certificate.new raw      
    daysToExpiration = (certificate.not_after - t).to_i / (24 * 60 * 60)

    if daysToExpiration < 30 then
      @logger.info "#{cn} certificate needs to be renewed"
      self.requestCertificate configPath:  c
    else
      @logger.info "#{cn} certificate does not need to be renewed"
    end
  end
end

#requestCertificate(configPath: nil, certConfig: nil) ⇒ Object



89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
# File 'lib/amarillo.rb', line 89

def requestCertificate(configPath:  nil, certConfig:  nil)

  if configPath
    certConfig = YAML.load(File.read(configPath))
  end
  
  commonName     = certConfig["commonName"]
  email          = certConfig["email"]
  zone           = certConfig["zone"]
  key_type       = certConfig["key_type"]
  script         = certConfig["script"]

  @zone = zone

  acmeUrl = @config["defaults"]["acme_url"] ? @config["defaults"]["acme_url"] : 'https://acme-v02.api.letsencrypt.org/directory'

  # Load private key

  @logger.info "Loading 4096-bit RSA private key for Let's Encrypt account"
  @logger.info "Let's Encrypt directory set to #{acmeUrl}"

  key = OpenSSL::PKey::RSA.new File.read "#{@keyPath}/letsencrypt.key"

  client = Acme::Client.new private_key: key, 
                            directory:   acmeUrl

   = client. contact: "mailto:#{email}", 
                               terms_of_service_agreed: true

  # Generate a certificate order
  @logger.info "Creating certificate order request for #{commonName}"

  order          = client.new_order(identifiers: [commonName])
  authorization  = order.authorizations.first
  label          = "_acme-challenge.#{commonName}"
  record_type    = authorization.dns.record_type
  challengeValue = authorization.dns.record_content

  @logger.info "Challenge value for #{commonName} in #{zone} zone is #{challengeValue}"

  self.get_route53

  change = {
    action: 'UPSERT',
    resource_record_set: {
      name: label,
      type: record_type,
      ttl: 1,
      resource_records: [
        { value: "\"#{challengeValue}\"" }
      ]
    }
  }

  options = {
    hosted_zone_id: @hzone.id,
    change_batch: {
      changes: [change]
    }
  }

  @route53.change_resource_record_sets(options)

  at_exit do 
    self.cleanup label, record_type, challengeValue
  end


  nameservers = @environment.get_zone_nameservers

  @logger.info "Waiting for DNS record to propagate"
  while !check_dns(commonName, nameservers, challengeValue)
    sleep 5
    @logger.info "Still waiting..."
  end

  authorization.dns.request_validation

  @logger.info "Requesting validation..."
  authorization.dns.reload
  while authorization.dns.status == 'pending'
  	sleep 5
  	@logger.info "DNS status:  #{authorization.dns.status}"
  	authorization.dns.reload
  end

  @logger.info "Generating key"

  if key_type
    certConfig["key_type"] = key_type
  else
    key_type = @config["defaults"]["key_type"]
    certConfig["key_type"] = key_type
  end 

  type, args = key_type.split(',')

  if type == 'ec' then
    certPrivateKey = OpenSSL::PKey::EC.new(args).generate_key
  elsif type == 'rsa' then
    if args.to_i > 0
      certPrivateKey = OpenSSL::PKey::RSA.new(args.to_i)
    else
      @logger.error("Invalid RSA key size:  #{args}")
    end 
  end

  @logger.info "Requesting certificate..."  
  csr = Acme::Client::CertificateRequest.new private_key: certPrivateKey, 
                                             names: [commonName]

  while order.status != 'ready'
    sleep(1)
    @logger.info "Order status:  #{order.status}"
    order.reload
    raise if order.status == 'invalid'
  end

  @logger.info "Order status:  #{order.status}"

  begin                                               
    order.finalize(csr: csr)
  rescue
    @logger.error("Error finalizing certificate order")
    raise 
  end

  keyOutputPath =  "#{@keyPath}/#{commonName}.key"
  certOutputPath = "#{@certificatePath}/#{commonName}.crt"

  @logger.info "Saving private key to #{keyOutputPath}"

  File.open(keyOutputPath, "w") do |f|
  	f.puts certPrivateKey.to_pem.to_s
  end

  keyMode = @config["defaults"]["key_mode"] || 0600
  if keyMode
    File.chmod(keyMode, keyOutputPath)
  else
    File.chmod(0600, keyOutputPath)
  end

  @logger.info "Saving certificate to #{certOutputPath}"

  File.open(certOutputPath, "w") do |f|
  	f.puts order.certificate
  end

  owner = certConfig["owner"] || @config["defaults"]["owner"] || "root"
  group = certConfig["group"] || @config["defaults"]["group"] || "root"
  begin
    FileUtils.chown(owner, group, keyOutputPath)
  rescue
    @logger.info "Unable to change ownership of key file #{keyOutputPath}"
  end

  certConfigFile = "#{@configsPath}/#{commonName}.yml"

  @logger.info "Saving certificate configuration to #{certConfigFile}"
  File.write(certConfigFile, certConfig.to_yaml)

  self.doRenewalAction script

end