Debian Codegraph @

src/pem/twisted.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2
3 """
4 Twisted-specific convenience helpers.
5 """
6
7 from __future__ import absolute_import, division, print_function
8
9 from OpenSSL.SSL import FILETYPE_PEM
10 from twisted.internet import ssl
11
12 from ._core import Certificate, DHParameters, Key, parse_file
13
14
15 # mypy hack: Import typing information without actually importing anything.
16 MYPY = False
17 if MYPY: # pragma: nocover
18 from ._core import AbstractPEMObject # noqa
19 from typing import List, Any # noqa
20
21
22 def certificateOptionsFromPEMs(pemObjects, **kw):
23 # type: (List[AbstractPEMObject], **Any) -> ssl.CerticateOptions
24 """
25 Load a CertificateOptions from the given collection of PEM objects
26 (already-loaded private keys and certificates).
27
28 In those PEM objects, identify one private key and its corresponding
29 certificate to use as the primary certificate. Then use the rest of the
30 certificates found as chain certificates. Raise a ValueError if no
31 certificate matching a private key is found.
32
33 :return: A TLS context factory using *pemObjects*
34 :rtype: `twisted.internet.ssl.CertificateOptions`_
35
36 .. _`twisted.internet.ssl.CertificateOptions`: \
37 https://twistedmatrix.com/documents/current/api/\
38 twisted.internet.ssl.CertificateOptions.html
39 """
40 keys = [key for key in pemObjects if isinstance(key, Key)]
41 if not len(keys):
42 raise ValueError("Supplied PEM file(s) does *not* contain a key.")
43 if len(keys) > 1:
44 raise ValueError("Supplied PEM file(s) contains *more* than one key.")
45
46 privateKey = ssl.KeyPair.load(str(keys[0]), FILETYPE_PEM)
47
48 certs = [cert for cert in pemObjects if isinstance(cert, Certificate)]
49 if not len(certs):
50 raise ValueError("*At least one* certificate is required.")
51 certificates = [ssl.Certificate.loadPEM(str(certPEM)) for certPEM in certs]
52
53 certificatesByFingerprint = dict(
54 [
55 (certificate.getPublicKey().keyHash(), certificate)
56 for certificate in certificates
57 ]
58 )
59
60 if privateKey.keyHash() not in certificatesByFingerprint:
61 raise ValueError(
62 "No certificate matching {fingerprint} found.".format(
63 fingerprint=privateKey.keyHash()
64 )
65 )
66
67 primaryCertificate = certificatesByFingerprint.pop(privateKey.keyHash())
68
69 if "dhParameters" in kw:
70 raise TypeError(
71 "Passing DH parameters as a keyword argument instead of a "
72 "PEM object is not supported anymore."
73 )
74
75 dhparams = [o for o in pemObjects if isinstance(o, DHParameters)]
76 if len(dhparams) > 1:
77 raise ValueError(
78 "Supplied PEM file(s) contain(s) *more* than one set of DH "
79 "parameters."
80 )
81 elif len(dhparams) == 1:
82 kw["dhParameters"] = ssl.DiffieHellmanParameters(str(dhparams[0]))
83
84 ctxFactory = ssl.CertificateOptions(
85 privateKey=privateKey.original,
86 certificate=primaryCertificate.original,
87 extraCertChain=[
88 chain.original for chain in certificatesByFingerprint.values()
89 ],
90 **kw
91 )
92
93 return ctxFactory
94
95
96 def certificateOptionsFromFiles(*pemFiles, **kw):
97 # type: (*str, **Any) -> ssl.CertificateOptions
98 """
99 Read all files named by *pemFiles*, and parse them using
100 :func:`certificateOptionsFromPEMs`.
101 """
102 pems = [] # type: List[AbstractPEMObject]
103 for pemFile in pemFiles:
104 pems += parse_file(pemFile)
105
106 return certificateOptionsFromPEMs(pems, **kw)