-
Notifications
You must be signed in to change notification settings - Fork 59
/
simp_le.py
executable file
·1542 lines (1246 loc) · 51.9 KB
/
simp_le.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
#
# Simple Let's Encrypt client.
#
# Copyright (C) 2015 Jakub Warmuz
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
"""Simple Let's Encrypt client."""
import abc
import argparse
import collections
import contextlib
import datetime
import doctest
import hashlib
import errno
import logging
import os
import re
import shlex
import shutil
import subprocess
import sys
import tempfile
import time
import traceback
import unittest
import six
from six.moves import zip # pylint: disable=redefined-builtin
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
import mock
import OpenSSL
import pytz
import requests
from acme import client as acme_client
from acme import crypto_util
from acme import challenges
from acme import errors as acme_errors
from acme import jose
from acme import messages
# pylint: disable=too-many-lines
logger = logging.getLogger(__name__) # pylint: disable=invalid-name
VERSION = '0'
URL = 'https://github.com/kuba/simp_le'
LE_PRODUCTION_URI = 'https://acme-v01.api.letsencrypt.org/directory'
# https://letsencrypt.org/2015/11/09/why-90-days.html
LE_CERT_VALIDITY = 90 * 24 * 60 * 60
DEFAULT_VALID_MIN = LE_CERT_VALIDITY / 3
EXIT_RENEWAL = EXIT_TESTS_OK = EXIT_REVOKE_OK = EXIT_HELP_VERSION_OK = 0
EXIT_NO_RENEWAL = 1
EXIT_ERROR = 2
class Error(Exception):
"""simp_le error."""
class UnitTestCase(unittest.TestCase):
"""simp_le unit test case."""
class AssertRaisesContext(object):
"""Context for assert_raises."""
# pylint: disable=too-few-public-methods
def __init__(self):
self.error = None
@contextlib.contextmanager
def assert_raises(self, exc):
"""Assert raises context manager."""
context = self.AssertRaisesContext()
try:
yield context
except exc as error:
context.error = error
else:
self.fail('Expected exception (%s) not raised' % exc)
def assert_raises_regexp(self, exc, regexp, func, *args, **kwargs):
"""Assert raises that tests exception message against regexp."""
with self.assert_raises(exc) as context:
func(*args, **kwargs)
msg = str(context.error)
self.assertTrue(re.match(regexp, msg) is not None,
"Exception message (%s) doesn't match "
"regexp (%s)" % (msg, regexp))
def assert_raises_error(self, *args, **kwargs):
"""Assert raises simp_le error with given message."""
self.assert_raises_regexp(Error, *args, **kwargs)
_PEM_RE_LABELCHAR = r'[\x21-\x2c\x2e-\x7e]'
_PEM_RE = re.compile(
(r"""
^-----BEGIN\ ((?:%s(?:[- ]?%s)*)?)\s*-----$
.*?
^-----END\ \1-----\s*""" % (_PEM_RE_LABELCHAR, _PEM_RE_LABELCHAR)).encode(),
re.DOTALL | re.MULTILINE | re.VERBOSE)
_PEMS_SEP = b'\n'
def split_pems(buf):
r"""Split buffer comprised of PEM encoded (RFC 7468).
>>> x = b'\n-----BEGIN FOO BAR-----\nfoo\nbar\n-----END FOO BAR-----'
>>> len(list(split_pems(x * 3)))
3
>>> list(split_pems(b''))
[]
"""
for match in _PEM_RE.finditer(buf):
yield match.group(0)
def gen_pkey(bits):
"""Generate a private key.
>>> gen_pkey(1024)
<OpenSSL.crypto.PKey object at 0x...>
Args:
bits: Bit size of the key.
Returns:
Freshly generated private key.
"""
assert bits >= 1024 # XXX
pkey = OpenSSL.crypto.PKey()
pkey.generate_key(OpenSSL.crypto.TYPE_RSA, bits)
return pkey
def gen_csr(pkey, domains, sig_hash='sha256'):
"""Generate a CSR.
>>> [str(domain) for domain in crypto_util._pyopenssl_cert_or_req_san(
... gen_csr(gen_pkey(1024), [b'example.com', b'example.net']))]
['example.com', 'example.net']
Args:
pkey: Private key.
domains: List of domains included in the cert.
sig_hash: Hash used to sign the CSR.
Returns:
Generated CSR.
"""
assert domains, 'Must provide one or more hostnames for the CSR.'
req = OpenSSL.crypto.X509Req()
req.add_extensions([
OpenSSL.crypto.X509Extension(
b'subjectAltName',
critical=False,
value=b', '.join(b'DNS:' + d for d in domains)
),
])
req.set_pubkey(pkey)
# pre-1.0.2 version of OpenSSL the generated CSR will contain a
# zero-length Version field which will cause some strict parsers
# (e.g. the one in Golang, used by Boulder) to fail.
req.set_version(2)
req.sign(pkey, sig_hash)
return req
class ComparablePKey(object): # pylint: disable=too-few-public-methods
"""Comparable key.
Suppose you have the following keys with the same material:
>>> pem = OpenSSL.crypto.dump_privatekey(
... OpenSSL.crypto.FILETYPE_PEM, gen_pkey(1024))
>>> k1 = OpenSSL.crypto.load_privatekey(OpenSSL.crypto.FILETYPE_PEM, pem)
>>> k2 = OpenSSL.crypto.load_privatekey(OpenSSL.crypto.FILETYPE_PEM, pem)
Unfortunately, in pyOpenSSL, equality is not well defined:
>>> k1 == k2
False
Using `ComparablePKey` you get the equality relation right:
>>> ck1, ck2 = ComparablePKey(k1), ComparablePKey(k2)
>>> other_ckey = ComparablePKey(gen_pkey(1024))
>>> ck1 == ck2
True
>>> ck1 == k1
False
>>> k1 == ck1
False
>>> other_ckey == ck1
False
Non-equalty is also well defined:
>>> ck1 != ck2
False
>>> ck1 != k1
True
>>> k1 != ck1
True
>>> k1 != other_ckey
True
>>> other_ckey != ck1
True
Wrapepd key is available as well:
>>> ck1.wrapped is k1
True
Internal implementation is not optimized for performance!
"""
def __init__(self, wrapped):
self.wrapped = wrapped
def __ne__(self, other):
return not self == other # pylint: disable=unneeded-not
def _dump(self):
return OpenSSL.crypto.dump_privatekey(
OpenSSL.crypto.FILETYPE_ASN1, self.wrapped)
def __eq__(self, other):
if not isinstance(other, self.__class__):
return NotImplemented
# pylint: disable=protected-access
return self._dump() == other._dump()
class Vhost(collections.namedtuple('Vhost', 'name root')):
"""Vhost: domain name and public html root."""
_SEP = ':'
@classmethod
def decode(cls, data):
"""Decode vhost.
>>> Vhost.decode('example.com')
Vhost(name='example.com', root=None)
>>> Vhost.decode('example.com:/var/www/html')
Vhost(name='example.com', root='/var/www/html')
>>> Vhost.decode(Vhost(name='example.com', root=None))
Vhost(name='example.com', root=None)
"""
if isinstance(data, cls):
return data
parts = data.split(cls._SEP, 1)
parts.append(None)
return cls(name=parts[0], root=parts[1])
class IOPlugin(object):
"""Input/output plugin.
In case of any problems, `persisted`, `load` and `save`
methods should raise `Error`, for which message will be
displayed directly to the user through STDERR (in `main`).
"""
__metaclass__ = abc.ABCMeta
Data = collections.namedtuple('IOPluginData', 'account_key key cert chain')
"""Plugin data.
Unless otherwise stated, plugin data components are typically
filled with the following data:
- for `account_key`: private account key, an instance of `acme.jose.JWK`
- for `key`: private key, an instance of `OpenSSL.crypto.PKey`
- for `cert`: certificate, an instance of `OpenSSL.crypto.X509`
- for `chain`: certificate chain, a list of `OpenSSL.crypto.X509` instances
"""
EMPTY_DATA = Data(account_key=None, key=None, cert=None, chain=None)
def __init__(self, path, **dummy_kwargs):
self.path = path
@abc.abstractmethod
def persisted(self):
"""Which data is persisted by this plugin?
This method must be overridden in subclasses and must return
`IOPlugin.Data` with Boolean values indicating whether specific
component is persisted by the plugin.
"""
raise NotImplementedError()
@abc.abstractmethod
def load(self):
"""Load persisted data.
This method must be overridden in subclasses and must return
`IOPlugin.Data`. For all non-persisted data it must set the
corresponding component to `None`. If the data was not persisted
previously, it must return `EMPTY_DATA` (note that it does not
make sense for the plugin to set subset of the persisted
components to not-None: this would mean that data was persisted
only partially - if possible plugin should detect such condition
and throw an `Error`).
"""
raise NotImplementedError()
@abc.abstractmethod
def save(self, data):
"""Save data to file system.
This method must be overridden in subclasses and must accept
`IOPlugin.Data`. It must store all persisted components and
ignore all non-persisted components. It is guaranteed that all
persisted components are not `None`.
"""
raise NotImplementedError()
# Plugin registration magic
registered = {}
@classmethod
def register(cls, **kwargs):
"""Register IO plugin."""
def init_and_reg(plugin_cls):
"""Initialize plugin class and register."""
plugin = plugin_cls(**kwargs)
assert (os.path.sep not in plugin.path and
plugin.path not in ('.', '..'))
cls.registered[plugin.path] = plugin
return plugin_cls
return init_and_reg
class FileIOPlugin(IOPlugin):
"""Plugin that saves/reads files on disk."""
READ_MODE = 'rb'
WRITE_MODE = 'wb'
def load(self):
logger.debug('Loading %s', self.path)
try:
with open(self.path, self.READ_MODE) as persist_file:
content = persist_file.read()
except IOError as error:
if error.errno == errno.ENOENT:
# file does not exist, so it was not persisted
# previously
return self.EMPTY_DATA
raise
return self.load_from_content(content)
@abc.abstractmethod
def load_from_content(self, content):
"""Load from file contents.
This method must be overridden in subclasses. It will be called
with the contents of the file read from `path` and should return
whatever `IOPlugin.load` is meant to return.
"""
raise NotImplementedError()
def save_to_file(self, data):
"""Save data to file."""
logger.info('Saving %s', self.path)
try:
with open(self.path, self.WRITE_MODE) as persist_file:
persist_file.write(data)
except OSError as error:
logging.exception(error)
raise Error('Error when saving %s', self.path)
class JWKIOPlugin(IOPlugin): # pylint: disable=abstract-method
"""IO Plugin that uses JWKs."""
@classmethod
def load_jwk(cls, data):
"""Load JWK."""
return jose.JWKRSA.json_loads(data)
@classmethod
def dump_jwk(cls, jwk):
"""Dump JWK."""
return jwk.json_dumps()
@IOPlugin.register(path='account_key.json')
class AccountKey(FileIOPlugin, JWKIOPlugin):
"""Account key IO Plugin using JWS."""
# this is not a binary file
READ_MODE = 'r'
WRITE_MODE = 'w'
def persisted(self):
return self.Data(account_key=True, key=False, cert=False, chain=False)
def load_from_content(self, content):
return self.Data(account_key=self.load_jwk(content), key=None,
cert=None, chain=None)
def save(self, data):
return self.save_to_file(self.dump_jwk(data.account_key))
class OpenSSLIOPlugin(IOPlugin): # pylint: disable=abstract-method
"""IOPlugin that uses pyOpenSSL.
Args:
typ: One of `OpenSSL.crypto.FILETYPE_*`, used in loading/dumping.
"""
def __init__(self, typ=OpenSSL.crypto.FILETYPE_PEM, **kwargs):
self.typ = typ
super(OpenSSLIOPlugin, self).__init__(**kwargs)
def load_key(self, data):
"""Load private key."""
return ComparablePKey(OpenSSL.crypto.load_privatekey(self.typ, data))
def dump_key(self, data):
"""Dump private key."""
return OpenSSL.crypto.dump_privatekey(self.typ, data.wrapped).strip()
def load_cert(self, data):
"""Load certificate."""
return jose.ComparableX509(OpenSSL.crypto.load_certificate(
self.typ, data))
def dump_cert(self, data):
"""Dump certificate."""
return OpenSSL.crypto.dump_certificate(self.typ, data.wrapped).strip()
def load_pem_jwk(data):
"""Load JWK encoded as PEM."""
return jose.JWKRSA(key=serialization.load_pem_private_key(
data, password=None, backend=default_backend()))
def dump_pem_jwk(data):
"""Dump JWK as PEM."""
return data.key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.TraditionalOpenSSL,
encryption_algorithm=serialization.NoEncryption(),
).strip()
@IOPlugin.register(path='external.sh', typ=OpenSSL.crypto.FILETYPE_PEM)
class ExternalIOPlugin(OpenSSLIOPlugin):
"""External IO Plugin.
This plugin executes script that complies with the
"persisted|load|save protocol":
- whenever the script is called with `persisted` as the first
argument, it should send to STDOUT a single line consisting of a
subset of three keywords: `account_key`, `key`, `cart`, `chain`
(in any order, separated by whitespace);
- whenever the script is called with `load` as the first argument it
shall write to STDOUT all persisted data as PEM encoded strings in
the following order: account_key, key, certificate, certificates
in the chain (from leaf to root). If some data is not persisted,
it must be skipped in the output;
- whenever the script is called with `save` as the first argument,
it should accept data from STDIN and persist it. Data is encoded
and ordered in the same way as in the `load` case.
"""
@property
def script(self):
"""Path to the script."""
return os.path.join('.', self.path)
def get_output_or_fail(self, command):
"""Get output or throw an exception in case of errors."""
try:
proc = subprocess.Popen(
[self.script, command], stdin=subprocess.PIPE,
stdout=subprocess.PIPE)
except (OSError, subprocess.CalledProcessError) as error:
raise Error('Failed to execute external script: %s' % error)
stdout, stderr = proc.communicate()
if stderr is not None:
logger.error('STDERR: %s', stderr)
if proc.wait():
raise Error('External script exited with non-zero code: %d' %
proc.returncode)
# Do NOT log `stdout` as it might contain secret material (in
# case key is persisted)
return stdout
def persisted(self):
"""Call the external script and see which data is persisted."""
output = self.get_output_or_fail('persisted').split()
return self.Data(
account_key=(b'account_key' in output),
key=(b'key' in output),
cert=(b'cert' in output),
chain=(b'chain' in output),
)
def load(self):
"""Call the external script to retrieve persisted data."""
pems = list(split_pems(self.get_output_or_fail('load')))
if not pems:
return self.EMPTY_DATA
persisted = self.persisted()
account_key = load_pem_jwk(
pems.pop(0)) if persisted.account_key else None
key = self.load_key(pems.pop(0)) if persisted.key else None
cert = self.load_cert(pems.pop(0)) if persisted.cert else None
chain = ([self.load_cert(cert_data) for cert_data in pems]
if persisted.chain else None)
return self.Data(account_key=account_key, key=key,
cert=cert, chain=chain)
def save(self, data):
"""Call the external script and send data to be persisted to STDIN."""
persisted = self.persisted()
output = []
if persisted.account_key:
output.append(dump_pem_jwk(data.account_key))
if persisted.key:
output.append(self.dump_key(data.key))
if persisted.cert:
output.append(self.dump_cert(data.cert))
if persisted.chain:
output.extend(self.dump_cert(cert) for cert in data.chain)
logger.info('Calling `%s save` and piping data through', self.script)
try:
proc = subprocess.Popen(
[self.script, 'save'], stdin=subprocess.PIPE,
stdout=subprocess.PIPE)
except OSError as error:
logger.exception(error)
raise Error(
'There was a problem executing external IO plugin script')
stdout, stderr = proc.communicate(_PEMS_SEP.join(output))
if stdout is not None:
logger.debug('STDOUT: %s', stdout)
if stderr is not None:
logger.error('STDERR: %s', stderr)
if proc.wait():
raise Error('External script exited with non-zero code: %d' %
proc.returncode)
class PluginIOTestMixin(object):
"""Common plugins tests."""
# this is a test suite | pylint: disable=missing-docstring
PLUGIN_CLS = NotImplemented
def __init__(self, *args, **kwargs):
super(PluginIOTestMixin, self).__init__(*args, **kwargs)
raw_key = gen_pkey(1024)
self.all_data = IOPlugin.Data(
account_key=jose.JWKRSA(key=rsa.generate_private_key(
public_exponent=65537, key_size=1024,
backend=default_backend(),
)),
key=ComparablePKey(raw_key),
cert=jose.ComparableX509(crypto_util.gen_ss_cert(raw_key, ['a'])),
chain=[
jose.ComparableX509(crypto_util.gen_ss_cert(raw_key, ['b'])),
jose.ComparableX509(crypto_util.gen_ss_cert(raw_key, ['c'])),
],
)
self.key_data = IOPlugin.EMPTY_DATA._replace(key=self.all_data.key)
def setUp(self): # pylint: disable=invalid-name
self.root = tempfile.mkdtemp()
self.path = os.path.join(self.root, 'plugin')
# pylint: disable=not-callable
self.plugin = self.PLUGIN_CLS(path=self.path)
def tearDown(self): # pylint: disable=invalid-name
shutil.rmtree(self.root)
class FileIOPluginTestMixin(PluginIOTestMixin):
"""Common FileIO plugins tests."""
# this is a test suite | pylint: disable=missing-docstring
def test_empty(self):
self.assertEqual(IOPlugin.EMPTY_DATA, self.plugin.load())
def test_save_ignore_unpersisted(self):
self.plugin.save(self.all_data)
self.assertEqual(self.plugin.load(), IOPlugin.Data(
*(data if persist else None for persist, data in
zip(self.plugin.persisted(), self.all_data))))
class ExternalIOPluginTest(PluginIOTestMixin, UnitTestCase):
"""Tests for ExternalIOPlugin."""
# this is a test suite | pylint: disable=missing-docstring
PLUGIN_CLS = ExternalIOPlugin
def save_script(self, contents):
with open(self.path, 'w') as external_plugin_file:
external_plugin_file.write(contents)
os.chmod(self.path, 0o700)
def test_no_persisted_empty(self):
self.save_script('#!/bin/sh')
self.assertEqual(IOPlugin.EMPTY_DATA, self.plugin.load())
def test_missing_path_raises_error(self):
self.assert_raises_error(
'Failed to execute external script', self.plugin.load)
def test_load_nonzero_raises_error(self):
self.save_script('#!/bin/sh\nfalse')
self.assert_raises_error(
'.*exited with non-zero code: 1', self.plugin.load)
def test_save_nonzero_raises_error(self):
self.save_script('#!/bin/sh\nfalse')
self.assert_raises_error(
'.*exited with non-zero code: 1', self.plugin.save, self.key_data)
def one_file_script(self, persisted):
path = os.path.join(self.root, 'pem')
self.save_script("""\
#!/bin/sh
case $1 in
save) cat - > {path};;
load) [ ! -f {path} ] || cat {path};;
persisted) echo {persisted};;
esac
""".format(path=path, persisted=persisted))
return path
def test_it(self):
path = self.one_file_script('cert chain key account_key')
# not yet persisted
self.assertEqual(IOPlugin.EMPTY_DATA, self.plugin.load())
# save some data
self.plugin.save(self.all_data)
self.assertTrue(os.path.exists(path))
# loading should return the persisted data back in
self.assertEqual(self.all_data, self.plugin.load())
@IOPlugin.register(path='chain.pem', typ=OpenSSL.crypto.FILETYPE_PEM)
class ChainFile(FileIOPlugin, OpenSSLIOPlugin):
"""Certificate chain plugin."""
def persisted(self):
return self.Data(account_key=False, key=False, cert=False, chain=True)
def load_from_content(self, output):
chain = [self.load_cert(cert_data)
for cert_data in split_pems(output)]
return self.Data(account_key=None, key=None, cert=None, chain=chain)
def save(self, data):
return self.save_to_file(_PEMS_SEP.join(
self.dump_cert(chain_cert) for chain_cert in data.chain))
class ChainFileTest(FileIOPluginTestMixin, UnitTestCase):
"""Tests for ChainFile."""
# this is a test suite | pylint: disable=missing-docstring
PLUGIN_CLS = ChainFile
@IOPlugin.register(path='fullchain.pem', typ=OpenSSL.crypto.FILETYPE_PEM)
class FullChainFile(ChainFile):
"""Full chain file plugin."""
def persisted(self):
return self.Data(account_key=False, key=False, cert=True, chain=True)
def load(self):
data = super(FullChainFile, self).load()
if data.chain is None:
cert, chain = None, None
else:
cert, chain = data.chain[0], data.chain[1:]
return self.Data(account_key=data.account_key, key=data.key,
cert=cert, chain=chain)
def save(self, data):
return super(FullChainFile, self).save(self.Data(
account_key=data.account_key, key=data.key,
cert=None, chain=([data.cert] + data.chain)))
class FullChainFileTest(FileIOPluginTestMixin, UnitTestCase):
"""Tests for FullChainFile."""
# this is a test suite | pylint: disable=missing-docstring
PLUGIN_CLS = FullChainFile
@IOPlugin.register(path='key.der', typ=OpenSSL.crypto.FILETYPE_ASN1)
@IOPlugin.register(path='key.pem', typ=OpenSSL.crypto.FILETYPE_PEM)
class KeyFile(FileIOPlugin, OpenSSLIOPlugin):
"""Private key file plugin."""
def persisted(self):
return self.Data(account_key=False, key=True, cert=False, chain=False)
def load_from_content(self, output):
return self.Data(account_key=None, key=self.load_key(output),
cert=None, chain=None)
def save(self, data):
return self.save_to_file(self.dump_key(data.key))
class KeyFileTest(FileIOPluginTestMixin, UnitTestCase):
"""Tests for KeyFile."""
# this is a test suite | pylint: disable=missing-docstring
PLUGIN_CLS = KeyFile
@IOPlugin.register(path='cert.der', typ=OpenSSL.crypto.FILETYPE_ASN1)
@IOPlugin.register(path='cert.pem', typ=OpenSSL.crypto.FILETYPE_PEM)
class CertFile(FileIOPlugin, OpenSSLIOPlugin):
"""Certificate file plugin."""
def persisted(self):
return self.Data(account_key=False, key=False, cert=True, chain=False)
def load_from_content(self, output):
return self.Data(account_key=None, key=None,
cert=self.load_cert(output), chain=None)
def save(self, data):
return self.save_to_file(self.dump_cert(data.cert))
class CertFileTest(FileIOPluginTestMixin, UnitTestCase):
"""Tests for CertFile."""
# this is a test suite | pylint: disable=missing-docstring
PLUGIN_CLS = CertFile
@IOPlugin.register(path='full.pem', typ=OpenSSL.crypto.FILETYPE_PEM)
class FullFile(FileIOPlugin, OpenSSLIOPlugin):
"""Private key, certificate and chain plugin."""
def persisted(self):
return self.Data(account_key=False, key=True, cert=True, chain=True)
def load_from_content(self, content):
pems = split_pems(content)
return self.Data(
account_key=None,
key=self.load_key(next(pems)),
cert=self.load_cert(next(pems)),
chain=[self.load_cert(cert) for cert in pems],
)
def save(self, data):
pems = [self.dump_key(data.key), self.dump_cert(data.cert)]
pems.extend(self.dump_cert(cert) for cert in data.chain)
self.save_to_file(_PEMS_SEP.join(pems))
class FullFileTest(FileIOPluginTestMixin, UnitTestCase):
"""Tests for FullFile."""
# this is a test suite | pylint: disable=missing-docstring
PLUGIN_CLS = FullFile
def create_parser():
"""Create argument parser."""
parser = argparse.ArgumentParser(
description=__doc__.splitlines()[0],
usage=argparse.SUPPRESS, add_help=False,
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
epilog='See %s for more info.' % URL,
)
general = parser.add_argument_group()
general.add_argument(
'-v', '--verbose', action='store_true', default=False,
help='Increase verbosity of the logging.',
)
modes = parser.add_argument_group()
modes.add_argument(
'-h', '--help', action='store_true',
help='Show this help message and exit.',
)
modes.add_argument(
'--version', action='store_true',
help='Display version and exit.'
)
modes.add_argument(
'--revoke', action='store_true', default=False,
help='Revoke existing certificate')
modes.add_argument(
'--test', action='store_true', default=False,
help='Run tests and exit.',
)
modes.add_argument(
'--integration_test', action='store_true', default=False,
help='Run integration tests and exit.',
)
manager = parser.add_argument_group(
'Webroot manager', description='This client is just a '
'sophisticated manager for $webroot/' +
challenges.HTTP01.URI_ROOT_PATH + '. You can (optionally) '
'specify `--default_root`, and override per-vhost with '
'`-d example.com:/var/www/other_html` syntax.',
)
manager.add_argument(
'-d', '--vhost', dest='vhosts', action='append',
help='Domain name that will be included in the certificate. '
'Must be specified at least once.', metavar='DOMAIN:PATH',
type=Vhost.decode,
)
manager.add_argument(
'--default_root', help='Default webroot path.', metavar='PATH',
)
io_group = parser.add_argument_group('Certificate data files')
io_group.add_argument(
'-f', dest='ioplugins', action='append', default=[],
metavar='PLUGIN', choices=sorted(IOPlugin.registered),
help='Input/output plugin of choice, can be specified multiple '
'times and, in fact, it should be specified as many times as it '
'is necessary to cover all components: key, certificate, chain. '
'Allowed values: %s.' % ', '.join(sorted(IOPlugin.registered)),
)
io_group.add_argument(
'--cert_key_size', type=int, default=4096, metavar='BITS',
help='Certificate key size. Fresh key is created for each renewal.',
)
io_group.add_argument(
'--valid_min', type=int, default=DEFAULT_VALID_MIN, metavar='SECONDS',
help='Minimum validity of the resulting certificate.',
)
io_group.add_argument(
'--reuse_key', action='store_true', default=False,
help='Reuse private key if it was previously persisted.',
)
reg = parser.add_argument_group(
'Registration', description='This client will automatically '
'register an account with the ACME CA specified by `--server`.'
)
reg.add_argument(
'--account_key_public_exponent', type=int, default=65537,
metavar='BITS', help='Account key public exponent value.',
)
reg.add_argument(
'--account_key_size', type=int, default=4096, metavar='BITS',
help='Account key size in bits.',
)
reg.add_argument(
'--tos_sha256', help='SHA-256 hash of the contents of Terms Of '
'Service URI contents.', default='33d233c8ab558ba6c8ebc370a509a'
'cdded8b80e5d587aa5d192193f35226540f', metavar='HASH',
)
reg.add_argument(
'--email', help='Email address. CA is likely to use it to '
'remind about expiring certificates, as well as for account '
'recovery. Therefore, it\'s highly recommended to set this '
'value.',
)
http = parser.add_argument_group(
'HTTP', description='Configure properties of HTTP requests and '
'responses.',
)
http.add_argument(
'--user_agent', default=('simp_le/' + VERSION), metavar='NAME',
help='User-Agent sent in all HTTP requests. Override with '
'--user_agent "" if you want to protect your privacy.',
)
http.add_argument(
'--server', metavar='URI', default=LE_PRODUCTION_URI,
help='Directory URI for the CA ACME API endpoint.',
)
return parser
def supported_challb(authorization):
"""Find supported challenge body.
This plugin supports only `http-01`, so CA must offer it as a
single-element combo. If this is not the case this function returns
`None`.
Returns:
`acme.messages.ChallengeBody` with `http-01` challenge or `None`.
"""
for combo in authorization.body.combinations:
first_challb = authorization.body.challenges[combo[0]]
if len(combo) == 1 and isinstance(
first_challb.chall, challenges.HTTP01):
return first_challb
return None
def compute_roots(vhosts, default_root):
"""Compute webroots.
Args:
vhosts: collection of `Vhost` objects.
default_root: Default webroot path.
Returns:
Dictionary mapping vhost name to its webroot path. Vhosts without
a root will be pre-populated with the `default_root`.
"""
roots = {}
for vhost in vhosts:
if vhost.root is not None:
root = vhost.root
else:
root = default_root
roots[vhost.name] = root
empty_roots = dict((name, root)
for name, root in six.iteritems(roots) if root is None)
if empty_roots:
raise Error('Root for the following host(s) were not specified: %s. '
'Try --default_root or use -d example.com:/var/www/html '
'syntax' % ', '.join(empty_roots))
return roots
def save_validation(root, challb, validation):
"""Save validation to webroot.
Args:
root: Webroot path.
challb: `acme.messages.ChallengeBody` with `http-01` challenge.
validation: `http-01` validation
"""
try:
os.makedirs(os.path.join(root, challb.URI_ROOT_PATH))
except OSError as error:
if error.errno != errno.EEXIST:
# directory doesn't already exist and we cannot create it
raise
path = os.path.join(root, challb.path[1:])
with open(path, 'w') as validation_file:
logger.debug('Saving validation (%r) at %s', validation, path)
validation_file.write(validation)
def sha256_of_uri_contents(uri, chunk_size=10):
"""Get SHA256 of URI contents.
>>> with mock.patch('requests.get') as mock_get:
... sha256_of_uri_contents('https://example.com')
'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'
"""
h = hashlib.sha256() # pylint: disable=invalid-name
response = requests.get(uri, stream=True)
for chunk in response.iter_content(chunk_size):
h.update(chunk)
return h.hexdigest()