File: crypto_util_test.py

package info (click to toggle)
python-certbot 4.0.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,688 kB
  • sloc: python: 21,764; makefile: 182; sh: 108
file content (509 lines) | stat: -rw-r--r-- 18,812 bytes parent folder | download
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
"""Tests for certbot.crypto_util."""
import logging
import re
import sys
import unittest
from unittest import mock

import pytest
from cryptography import x509
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.hazmat.primitives.serialization import Encoding

from acme import crypto_util as acme_crypto_util
from certbot import errors
from certbot import util
from certbot.compat import filesystem
from certbot.compat import os
import certbot.tests.util as test_util

RSA512_KEY = test_util.load_vector('rsa512_key.pem')
RSA512_KEY_PATH = test_util.vector_path('rsa512_key.pem')
RSA2048_KEY = test_util.load_vector('rsa2048_key.pem')
RSA2048_KEY_PATH = test_util.vector_path('rsa2048_key.pem')
CERT_PATH = test_util.vector_path('cert_512.pem')
CERT = test_util.load_vector('cert_512.pem')
SS_CERT_PATH = test_util.vector_path('cert_2048.pem')
SS_CERT = test_util.load_vector('cert_2048.pem')
P256_KEY = test_util.load_vector('nistp256_key.pem')
P256_KEY_PATH = test_util.vector_path('nistp256_key.pem')
P256_CERT_PATH = test_util.vector_path('cert-nosans_nistp256.pem')
P256_CERT = test_util.load_vector('cert-nosans_nistp256.pem')
# CERT_LEAF is signed by CERT_ISSUER. CERT_ALT_ISSUER is a cross-sign of CERT_ISSUER.
CERT_LEAF = test_util.load_vector('cert_leaf.pem')
CERT_ISSUER = test_util.load_vector('cert_intermediate_1.pem')
CERT_ALT_ISSUER = test_util.load_vector('cert_intermediate_2.pem')


class GenerateKeyTest(test_util.TempDirTestCase):
    """Tests for certbot.crypto_util.generate_key."""
    def setUp(self):
        super().setUp()

        self.workdir = os.path.join(self.tempdir, 'workdir')
        filesystem.mkdir(self.workdir, mode=0o700)

        logging.disable(logging.CRITICAL)

    def tearDown(self):
        super().tearDown()

        logging.disable(logging.NOTSET)

    @classmethod
    def _call(cls, key_size, key_dir):
        from certbot.crypto_util import generate_key
        return generate_key(key_size, key_dir, 'key-certbot.pem', strict_permissions=True)

    @mock.patch('certbot.crypto_util.make_key')
    def test_success(self, mock_make):
        mock_make.return_value = b'key_pem'
        key = self._call(1024, self.workdir)
        assert key.pem == b'key_pem'
        assert 'key-certbot.pem' in key.file
        assert os.path.exists(os.path.join(self.workdir, key.file))

    @mock.patch('certbot.crypto_util.make_key')
    def test_key_failure(self, mock_make):
        mock_make.side_effect = ValueError
        with pytest.raises(ValueError):
            self._call(431, self.workdir)


class GenerateCSRTest(test_util.TempDirTestCase):
    """Tests for certbot.crypto_util.generate_csr."""
    @mock.patch('acme.crypto_util.make_csr')
    @mock.patch('certbot.crypto_util.util.make_or_verify_dir')
    def test_it(self, unused_mock_verify, mock_csr):
        from certbot.crypto_util import generate_csr

        mock_csr.return_value = b'csr_pem'

        csr = generate_csr(
            mock.Mock(pem='dummy_key'), 'example.com', self.tempdir, strict_permissions=True)

        assert csr.data == b'csr_pem'
        assert 'csr-certbot.pem' in csr.file


