Debian Codegraph @

src/nitrokey/trussed/_bootloader/lpc55_upload/crypto/certificate.py

raw
1 #!/usr/bin/env python
2 # -*- coding: UTF-8 -*-
3 #
4 # Copyright 2020-2024 NXP
5 #
6 # SPDX-License-Identifier: BSD-3-Clause
7 """Module for certificate management (generating certificate, validating certificate, chains)."""
8
9 from typing import Optional
10
11 from cryptography import x509
12 from cryptography.hazmat.primitives import hashes
13 from cryptography.hazmat.primitives.asymmetric import rsa
14
15 from ..crypto.hash import EnumHashAlgorithm
16 from ..crypto.keys import PublicKey, PublicKeyRsa
17 from ..crypto.types import (
18 SPSDKEncoding,
19 SPSDKExtensionOID,
20 SPSDKExtensions,
21 SPSDKName,
22 SPSDKVersion,
23 )
24 from ..exceptions import SPSDKError, SPSDKValueError
25 from ..utils.abstract import BaseClass
26 from ..utils.misc import align_block
27
28
29 class Certificate(BaseClass):
30 """SPSDK Certificate representation."""
31
32 def __init__(self, certificate: x509.Certificate) -> None:
33 """Constructor of SPSDK Certificate.
34
35 :param certificate: Cryptography Certificate representation.
36 """
37 assert isinstance(certificate, x509.Certificate)
38 self.cert = certificate
39
40 def export(self, encoding: SPSDKEncoding = SPSDKEncoding.NXP) -> bytes:
41 """Convert certificates into bytes.
42
43 :param encoding: encoding type
44 :return: certificate in bytes form
45 """
46 if encoding == SPSDKEncoding.NXP:
47 return align_block(self.export(SPSDKEncoding.DER), 4, "zeros")
48
49 return self.cert.public_bytes(SPSDKEncoding.get_cryptography_encodings(encoding))
50
51 def get_public_key(self) -> PublicKey:
52 """Get public keys from certificate.
53
54 :return: RSA public key
55 """
56 pub_key = self.cert.public_key()
57 if isinstance(pub_key, rsa.RSAPublicKey):
58 return PublicKeyRsa(pub_key)
59
60 raise SPSDKError(f"Unsupported Certificate public key: {type(pub_key)}")
61
62 @property
63 def version(self) -> SPSDKVersion:
64 """Returns the certificate version."""
65 return self.cert.version
66
67 @property
68 def signature(self) -> bytes:
69 """Returns the signature bytes."""
70 return self.cert.signature
71
72 @property
73 def tbs_certificate_bytes(self) -> bytes:
74 """Returns the tbsCertificate payload bytes as defined in RFC 5280."""
75 return self.cert.tbs_certificate_bytes
76
77 @property
78 def signature_hash_algorithm(self) -> Optional[hashes.HashAlgorithm]:
79 """Returns a HashAlgorithm corresponding to the type of the digest signed in the certificate."""
80 return self.cert.signature_hash_algorithm
81
82 @property
83 def extensions(self) -> SPSDKExtensions:
84 """Returns an Extensions object."""
85 return self.cert.extensions
86
87 @property
88 def issuer(self) -> SPSDKName:
89 """Returns the issuer name object."""
90 return self.cert.issuer
91
92 @property
93 def serial_number(self) -> int:
94 """Returns certificate serial number."""
95 return self.cert.serial_number
96
97 @property
98 def subject(self) -> SPSDKName:
99 """Returns the subject name object."""
100 return self.cert.subject
101
102 def validate(self, issuer_certificate: "Certificate") -> bool:
103 """Validate certificate.
104
105 :param issuer_certificate: Issuer's certificate
106 :raises SPSDKError: Unsupported key type in Certificate
107 :return: true/false whether certificate is valid or not
108 """
109 assert self.signature_hash_algorithm
110 return issuer_certificate.get_public_key().verify_signature(
111 self.signature,
112 self.tbs_certificate_bytes,
113 EnumHashAlgorithm.from_label(self.signature_hash_algorithm.name),
114 )
115
116 @property
117 def ca(self) -> bool:
118 """Check if CA flag is set in certificate.
119
120 :return: true/false depending whether ca flag is set or not
121 """
122 extension = self.extensions.get_extension_for_oid(SPSDKExtensionOID.BASIC_CONSTRAINTS)
123 return extension.value.ca # type: ignore # mypy can not handle property definition in cryptography
124
125 @property
126 def self_signed(self) -> bool:
127 """Indication whether the Certificate is self-signed."""
128 return self.validate(self)
129
130 @property
131 def raw_size(self) -> int:
132 """Raw size of the certificate."""
133 return len(self.export())
134
135 def public_key_hash(self, algorithm: EnumHashAlgorithm = EnumHashAlgorithm.SHA256) -> bytes:
136 """Get key hash.
137
138 :param algorithm: Used hash algorithm, defaults to sha256
139 :return: Key Hash
140 """
141 return self.get_public_key().key_hash(algorithm)
142
143 def __repr__(self) -> str:
144 """Text short representation about the Certificate."""
145 return f"Certificate, SN:{hex(self.cert.serial_number)}"
146
147 def __str__(self) -> str:
148 """Text information about the Certificate."""
149 not_valid_before = self.cert.not_valid_before.strftime("%d.%m.%Y (%H:%M:%S)")
150 not_valid_after = self.cert.not_valid_after.strftime("%d.%m.%Y (%H:%M:%S)")
151 nfo = ""
152 nfo += f" Certification Authority: {'YES' if self.ca else 'NO'}\n"
153 nfo += f" Serial Number: {hex(self.cert.serial_number)}\n"
154 nfo += f" Validity Range: {not_valid_before} - {not_valid_after}\n"
155 if self.signature_hash_algorithm:
156 nfo += f" Signature Algorithm: {self.signature_hash_algorithm.name}\n"
157 nfo += f" Self Issued: {'YES' if self.self_signed else 'NO'}\n"
158
159 return nfo
160
161 @classmethod
162 def parse(cls, data: bytes) -> "Certificate":
163 """Deserialize object from bytes array.
164
165 :param data: Data to be parsed
166 :returns: Recreated certificate
167 """
168
169 def load_der_certificate(data: bytes) -> x509.Certificate:
170 """Load the DER certificate from bytes.
171
172 This function is designed to eliminate cryptography exception
173 when the padded data is provided.
174
175 :param data: Data with DER certificate
176 :return: Certificate (from cryptography library)
177 :raises SPSDKError: Unsupported certificate to load
178 """
179 while True:
180 try:
181 return x509.load_der_x509_certificate(data)
182 except ValueError as exc:
183 if len(exc.args) and "kind: ExtraData" in exc.args[0] and data[-1:] == b"\00":
184 data = data[:-1]
185 else:
186 raise SPSDKValueError(str(exc)) from exc
187
188 try:
189 encoding = SPSDKEncoding.get_file_encodings(data)
190 if encoding != SPSDKEncoding.DER:
191 raise ValueError("Unsupported encoding: {encoding}")
192 return Certificate(load_der_certificate(data))
193 except ValueError as exc:
194 raise SPSDKError(f"Cannot load certificate: ({str(exc)})") from exc