]> git.netwichtig.de Git - user/henk/code/ruby/macir.git/blob - macir.rb
cleanup linter grievances; general tidying; less sleeping
[user/henk/code/ruby/macir.git] / macir.rb
1 #!/usr/bin/ruby
2
3 # frozen_string_literal: true
4
5 require 'yaml'
6 require 'openssl'
7 require 'acme-client'
8 require 'dnsruby'
9 require 'time'
10 require 'English'
11
12
13 def read_config(path = 'config.yaml')
14   p "Reading config from #{path}"
15   YAML.load_file(path)
16 rescue Psych::SyntaxError => e
17   warn "Parsing configfile failed: #{e}"
18   raise
19 rescue Errno::ENOENT => e
20   warn "IO failed: #{e}"
21   raise
22 end
23
24 def ensure_cert_dir(path = './certs')
25   unless File.exist?(path)
26     puts 'Certificate directory does not exist. Creating with secure permissions.'
27     Dir.mkdir(path, 0o0700)
28   end
29   File.world_writable?(path) && warn('WARNING! Certificate directory is world writable! This could be a serious security issue!')
30   File.world_readable?(path) && warn('WARNING! Certificate directory is world readable! This could be a serious security issue!')
31   File.file?(path) && raise('Certificate directory is not a directory but a file. Aborting.')
32   File.writable?(path) || raise('Certificate directory is not writable. Aborting.')
33 end
34
35 def read_account_key(path = 'pkey.pem')
36   p "Reading account key from #{path}"
37   if File.readable?(path)
38     p "File #{path} is readable, trying to parse"
39     privatekey_string = File.read(path)
40     private_key = OpenSSL::PKey::EC.new(privatekey_string)
41   elsif File.exist?(path)
42     raise("The file #{path} exists but is not readable. Make it readable or specify different path")
43   else
44     p "File #{path} does not exist, trying to create"
45     private_key = OpenSSL::PKey::EC.generate('prime256v1')
46     File.write(path, private_key.private_to_pem)
47   end
48   return private_key
49 end
50
51 def read_cert_key(cert_name)
52   folder = "./certs/#{cert_name}/"
53   path = "#{folder}/current.key"
54   p "cert_name #{cert_name}: Reading cert key from #{path}"
55   if File.readable?(path)
56     p "cert_name #{cert_name}: File #{path} is readable, trying to parse"
57     privatekey_string = File.read(path)
58     private_key = OpenSSL::PKey::EC.new(privatekey_string)
59   elsif File.exist?(path)
60     raise("cert_name #{cert_name}: The file #{path} exists but is not readable. Make it readable or specify different path")
61   else
62     p "cert_name #{cert_name}: File #{path} does not exist, trying to create"
63     private_key = OpenSSL::PKey::EC.generate('prime256v1')
64     pkey_file = File.new("#{folder}#{Time.now.to_i}.key", 'w')
65     pkey_file.write(private_key.private_to_pem)
66     File.symlink(File.basename(pkey_file), "#{File.dirname(pkey_file)}/current.key")
67   end
68   return private_key
69 end
70
71 def lookup_soa(domain)
72   rec = Dnsruby::Recursor.new
73   p "Domain #{domain}: Getting SOA records for #{domain}"
74   rec.query_no_validation_or_recursion(domain, 'SOA')
75 rescue StandardError => e
76   warn "Domain #{domain}: SOA lookup during deploy failed: #{e}"
77   raise
78 end
79
80 def find_apex_domain(domain)
81   domain_soa_resp = lookup_soa(domain)
82   if domain_soa_resp.answer.empty?
83     domain_soa_resp.authority[0].name
84   else
85     domain_soa_resp.answer[0].name
86   end
87 end
88
89 def deploy_dns01_challenge_token(domain, challenge, nameserver, config)
90   p "Domain #{domain}: Creating DNS UPDATE packet"
91
92   apex_domain = find_apex_domain(domain)
93
94   update = Dnsruby::Update.new(apex_domain)
95   # TODO: delete challenge token record after validation
96   update.delete("#{challenge.record_name}.#{domain}", challenge.record_type)
97   update.add("#{challenge.record_name}.#{domain}", challenge.record_type, 10, challenge.record_content)
98
99   p "Domain #{domain}: Creating object for contacting nameserver"
100   res = Dnsruby::Resolver.new(nameserver)
101   res.dnssec = false
102
103   p "Domain #{domain}: Looking up TSIG parameters"
104   tsig_name = config.dig('domains', domain, 'tsig_key') || config.dig('defaults', 'domains', 'tsig_key')
105   tsig_key = config.dig('tsig_keys', tsig_name, 'key')
106   tsig_alg = config.dig('tsig_keys', tsig_name, 'algorithm')
107
108   p "Domain #{domain}: Creating TSIG object"
109   tsig = Dnsruby::RR.create(
110     {
111       name: tsig_name,
112       type: 'TSIG',
113       key: tsig_key,
114       algorithm: tsig_alg,
115     }
116   )
117
118   p "Domain #{domain}: Signing DNS UPDATE packet with TSIG object"
119   tsig.apply(update)
120
121   p "Domain #{domain}: Sending UPDATE to nameserver"
122   res.send_message(update)
123 rescue StandardError => e
124   warn "Domain #{domain}: DNS Update failed: #{e}"
125   raise
126 end
127
128 def wait_for_challenge_propagation(domain, challenge)
129   rec = Dnsruby::Recursor.new
130   p "Domain #{domain}: Getting SOA records for #{domain}"
131   begin
132     domain_soa_resp = rec.query_no_validation_or_recursion(domain, 'SOA')
133   rescue StandardError => e
134     warn "Domain #{domain}: SOA lookup during propagation wait failed: #{e}"
135     raise
136   end
137   apex_domain = if domain_soa_resp.answer.empty?
138                   domain_soa_resp.authority[0].name
139                 else
140                   domain_soa_resp.answer[0].name
141                 end
142
143   p "Domain #{domain}: Creating recursor object for checking challenge propagation"
144   rec = Dnsruby::Recursor.new
145   p "Domain #{domain}: Getting NS records for #{apex_domain}"
146   begin
147     domain_auth_ns = rec.query_no_validation_or_recursion(apex_domain, 'NS')
148   rescue StandardError => e
149     warn "Domain #{domain}: NS lookup failed: #{e}"
150     raise
151   end
152
153   p "Domain #{domain}: Checking challenge status on all NS"
154
155   threads = []
156
157   domain_auth_ns.answer.each do |ns|
158     threads << Thread.new(ns) do |my_ns|
159       nameserver = my_ns.rdata.to_s
160       p "Domain #{domain}: Creating resolver object for checking propagation on #{nameserver}"
161       res = Dnsruby::Resolver.new(nameserver)
162       res.dnssec = false
163       res.do_caching = false
164       begin
165         p "Domain #{domain}: Querying ACME challenge record"
166         begin
167           result = res.query_no_validation_or_recursion("_acme-challenge.#{domain}", 'TXT')
168         rescue Dnsruby::NXDomain
169           p "Domain #{domain}: Not yet propagated, sleeping before checking again"
170           Thread.pass
171           sleep(0.1)
172           retry
173         rescue StandardError => e
174           warn "Domain #{domain}: ACME challenge lookup failed: #{e}"
175           raise
176         end
177         # p result
178         propagated = result.answer.any? do |answer|
179           answer.rdata[0] == challenge.record_content
180         end
181         unless propagated
182           p "Domain #{domain}: Not yet propagated, sleeping before checking again"
183           Thread.pass
184           sleep(0.1)
185         end
186       end until propagated
187     end
188   end
189
190   threads.each(&:join)
191 end
192
193 def wait_for_challenge_validation(challenge)
194   p 'Requesting validation of challenge'
195   begin
196     retries ||= 0
197     challenge.request_validation
198   rescue Acme::Client::Error::BadNonce
199     retries += 1
200     p 'Retrying because of invalid nonce.'
201     retry if retries <= 5
202   end
203
204   while challenge.status == 'pending'
205     p 'Sleeping because challenge validation is pending'
206     sleep(1)
207     p 'Checking again'
208     begin
209       retries ||= 0
210       challenge.reload
211     rescue Acme::Client::Error::BadNonce
212       retries += 1
213       p 'Retrying because of invalid nonce.'
214       retry if retries <= 5
215     end
216   end
217 end
218
219 def get_cert(order, cert_name, domains, domain_key)
220   path = "./certs/#{cert_name}/"
221   crt_file = "#{path}/cert.pem"
222   p "Cert #{cert_name}: Creating CSR object"
223   csr = Acme::Client::CertificateRequest.new(
224     private_key: domain_key,
225     names: domains,
226     subject: { common_name: domains[0] }
227   )
228   p "Cert #{cert_name}: Finalize cert order"
229   begin
230     retries ||= 0
231     order.reload
232   rescue Acme::Client::Error::BadNonce
233     retries += 1
234     p 'Retrying because of invalid nonce.'
235     retry if retries <= 5
236   end
237   begin
238     retries ||= 0
239     order.finalize(csr: csr)
240   rescue Acme::Client::Error::BadNonce
241     retries += 1
242     p 'Retrying because of invalid nonce.'
243     retry if retries <= 5
244   end
245   while order.status == 'processing'
246     p "Cert #{cert_name}: Sleep while order is processing"
247     sleep(1)
248     p "Cert #{cert_name}: Rechecking order status"
249     begin
250       retries ||= 0
251       order.reload
252     rescue Acme::Client::Error::BadNonce
253       retries += 1
254       p 'Retrying because of invalid nonce.'
255       retry if retries <= 5
256     end
257   end
258   # p "order status: #{order.status}"
259   # pp order
260   begin
261     retries ||= 0
262     cert = order.certificate
263   rescue Acme::Client::Error::BadNonce
264     retries += 1
265     p 'Retrying because of invalid nonce.'
266     retry if retries <= 5
267   end
268
269   p "Cert #{cert_name}: Writing cert"
270   cert_file = File.new(path + Time.now.to_i.to_s + ".crt", 'w')
271   cert_file.write(cert)
272   if File.symlink?(File.dirname(cert_file) + "/current.crt")
273     File.unlink(File.dirname(cert_file) + "/current.crt")
274     File.symlink(File.basename(cert_file), File.dirname(cert_file) + "/current.crt")
275   elsif File.file?(File.dirname(cert_file) + "/current.crt")
276     raise 'Could not place symlink for "current.crt" because that is already a normal file.'
277   end
278   return cert
279 end
280
281
282 config = read_config
283
284 cert_dir = config.dig('global', 'cert_dir') || './certs/'
285
286 ensure_cert_dir(cert_dir)
287
288 acme_threads = []
289 # iterate over configured certs
290 # TODO: make this one thread per cert
291 config['certs'].each_pair do |cert_name, cert_opts|
292   acme_threads << Thread.new(cert_name, cert_opts) do |cert_name, cert_opts|
293     ensure_cert_dir(cert_dir + cert_name)
294
295     p "Cert #{cert_name}: Finding CA to use for cert"
296     cert_ca = cert_opts['ca'] || config.dig('defaults', 'certs', 'ca')
297     cert_ca_name = cert_ca['name']
298     cert_ca_account = cert_ca['account']
299
300     p "Cert #{cert_name}: Finding directory URL for CA"
301     acme_directory_url = config.dig('CAs', cert_ca_name, 'directory_url')
302
303     p "Cert #{cert_name}: Finding account to use for cert #{cert_name} from CA #{cert_ca_name}"
304     account = config.dig('ca_accounts', cert_ca_account)
305     email = account['email']
306
307     private_key = read_account_key(account['keyfile'])
308
309     p "Cert #{cert_name}: Creating client object for communication with CA"
310     client = Acme::Client.new(private_key: private_key, directory: acme_directory_url)
311
312     begin
313       retries ||= 0
314       client.new_account(contact: "mailto:#{email}", terms_of_service_agreed: true)
315     rescue Acme::Client::Error::BadNonce
316       retries += 1
317       p 'Retrying because of invalid nonce.'
318       retry if retries <= 5
319     end
320
321     p "Cert #{cert_name}: Creating order object for cert #{cert_name}"
322     begin
323       retries ||= 0
324       order = client.new_order(identifiers: cert_opts['domain_names'])
325     rescue Acme::Client::Error::BadNonce
326       retries += 1
327       p 'Retrying because of invalid nonce.'
328       retry if retries <= 5
329     end
330
331     p "Cert #{cert_name}: order status"
332     p order.status
333
334     if order.status != 'ready'
335       p "Cert #{cert_name}: Order is not ready, we need to authorize first"
336
337       p "Cert #{cert_name}: Iterating over required authorizations"
338       begin
339         retries ||= 0
340         auths = order.authorizations
341       rescue Acme::Client::Error::BadNonce
342         retries += 1
343         p 'Retrying because of invalid nonce.'
344         retry if retries <= 5
345       end
346       auths.each do |auth|
347         p "Cert #{cert_name}: Processing authorization for #{auth.domain}"
348         p "Cert #{cert_name}: Finding challenge type for #{auth.domain}"
349         # p "Cert #{cert_name}: auth is:"
350         # pp auth
351         if auth.status == 'valid'
352           p "Cert #{cert_name}: Authorization for #{auth.domain} is still valid, skipping"
353           next
354         end
355
356         challenge = auth.dns01
357         primary_ns = config.dig('domains', auth.domain, 'primary_ns') || config.dig('defaults', 'domains', 'primary_ns')
358         deploy_dns01_challenge_token(auth.domain, challenge, primary_ns, config)
359         wait_for_challenge_propagation(auth.domain, challenge)
360         wait_for_challenge_validation(challenge)
361       end
362     else
363       p "Cert #{cert_name}: Order is ready, we don’t need to authorize"
364     end
365     domain_key = read_cert_key(cert_name)
366
367     get_cert(order, cert_name, cert_opts['domain_names'], domain_key)
368   end
369 end
370
371 acme_threads.each(&:join)