class ValidCSRTest(unittest.TestCase):
    """Tests for certbot.crypto_util.valid_csr."""

    @classmethod
    def _call(cls, csr):
        from certbot.crypto_util import valid_csr
        return valid_csr(csr)

    def test_valid_pem_true(self):
        assert self._call(test_util.load_vector('csr_512.pem'))

    def test_valid_pem_san_true(self):
        assert self._call(test_util.load_vector('csr-san_512.pem'))

    def test_valid_der_false(self):
        assert not self._call(test_util.load_vector('csr_512.der'))

    def test_empty_false(self):
        assert not self._call('')

    def test_random_false(self):
        assert not self._call('foo bar')


class CSRMatchesPubkeyTest(unittest.TestCase):
    """Tests for certbot.crypto_util.csr_matches_pubkey."""

    @classmethod
    def _call(cls, *args, **kwargs):
        from certbot.crypto_util import csr_matches_pubkey
        return csr_matches_pubkey(*args, **kwargs)

    def test_valid_true(self):
        assert self._call(
            test_util.load_vector('csr_512.pem'), RSA512_KEY)

    def test_invalid_false(self):
        assert not self._call(
            test_util.load_vector('csr_512.pem'), P256_KEY)


class ImportCSRFileTest(unittest.TestCase):
    """Tests for certbot.certbot_util.import_csr_file."""

    @classmethod
    def _call(cls, *args, **kwargs):
        from certbot.crypto_util import import_csr_file
        return import_csr_file(*args, **kwargs)

    def test_der_csr(self):
        csrfile = test_util.vector_path('csr_512.der')
        data = test_util.load_vector('csr_512.der')
        data_pem = test_util.load_vector('csr_512.pem')

        assert (acme_crypto_util.Format.PEM,
             util.CSR(file=csrfile,
                      data=data_pem,
                      form="pem"),
             ["Example.com"]) == \
            self._call(csrfile, data)

    def test_pem_csr(self):
        csrfile = test_util.vector_path('csr_512.pem')
        data = test_util.load_vector('csr_512.pem')

        assert (acme_crypto_util.Format.PEM,
             util.CSR(file=csrfile,
                      data=data,
                      form="pem"),
             ["Example.com"],) == \
            self._call(csrfile, data)

    def test_bad_csr(self):
        with pytest.raises(errors.Error):
            self._call(test_util.vector_path('cert_512.pem'),
                          test_util.load_vector('cert_512.pem'))


class MakeKeyTest(unittest.TestCase):
    """Tests for certbot.crypto_util.make_key."""

    def test_rsa(self):  # pylint: disable=no-self-use
        # RSA Key Type Test
        from certbot.crypto_util import make_key

        # Do not test larger keys as it takes too long.
        serialization.load_pem_private_key(make_key(2048), password=None)

    def test_ec(self):  # pylint: disable=no-self-use
        # ECDSA Key Type Tests
        from certbot.crypto_util import make_key

        for (name, bits) in [('secp256r1', 256), ('secp384r1', 384), ('secp521r1', 521)]:
            pkey = serialization.load_pem_private_key(
                make_key(elliptic_curve=name, key_type='ecdsa'),
                password=None
            )
            assert isinstance(pkey, ec.EllipticCurvePrivateKey)
            assert pkey.curve.key_size == bits

    def test_bad_key_sizes(self):
        from certbot.crypto_util import make_key

        # Try a bad key size for RSA and ECDSA
        with pytest.raises(errors.Error, match='Unsupported RSA key length: 1024'):
            make_key(bits=1024, key_type='rsa')

    def test_bad_elliptic_curve_name(self):
        from certbot.crypto_util import make_key
        with pytest.raises(errors.Error, match='Unsupported elliptic curve: nothere'):
            make_key(elliptic_curve="nothere", key_type='ecdsa')

    def test_bad_key_type(self):
        from certbot.crypto_util import make_key

        # Try a bad --key-type
        with pytest.raises(errors.Error,
                           match=re.escape('Invalid key_type specified: unf.  Use [rsa|ecdsa]')):
            make_key(2048, key_type='unf')

    def test_for_pkcs8_format(self):
        from certbot.crypto_util import make_key

        # PKCS#1 format will instead have text like "BEGIN RSA PRIVATE KEY" or "BEGIN EC PRIVATE
        # KEY"
        assert b"BEGIN PRIVATE KEY" in make_key(2048)
        assert b"BEGIN PRIVATE KEY" in make_key(elliptic_curve='secp256r1', key_type='ecdsa')


