Debian Codegraph @

tests/test_module.py

raw
1 import os
2 import sys
3 import json
4 import time
5 import shutil
6 import logging
7 import unittest
8 import tempfile
9 from subprocess import Popen, PIPE
10
11 try:
12 from urllib.request import urlopen, Request # Python 3
13 except ImportError: # pragma: no cover
14 from urllib2 import urlopen, Request # Python 2
15
16 try:
17 from StringIO import StringIO # Python 2
18 except ImportError: # pragma: no cover
19 from io import StringIO # Python 3
20
21 import acme_tiny
22 from . import utils
23
24 # test settings based on environmental variables
25 PEBBLE_BIN = os.getenv("ACME_TINY_PEBBLE_BIN") or "{}/go/bin/pebble".format(os.getenv("HOME")) # default pebble install path
26 DOMAIN = os.getenv("ACME_TINY_DOMAIN") or "local.gethttpsforfree.com" # default to domain that resolves to 127.0.0.1
27 USE_STAGING = bool(os.getenv("ACME_TINY_USE_STAGING")) # default to false
28 SSHFS_CHALLENGE_DIR = os.getenv("ACME_TINY_SSHFS_CHALLENGE_DIR") # default to None (only used if USE_STAGING is True)
29
30 class TestModule(unittest.TestCase):
31 """
32 Tests for acme_tiny.py functionality itself
33 """
34 def setUp(self):
35 """
36 Set up ACME server for each test (or use Let's Encrypt's staging server)
37 """
38 # create new account keys every test
39 self.KEYS = utils.gen_keys(DOMAIN)
40
41 # use Let's Encrypt staging server
42 if USE_STAGING: # pragma: no cover
43 os.unsetenv("SSL_CERT_FILE") # use the default ssl trust store
44 # config references
45 self.tempdir = SSHFS_CHALLENGE_DIR
46 self.check_port = "80"
47 self.DIR_URL = "https://acme-staging-v02.api.letsencrypt.org/directory"
48 # staging server errors
49 self.account_key_error = "certificate public key must be different than account key"
50 self.ca_issued_string = "(STAGING) Let's Encrypt"
51 self.bad_character_error = "Domain name contains an invalid character"
52
53 # default to using pebble server
54 else:
55 # config references
56 self.tempdir = None # generated below
57 self.DIR_URL = "https://localhost:14000/dir"
58 self._pebble_server, self._pebble_config = utils.setup_pebble(PEBBLE_BIN)
59 self.check_port = str(self._pebble_config['pebble']['httpPort'])
60 self._challenge_file_server, self._base_tempdir, self.tempdir = utils.setup_local_fileserver(self.check_port, pebble_proc=self._pebble_server)
61 # pebble server errors
62 self.account_key_error = "CSR contains a public key for a known account"
63 self.ca_issued_string = "Pebble Intermediate CA"
64 self.bad_character_error = "Order included DNS identifier with a value containing an illegal character"
65
66 def tearDown(self):
67 """
68 Shut down sub processes (pebble, etc.)
69 """
70 # only need to shut down stuff if using local servers (pebble)
71 if not USE_STAGING:
72
73 self._pebble_server.terminate()
74 self._pebble_server.wait()
75 os.remove(self._pebble_config['pebble']['certificate'])
76 os.remove(self._pebble_config['pebble']['privateKey'])
77
78 self._challenge_file_server.terminate()
79 self._challenge_file_server.wait()
80 shutil.rmtree(self._base_tempdir)
81
82 def test_module_linecount(self):
83 """ This project is supposed to remain under 200 lines """
84 test_dir = os.path.dirname(os.path.realpath(__file__))
85 module_path = os.path.abspath(os.path.join(test_dir, os.pardir, "acme_tiny.py"))
86 out, err = Popen(["wc", "-l", module_path], stdout=PIPE, stderr=PIPE).communicate()
87 num_lines = int(out.decode("utf8").split(" ", 1)[0])
88 self.assertTrue(num_lines <= 200)
89
90 def test_success_domain(self):
91 """ Successfully issue a certificate via subject alt name """
92 old_stdout = sys.stdout
93 sys.stdout = StringIO()
94 result = acme_tiny.main([
95 "--account-key", self.KEYS['account_key'].name,
96 "--csr", self.KEYS['domain_csr'].name,
97 "--acme-dir", self.tempdir,
98 "--directory-url", self.DIR_URL,
99 "--check-port", self.check_port,
100 ])
101 sys.stdout.seek(0)
102 crt = sys.stdout.read().encode("utf8")
103 sys.stdout = old_stdout
104 out, err = Popen(["openssl", "x509", "-text", "-noout"], stdin=PIPE, stdout=PIPE, stderr=PIPE).communicate(crt)
105 self.assertIn(self.ca_issued_string, out.decode("utf8"))
106
107 def test_skip_valid_authorizations(self):
108 """ Authorizations that are already valid should be skipped """
109 # issue a valid cert
110 self.test_success_domain()
111
112 # add a logging handler that captures the info log output
113 log_output = StringIO()
114 debug_handler = logging.StreamHandler(log_output)
115 acme_tiny.LOGGER.addHandler(debug_handler)
116
117 # issue the cert again, where challenges should already be valid
118 old_stdout = sys.stdout
119 sys.stdout = StringIO()
120 result = acme_tiny.main([
121 "--account-key", self.KEYS['account_key'].name,
122 "--csr", self.KEYS['domain_csr'].name,
123 "--acme-dir", self.tempdir,
124 "--directory-url", self.DIR_URL,
125 "--check-port", self.check_port,
126 ])
127 sys.stdout.seek(0)
128 crt = sys.stdout.read().encode("utf8")
129 sys.stdout = old_stdout
130 log_output.seek(0)
131 log_string = log_output.read().encode("utf8")
132
133 # remove logging capture
134 acme_tiny.LOGGER.removeHandler(debug_handler)
135
136 # should say the domain is already verified
137 self.assertIn("Already verified: {0}, skipping...".format(DOMAIN), log_string.decode("utf8"))
138
139 def test_success_cli(self):
140 """ Successfully issue a certificate via command line interface """
141 crt, err = Popen([
142 "python", "acme_tiny.py",
143 "--account-key", self.KEYS['account_key'].name,
144 "--csr", self.KEYS['domain_csr'].name,
145 "--acme-dir", self.tempdir,
146 "--directory-url", self.DIR_URL,
147 "--check-port", self.check_port,
148 ], stdout=PIPE, stderr=PIPE).communicate()
149 out, err = Popen(["openssl", "x509", "-text", "-noout"], stdin=PIPE, stdout=PIPE, stderr=PIPE).communicate(crt)
150 self.assertIn(self.ca_issued_string, out.decode("utf8"))
151
152 def test_missing_account_key(self):
153 """ OpenSSL throws an error when the account key is missing """
154 try:
155 result = acme_tiny.main([
156 "--account-key", "/foo/bar",
157 "--csr", self.KEYS['domain_csr'].name,
158 "--acme-dir", self.tempdir,
159 "--directory-url", self.DIR_URL,
160 "--check-port", self.check_port,
161 ])
162 except Exception as e:
163 result = e
164 self.assertIsInstance(result, IOError)
165 err_msgs = ["unable to load Private Key", "Could not open file or uri for loading private key"]
166 self.assertTrue(any(msg in result.args[0] for msg in err_msgs))
167
168 def test_missing_csr(self):
169 """ OpenSSL throws an error when the CSR is missing """
170 try:
171 result = acme_tiny.main([
172 "--account-key", self.KEYS['account_key'].name,
173 "--csr", "/foo/bar",
174 "--acme-dir", self.tempdir,
175 "--directory-url", self.DIR_URL,
176 "--check-port", self.check_port,
177 ])
178 except Exception as e:
179 result = e
180 self.assertIsInstance(result, IOError)
181 self.assertIn("Error loading /foo/bar", result.args[0])
182
183 def test_invalid_domain(self):
184 """ Let's Encrypt rejects invalid domains """
185 try:
186 result = acme_tiny.main([
187 "--account-key", self.KEYS['account_key'].name,
188 "--csr", self.KEYS['invalid_csr'].name,
189 "--acme-dir", self.tempdir,
190 "--directory-url", self.DIR_URL,
191 "--check-port", self.check_port,
192 ])
193 except Exception as e:
194 result = e
195 self.assertIsInstance(result, ValueError)
196 self.assertIn(self.bad_character_error, result.args[0])
197
198 def test_nonexistent_domain(self):
199 """ Should be unable verify a nonexistent domain """
200 try:
201 result = acme_tiny.main([
202 "--account-key", self.KEYS['account_key'].name,
203 "--csr", self.KEYS['nonexistent_csr'].name,
204 "--acme-dir", self.tempdir,
205 "--directory-url", self.DIR_URL,
206 "--check-port", self.check_port,
207 ])
208 except Exception as e:
209 result = e
210 self.assertIsInstance(result, ValueError)
211 self.assertIn("but couldn't download", result.args[0])
212
213 def test_account_key_domain(self):
214 """ Can't use the account key for the CSR """
215 try:
216 result = acme_tiny.main([
217 "--account-key", self.KEYS['account_key'].name,
218 "--csr", self.KEYS['account_csr'].name,
219 "--acme-dir", self.tempdir,
220 "--directory-url", self.DIR_URL,
221 "--check-port", self.check_port,
222 ])
223 except Exception as e:
224 result = e
225 self.assertIsInstance(result, ValueError)
226 self.assertIn(self.account_key_error, result.args[0])
227
228 def test_contact(self):
229 """ Make sure optional contact details can be set """
230 # add a logging handler that captures the info log output
231 log_output = StringIO()
232 debug_handler = logging.StreamHandler(log_output)
233 acme_tiny.LOGGER.addHandler(debug_handler)
234 # call acme_tiny with new contact details
235 old_stdout = sys.stdout
236 sys.stdout = StringIO()
237 result = acme_tiny.main([
238 "--account-key", self.KEYS['account_key'].name,
239 "--csr", self.KEYS['domain_csr'].name,
240 "--acme-dir", self.tempdir,
241 "--directory-url", self.DIR_URL,
242 "--check-port", self.check_port,
243 "--contact", "mailto:[email protected]", "mailto:[email protected]",
244 ])
245 sys.stdout.seek(0)
246 crt = sys.stdout.read().encode("utf8")
247 sys.stdout = old_stdout
248 log_output.seek(0)
249 log_string = log_output.read().encode("utf8")
250 # make sure the certificate was issued and the contact details were updated
251 out, err = Popen(["openssl", "x509", "-text", "-noout"], stdin=PIPE, stdout=PIPE, stderr=PIPE).communicate(crt)
252 self.assertIn(self.ca_issued_string, out.decode("utf8"))
253 self.assertTrue(( # can be in either order
254 "Updated contact details:\nmailto:[email protected]\nmailto:[email protected]" in log_string.decode("utf8")
255 or "Updated contact details:\nmailto:[email protected]\nmailto:[email protected]" in log_string.decode("utf8")
256 ))
257 # remove logging capture
258 acme_tiny.LOGGER.removeHandler(debug_handler)
259
260 def test_challenge_failure(self):
261 """ Raises error if challenge doesn't pass """
262 # man-in-the-middle ACME requests to modify valid challenges so we raise that exception
263 def urlopenMITM(*args, **kwargs):
264 resp = urlopenOriginal(*args, **kwargs)
265 resp._orig_read = resp.read()
266 # modify valid challenges and authorizations to invalid
267 try:
268 resp_json = json.loads(resp._orig_read.decode("utf8"))
269 if (
270 len(resp_json.get("challenges", [])) == 1
271 and resp_json['challenges'][0]['status'] == "valid"
272 and resp_json['status'] == "valid"
273 ):
274 resp_json['challenges'][0]['status'] = "invalid"
275 resp_json['status'] = "invalid"
276 resp._orig_read = json.dumps(resp_json).encode("utf8")
277 except ValueError:
278 pass
279 # serve up modified response when read
280 def multi_read():
281 return resp._orig_read
282 resp.read = multi_read
283 return resp
284
285 # call acme-tiny with MITM'd urlopen
286 urlopenOriginal = acme_tiny.urlopen
287 acme_tiny.urlopen = urlopenMITM
288 try:
289 acme_tiny.main([
290 "--account-key", self.KEYS['account_key'].name,
291 "--csr", self.KEYS['domain_csr'].name,
292 "--acme-dir", self.tempdir,
293 "--directory-url", self.DIR_URL,
294 "--check-port", self.check_port,
295 ])
296 except ValueError as e:
297 result = e
298 acme_tiny.urlopen = urlopenOriginal
299
300 # should raise error that challenge didn't pass
301 self.assertIn("Challenge did not pass for", result.args[0])
302
303 def test_malicious_challenge_token(self):
304 """ Raises error if malicious challenge token is provided by the CA """
305
306 # assume the CA wants to try to fool you into serving up your password file
307 malicious_token = "../../../../etc/passwd"
308 cleaned_token = "____________etc_passwd"
309
310 # man-in-the-middle ACME requests to modify the challenge token to something malicious
311 def urlopenMITM(*args, **kwargs):
312 resp = urlopenOriginal(*args, **kwargs)
313 resp._orig_read = resp.read()
314 try:
315 resp_json = json.loads(resp._orig_read.decode("utf8"))
316 if len([c for c in resp_json.get("challenges", []) if c['type'] == "http-01"]) == 1:
317 challenge = [c for c in resp_json['challenges'] if c['type'] == "http-01"][0]
318 challenge['token'] = malicious_token
319 resp._orig_read = json.dumps(resp_json).encode("utf8")
320 except ValueError:
321 pass
322 # serve up modified response when read
323 def multi_read():
324 return resp._orig_read
325 resp.read = multi_read
326 return resp
327
328 # call acme-tiny with MITM'd urlopen
329 urlopenOriginal = acme_tiny.urlopen
330 acme_tiny.urlopen = urlopenMITM
331 try:
332 acme_tiny.main([
333 "--account-key", self.KEYS['account_key'].name,
334 "--csr", self.KEYS['domain_csr'].name,
335 "--acme-dir", self.tempdir,
336 "--directory-url", self.DIR_URL,
337 "--check-port", self.check_port,
338 ])
339 except ValueError as e:
340 result = e
341 acme_tiny.urlopen = urlopenOriginal
342
343 # should raise error that challenge didn't pass
344 self.assertIn("Challenge did not pass for", result.args[0])
345
346 # challenge file actually saved as a cleaned version
347 resp = urlopen(Request("http://{0}:{1}/.well-known/acme-challenge/{2}".format(DOMAIN, self.check_port, cleaned_token)))
348 token_data = resp.read().decode("utf8")
349 self.assertIn(cleaned_token, token_data)
350
351 def test_order_failure(self):
352 """ Raises error if order doesn't complete """
353 # man-in-the-middle ACME requests to modify valid orders so we raise that exception
354 def urlopenMITM(*args, **kwargs):
355 resp = urlopenOriginal(*args, **kwargs)
356 resp._orig_read = resp.read()
357 # modify valid orders to invalid
358 try:
359 resp_json = json.loads(resp._orig_read.decode("utf8"))
360 if (
361 resp_json.get("finalize", None) is not None
362 and resp_json.get("status", None) == "valid"
363 ):
364 resp_json['status'] = "invalid"
365 resp._orig_read = json.dumps(resp_json).encode("utf8")
366 except ValueError:
367 pass
368 # serve up modified response when read
369 def multi_read():
370 return resp._orig_read
371 resp.read = multi_read
372 return resp
373
374 # call acme-tiny with MITM'd urlopen
375 urlopenOriginal = acme_tiny.urlopen
376 acme_tiny.urlopen = urlopenMITM
377 try:
378 acme_tiny.main([
379 "--account-key", self.KEYS['account_key'].name,
380 "--csr", self.KEYS['domain_csr'].name,
381 "--acme-dir", self.tempdir,
382 "--directory-url", self.DIR_URL,
383 "--check-port", self.check_port,
384 ])
385 except ValueError as e:
386 result = e
387 acme_tiny.urlopen = urlopenOriginal
388
389 # should raise error that challenge didn't pass
390 self.assertIn("Order failed", result.args[0])
391
392 ###########################
393 ## Pebble-specific tests ##
394 ###########################
395
396 @unittest.skipIf(USE_STAGING, "only checked on pebble server since staging can't have nonce retries set")
397 def test_nonce_retry(self):
398 """ Still works when lots of nonce retries """
399 # kill current pebble server
400 self._pebble_server.terminate()
401 self._pebble_server.wait()
402 os.remove(self._pebble_config['pebble']['certificate'])
403 os.remove(self._pebble_config['pebble']['privateKey'])
404 # restart with new bad nonce rate
405 self._pebble_server, self._pebble_config = utils.setup_pebble(PEBBLE_BIN, bad_nonces=90)
406 # normal success test
407 self.test_success_domain()
408
409 @unittest.skipIf(USE_STAGING, "only checked on pebble server since ")
410 def test_pebble_doesnt_support_cn_domains(self):
411 """ Test that pebble server doesn't support CN subject domains """
412 try:
413 result = acme_tiny.main([
414 "--account-key", self.KEYS['account_key'].name,
415 "--csr", self.KEYS['cn_csr'].name,
416 "--acme-dir", self.tempdir,
417 "--directory-url", self.DIR_URL,
418 "--check-port", self.check_port,
419 ])
420 except Exception as e:
421 result = e
422 self.assertIsInstance(result, ValueError)
423 self.assertIn("Order includes different number of DNSnames identifiers than CSR specifies", result.args[0])
424
425 ############################
426 ## Staging-specific tests ##
427 ############################
428
429 @unittest.skipIf((not USE_STAGING), "only checked on staging since pebble doesn't support CN names")
430 def test_success_cn(self): # pragma: no cover
431 """ Successfully issue a certificate via common name """
432 old_stdout = sys.stdout
433 sys.stdout = StringIO()
434 result = acme_tiny.main([
435 "--account-key", self.KEYS['account_key'].name,
436 "--csr", self.KEYS['cn_csr'].name,
437 "--acme-dir", self.tempdir,
438 "--directory-url", self.DIR_URL,
439 #"--check-port", self.check_port, # defaults to port 80 anyway, so test that the default works
440 ])
441 sys.stdout.seek(0)
442 crt = sys.stdout.read().encode("utf8")
443 sys.stdout = old_stdout
444 out, err = Popen(["openssl", "x509", "-text", "-noout"], stdin=PIPE, stdout=PIPE, stderr=PIPE).communicate(crt)
445 self.assertIn(self.ca_issued_string, out.decode("utf8"))
446
447 @unittest.skipIf((not USE_STAGING), "only checked on staging since pebble doesn't check for weak keys")
448 def test_weak_key(self): # pragma: no cover
449 """ Let's Encrypt rejects weak keys """
450 try:
451 result = acme_tiny.main([
452 "--account-key", self.KEYS['weak_key'].name,
453 "--csr", self.KEYS['domain_csr'].name,
454 "--acme-dir", self.tempdir,
455 "--directory-url", self.DIR_URL,
456 #"--check-port", self.check_port, # defaults to port 80 anyway, so test that the default works
457 ])
458 except Exception as e:
459 result = e
460 self.assertIsInstance(result, ValueError)
461 err_msgs = ["key too small", "key size not supported"]
462 self.assertTrue(any(msg in result.args[0] for msg in err_msgs))
463