class VerifyCertSetup(unittest.TestCase):
    """Refactoring for verification tests."""

    def setUp(self):
        self.renewable_cert = mock.MagicMock()
        self.renewable_cert.cert_path = SS_CERT_PATH
        self.renewable_cert.chain_path = SS_CERT_PATH
        self.renewable_cert.key_path = RSA2048_KEY_PATH
        self.renewable_cert.fullchain_path = test_util.vector_path('cert_fullchain_2048.pem')

        self.bad_renewable_cert = mock.MagicMock()
        self.bad_renewable_cert.chain_path = SS_CERT_PATH
        self.bad_renewable_cert.cert_path = SS_CERT_PATH
        self.bad_renewable_cert.fullchain_path = SS_CERT_PATH


class VerifyRenewableCertTest(VerifyCertSetup):
    """Tests for certbot.crypto_util.verify_renewable_cert."""

    def _call(self, renewable_cert):
        from certbot.crypto_util import verify_renewable_cert
        return verify_renewable_cert(renewable_cert)

    def test_verify_renewable_cert(self):
        assert self._call(self.renewable_cert) is None

    @mock.patch('certbot.crypto_util.verify_renewable_cert_sig', side_effect=errors.Error(""))
    def test_verify_renewable_cert_failure(self, unused_verify_renewable_cert_sign):
        with pytest.raises(errors.Error):
            self._call(self.bad_renewable_cert)


class VerifyRenewableCertSigTest(VerifyCertSetup):
    """Tests for certbot.crypto_util.verify_renewable_cert."""

    def _call(self, renewable_cert):
        from certbot.crypto_util import verify_renewable_cert_sig
        return verify_renewable_cert_sig(renewable_cert)

    def test_cert_sig_match(self):
        assert self._call(self.renewable_cert) is None

    def test_cert_sig_match_ec(self):
        renewable_cert = mock.MagicMock()
        renewable_cert.cert_path = P256_CERT_PATH
        renewable_cert.chain_path = P256_CERT_PATH
        renewable_cert.key_path = P256_KEY
        assert self._call(renewable_cert) is None

    def test_cert_sig_mismatch(self):
        self.bad_renewable_cert.cert_path = test_util.vector_path('cert_512_bad.pem')
        with pytest.raises(errors.Error):
            self._call(self.bad_renewable_cert)


class VerifyFullchainTest(VerifyCertSetup):
    """Tests for certbot.crypto_util.verify_fullchain."""

    def _call(self, renewable_cert):
        from certbot.crypto_util import verify_fullchain
        return verify_fullchain(renewable_cert)

    def test_fullchain_matches(self):
        assert self._call(self.renewable_cert) is None

    def test_fullchain_mismatch(self):
        with pytest.raises(errors.Error):
            self._call(self.bad_renewable_cert)

    def test_fullchain_ioerror(self):
        self.bad_renewable_cert.chain = "dog"
        with pytest.raises(errors.Error):
            self._call(self.bad_renewable_cert)


class VerifyCertMatchesPrivKeyTest(VerifyCertSetup):
    """Tests for certbot.crypto_util.verify_cert_matches_priv_key."""

    def _call(self, renewable_cert):
        from certbot.crypto_util import verify_cert_matches_priv_key
        return verify_cert_matches_priv_key(renewable_cert.cert, renewable_cert.privkey)

    def test_cert_priv_key_match(self):
        self.renewable_cert.cert = SS_CERT_PATH
        self.renewable_cert.privkey = RSA2048_KEY_PATH
        assert self._call(self.renewable_cert) is None

    def test_cert_priv_key_mismatch(self):
        self.bad_renewable_cert.privkey = P256_KEY_PATH
        self.bad_renewable_cert.cert = SS_CERT_PATH

        with pytest.raises(errors.Error):
            self._call(self.bad_renewable_cert)


class ValidPrivkeyTest(unittest.TestCase):
    """Tests for certbot.crypto_util.valid_privkey."""

    @classmethod
    def _call(cls, privkey):
        from certbot.crypto_util import valid_privkey
        return valid_privkey(privkey)

    def test_valid_true(self):
        assert self._call(RSA512_KEY)

    def test_empty_false(self):
        assert not self._call('')

    def test_random_false(self):
        assert not self._call('foo bar')


class GetSANsFromCertTest(unittest.TestCase):
    """Tests for certbot.crypto_util.get_sans_from_cert."""

    @classmethod
    def _call(cls, *args, **kwargs):
        from certbot.crypto_util import get_sans_from_cert
        return get_sans_from_cert(*args, **kwargs)

    def test_single(self):
        assert [] == self._call(test_util.load_vector('cert_512.pem'))

    def test_san(self):
        assert ['example.com', 'www.example.com'] == \
            self._call(test_util.load_vector('cert-san_512.pem'))


class GetNamesFromCertTest(unittest.TestCase):
    """Tests for certbot.crypto_util.get_names_from_cert."""

    @classmethod
    def _call(cls, *args, **kwargs):
        from certbot.crypto_util import get_names_from_cert
        return get_names_from_cert(*args, **kwargs)

    def test_single(self):
        assert ['example.com'] == \
            self._call(test_util.load_vector('cert_512.pem'))

    def test_san(self):
        assert ['example.com', 'www.example.com'] == \
            self._call(test_util.load_vector('cert-san_512.pem'))

    def test_common_name_sans_order(self):
        # Tests that the common name comes first
        # followed by the SANS in alphabetical order
        assert ['example.com'] + ['{0}.example.com'.format(c) for c in 'abcd'] == \
            self._call(test_util.load_vector('cert-5sans_512.pem'))

    def test_parse_non_cert(self):
        with pytest.raises(ValueError):
            self._call(b"hello there")


class GetNamesFromReqTest(unittest.TestCase):
    """Tests for certbot.crypto_util.get_names_from_req."""

    @classmethod
    def _call(cls, *args, **kwargs):
        from certbot.crypto_util import get_names_from_req
        return get_names_from_req(*args, **kwargs)

    def test_nonames(self):
        assert [] == \
            self._call(test_util.load_vector('csr-nonames_512.pem'))

    def test_nosans(self):
        assert ['example.com'] == \
            self._call(test_util.load_vector('csr-nosans_512.pem'))

    def test_sans(self):
        assert ['example.com', 'example.org', 'example.net', 'example.info',
             'subdomain.example.com', 'other.subdomain.example.com'] == \
            self._call(test_util.load_vector('csr-6sans_512.pem'))

    def test_der(self):
        assert ['Example.com'] == \
            self._call(test_util.load_vector('csr_512.der'), typ=acme_crypto_util.Format.DER)


class NotBeforeTest(unittest.TestCase):
    """Tests for certbot.crypto_util.notBefore"""

    def test_notBefore(self):
        from certbot.crypto_util import notBefore
        assert notBefore(CERT_PATH).isoformat() == \
                         '2014-12-11T22:34:45+00:00'


class NotAfterTest(unittest.TestCase):
    """Tests for certbot.crypto_util.notAfter"""

    def test_notAfter(self):
        from certbot.crypto_util import notAfter
        assert notAfter(CERT_PATH).isoformat() == \
                         '2014-12-18T22:34:45+00:00'


class Sha256sumTest(unittest.TestCase):
    """Tests for certbot.crypto_util.notAfter"""
    def test_sha256sum(self):
        from certbot.crypto_util import sha256sum
        assert sha256sum(CERT_PATH) == \
            '914ffed8daf9e2c99d90ac95c77d54f32cbd556672facac380f0c063498df84e'


class CertAndChainFromFullchainTest(unittest.TestCase):
    """Tests for certbot.crypto_util.cert_and_chain_from_fullchain"""

    def _parse_and_reencode_pem(self, cert_pem:str)->str:
        cert = x509.load_pem_x509_certificate(cert_pem.encode())
        return cert.public_bytes(Encoding.PEM).decode()

    def test_cert_and_chain_from_fullchain(self):
        cert_pem: str = CERT.decode()
        chain_pem: str = cert_pem + SS_CERT.decode()
        fullchain_pem: str = cert_pem + chain_pem
        spacey_fullchain_pem: str = cert_pem + u'\n' + chain_pem
        crlf_fullchain_pem: str = fullchain_pem.replace(u'\n', u'\r\n')

        # In the ACME v1 code path, the fullchain is constructed by loading cert+chain DERs
        # and using OpenSSL to dump them, so here we confirm that cryptography is producing certs
        # that will be parseable by cert_and_chain_from_fullchain.
        acmev1_fullchain_pem = self._parse_and_reencode_pem(cert_pem) + \
            self._parse_and_reencode_pem(cert_pem) + self._parse_and_reencode_pem(SS_CERT.decode())

        from certbot.crypto_util import cert_and_chain_from_fullchain
        for fullchain in (fullchain_pem, spacey_fullchain_pem, crlf_fullchain_pem,
                          acmev1_fullchain_pem):
            cert_out, chain_out = cert_and_chain_from_fullchain(fullchain)
            assert cert_out == cert_pem
            assert chain_out == chain_pem

        with pytest.raises(errors.Error):
            cert_and_chain_from_fullchain(cert_pem)


class FindChainWithIssuerTest(unittest.TestCase):
    """Tests for certbot.crypto_util.find_chain_with_issuer"""

    @classmethod
    def _call(cls, fullchains, issuer_cn, **kwargs):
        from certbot.crypto_util import find_chain_with_issuer
        return find_chain_with_issuer(fullchains, issuer_cn, kwargs)

    def _all_fullchains(self):
        return [CERT_LEAF.decode() + CERT_ISSUER.decode(),
                CERT_LEAF.decode() + CERT_ALT_ISSUER.decode()]

    def test_positive_match(self):
        """Correctly pick the chain based on the root's CN"""
        fullchains = self._all_fullchains()
        matched = self._call(fullchains, "Pebble Root CA 0cc6f0")
        assert matched == fullchains[1]

    @mock.patch('certbot.crypto_util.logger.info')
    def test_intermediate_match(self, mock_info):
        """Don't pick a chain where only an intermediate matches"""
        fullchains = self._all_fullchains()
        # Make the second chain actually only contain "Pebble Root CA 0cc6f0"
        # as an intermediate, not as the root. This wouldn't be a valid chain
        # (the CERT_ISSUER cert didn't issue the CERT_ALT_ISSUER cert), but the
        # function under test here doesn't care about that.
        fullchains[1] = fullchains[1] + CERT_ISSUER.decode()
        matched = self._call(fullchains, "Pebble Root CA 0cc6f0")
        assert matched == fullchains[0]
        mock_info.assert_not_called()

    @mock.patch('certbot.crypto_util.logger.info')
    def test_no_match(self, mock_info):
        fullchains = self._all_fullchains()
        matched = self._call(fullchains, "non-existent issuer")
        assert matched == fullchains[0]
        mock_info.assert_not_called()

    @mock.patch('certbot.crypto_util.logger.warning')
    def test_warning_on_no_match(self, mock_warning):
        fullchains = self._all_fullchains()
        matched = self._call(fullchains, "non-existent issuer",
                             warn_on_no_match=True)
        assert matched == fullchains[0]
        mock_warning.assert_called_once_with("Certbot has been configured to prefer "
            "certificate chains with issuer '%s', but no chain from the CA matched "
            "this issuer. Using the default certificate chain instead.",
            "non-existent issuer")


if __name__ == '__main__':
    sys.exit(pytest.main(sys.argv[1:] + [__file__]))  # pragma: no cover