|
| 1 | +import base64 |
| 2 | +import os |
| 3 | +from datetime import datetime, timedelta |
| 4 | + |
| 5 | +from cryptography import x509 |
| 6 | +from cryptography.hazmat.backends import default_backend |
| 7 | +from cryptography.hazmat.primitives import hashes, serialization |
| 8 | +from cryptography.hazmat.primitives.asymmetric import ec |
| 9 | +from cryptography.hazmat.primitives.serialization import load_pem_private_key |
| 10 | +from cryptography.x509.oid import NameOID |
| 11 | + |
| 12 | + |
| 13 | +class ECDSASigner: |
| 14 | + """ECDSA secp384R1 signer |
| 15 | +
|
| 16 | + This class implements ECDSA methods specific to a single instance of |
| 17 | + enclave, so, that it can be reused across without passing references |
| 18 | + across the breadth of the code. The relevant keys and certificates are |
| 19 | + stored in /tmp. /tmp should be appropriately configured in the enclave |
| 20 | + manifest, so, that it is wiped off when the enclave exits. |
| 21 | +
|
| 22 | + Raises: |
| 23 | + Exception: ValueError() for incorrect configuration |
| 24 | +
|
| 25 | + Returns: |
| 26 | + object: The reference of the only object |
| 27 | + """ |
| 28 | + |
| 29 | + __signer_instance = None |
| 30 | + |
| 31 | + @staticmethod |
| 32 | + def get_instance(privkey_path="/tmp/client_privkey.pem"): |
| 33 | + if ECDSASigner.__signer_instance is None: |
| 34 | + ECDSASigner(privkey_path) |
| 35 | + return ECDSASigner.__signer_instance |
| 36 | + |
| 37 | + def __init__(self, privkey_path="/tmp/client_privkey.pem", cert_path="/tmp/"): |
| 38 | + """Constructor for creating the ECDSA Certificate Chain |
| 39 | +
|
| 40 | + Args: |
| 41 | + privkey_path (string, optional): Path to the existing client private key. |
| 42 | + Defaults to None. |
| 43 | +
|
| 44 | + Raises: |
| 45 | + Exception: Generic, in case there's invalid configuration or file data |
| 46 | + """ |
| 47 | + if ECDSASigner.__signer_instance is not None: |
| 48 | + raise Exception("ECDSASigner: Only one instance allowed") |
| 49 | + else: |
| 50 | + ECDSASigner.__signer_instance = self |
| 51 | + |
| 52 | + self._root_cert_path = os.path.join(cert_path, "openfl-security-ca-cert.pem") |
| 53 | + self._client_cert_path = os.path.join(cert_path, "openfl-enclave-cert.pem") |
| 54 | + |
| 55 | + # If the private key already exists, then reuse to create the certificate |
| 56 | + # if doesn't exist. |
| 57 | + self._client_cert = None |
| 58 | + self._root_cert = None |
| 59 | + |
| 60 | + if privkey_path and os.path.exists(privkey_path): |
| 61 | + with open(privkey_path, "rb") as client_priv_fh: |
| 62 | + client_privkey_pem = client_priv_fh.read() |
| 63 | + |
| 64 | + # Once the private key is found in filesystem, then look for saved |
| 65 | + # certificate and the corresponding public key |
| 66 | + self._client_privkey = load_pem_private_key(client_privkey_pem, password=None) |
| 67 | + if not isinstance(self._client_privkey, ec.EllipticCurvePrivateKey): |
| 68 | + raise ValueError(f"Invalid private key format: '{privkey_path}'") |
| 69 | + |
| 70 | + self._client_pubkey = self._client_privkey.public_key() |
| 71 | + |
| 72 | + # Check if certificate is already present in the filesystem, if not then |
| 73 | + # serialize is not called yet |
| 74 | + if os.path.exists(self._client_cert_path): |
| 75 | + with open(self._client_cert_path, "rb") as cert_fh: |
| 76 | + self._client_cert = x509.load_pem_x509_certificate( |
| 77 | + cert_fh.read(), default_backend() |
| 78 | + ) |
| 79 | + |
| 80 | + # FIXME: Post upgrading cryptography module, delete this below |
| 81 | + # and change above call to load_pem_x509_certificate(s) to load the chain |
| 82 | + if not os.path.exists(self._root_cert_path): |
| 83 | + raise ValueError( |
| 84 | + "Out of tree modification detected, " |
| 85 | + "clean all the keys and certs and try again" |
| 86 | + ) |
| 87 | + with open(self._root_cert_path, "rb") as cert_fh: |
| 88 | + self._root_cert = x509.load_pem_x509_certificate( |
| 89 | + cert_fh.read(), default_backend() |
| 90 | + ) |
| 91 | + |
| 92 | + else: |
| 93 | + self._root_privkey = ec.generate_private_key(ec.SECP384R1(), default_backend()) |
| 94 | + self._root_pubkey = self._root_privkey.public_key() |
| 95 | + |
| 96 | + self._client_privkey = ec.generate_private_key(ec.SECP384R1(), default_backend()) |
| 97 | + |
| 98 | + self._client_pubkey = self._client_privkey.public_key() |
| 99 | + |
| 100 | + def __get_cert( |
| 101 | + self, |
| 102 | + subject_name, |
| 103 | + subject_pubkey, |
| 104 | + issuer_name, |
| 105 | + issuer_privkey, |
| 106 | + ca=False, |
| 107 | + mrenclave_data=None, |
| 108 | + ): |
| 109 | + """Create a certificate with optional MRENCLAVE_OID extension. |
| 110 | +
|
| 111 | + Args: |
| 112 | + subject_name (string): The subject name in the certificate, must match the URL. |
| 113 | + subject_pubkey (string): Subject's public key to be embedded in the certificate. |
| 114 | + issuer_name (string): The CA name. |
| 115 | + issuer_privkey (string): The CA private key to sign the subject certificate. |
| 116 | + ca (bool, optional): To set CA=true property. Defaults to False. |
| 117 | + mrenclave_data (string, optional): The mrenclave data to be added as a custom extension. |
| 118 | +
|
| 119 | + Returns: |
| 120 | + object: Certificate. |
| 121 | + """ |
| 122 | + # Create the certificate builder |
| 123 | + cert_builder = x509.CertificateBuilder() |
| 124 | + cert_builder = cert_builder.subject_name( |
| 125 | + x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, subject_name)]) |
| 126 | + ) |
| 127 | + cert_builder = cert_builder.issuer_name( |
| 128 | + x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, issuer_name)]) |
| 129 | + ) |
| 130 | + |
| 131 | + oneday = timedelta(1, 0, 0) |
| 132 | + start_validity = datetime.today() - oneday |
| 133 | + end_validity = datetime.today() + (100 * oneday) |
| 134 | + cert_builder = cert_builder.not_valid_before(start_validity) |
| 135 | + cert_builder = cert_builder.not_valid_after(end_validity) |
| 136 | + |
| 137 | + if ca: |
| 138 | + cert_builder = cert_builder.add_extension( |
| 139 | + x509.BasicConstraints(ca=True, path_length=None), critical=True |
| 140 | + ) |
| 141 | + |
| 142 | + cert_builder = cert_builder.serial_number(x509.random_serial_number()) |
| 143 | + cert_builder = cert_builder.public_key(subject_pubkey) |
| 144 | + |
| 145 | + # Add the custom MRENCLAVE_OID extension if mrenclave_data is provided |
| 146 | + if mrenclave_data: |
| 147 | + MRENCLAVE_OID = x509.ObjectIdentifier("1.3.6.1.4.1.99999.1.1") # Example OID |
| 148 | + cert_builder = cert_builder.add_extension( |
| 149 | + x509.UnrecognizedExtension(MRENCLAVE_OID, mrenclave_data.encode("utf-8")), |
| 150 | + critical=False, |
| 151 | + ) |
| 152 | + |
| 153 | + # Sign the certificate |
| 154 | + return cert_builder.sign(issuer_privkey, algorithm=hashes.SHA384()) |
| 155 | + |
| 156 | + def __create_cert_chain(self): |
| 157 | + root_cert_bytes = self._root_cert.public_bytes((serialization.Encoding.PEM)) |
| 158 | + client_cert_bytes = self._client_cert.public_bytes((serialization.Encoding.PEM)) |
| 159 | + |
| 160 | + # Concatenate together and return |
| 161 | + cert_chain = client_cert_bytes.decode("utf-8") + root_cert_bytes.decode("utf-8") |
| 162 | + return cert_chain |
| 163 | + |
| 164 | + def cert(self, common_name, mrenclave_data=None): |
| 165 | + """Returns the self-signed certificate |
| 166 | + Args: |
| 167 | + common_name (string): to be used as subject and issuer name |
| 168 | + Returns: |
| 169 | + _type_: _description_ |
| 170 | + """ |
| 171 | + |
| 172 | + # Create the certificate chaining with local CA |
| 173 | + # A. Create a root CA certificate |
| 174 | + # B. Create the node certificate |
| 175 | + |
| 176 | + # Return the cached value if it exists |
| 177 | + if self._client_cert: |
| 178 | + return self.__create_cert_chain() |
| 179 | + |
| 180 | + ca_common_name = f"{common_name}-CA" |
| 181 | + self._root_cert = self.__get_cert( |
| 182 | + ca_common_name, self._root_pubkey, ca_common_name, self._root_privkey, ca=True |
| 183 | + ) |
| 184 | + |
| 185 | + self._client_cert = self.__get_cert( |
| 186 | + common_name, |
| 187 | + self._client_pubkey, |
| 188 | + ca_common_name, |
| 189 | + self._root_privkey, |
| 190 | + False, |
| 191 | + mrenclave_data=mrenclave_data, |
| 192 | + ) |
| 193 | + |
| 194 | + return self.__create_cert_chain() |
| 195 | + |
| 196 | + def get_pubkey(self): |
| 197 | + """returns public key as a PEM string""" |
| 198 | + |
| 199 | + return self._client_pubkey.public_bytes( |
| 200 | + encoding=serialization.Encoding.PEM, |
| 201 | + format=serialization.PublicFormat.SubjectPublicKeyInfo, |
| 202 | + ).decode("utf-8") |
| 203 | + |
| 204 | + def sign(self, message): |
| 205 | + """sign message string using private key. |
| 206 | +
|
| 207 | + Return Value: base64 encoded string |
| 208 | + """ |
| 209 | + |
| 210 | + signature_bytes = self._client_privkey.sign( |
| 211 | + message.encode("utf-8"), ec.ECDSA(hashes.SHA384()) |
| 212 | + ) |
| 213 | + return base64.b64encode(signature_bytes).decode("utf-8") |
| 214 | + |
| 215 | + def serialize_private_key(self, filename="/tmp/client_privkey.pem", save_root_cert=True): |
| 216 | + """write the private key to a file in PEM format""" |
| 217 | + |
| 218 | + client_privkey_pem = self._client_privkey.private_bytes( |
| 219 | + encoding=serialization.Encoding.PEM, |
| 220 | + format=serialization.PrivateFormat.PKCS8, |
| 221 | + encryption_algorithm=serialization.NoEncryption(), |
| 222 | + ) |
| 223 | + |
| 224 | + with open(filename, "wb") as fh: |
| 225 | + fh.write(client_privkey_pem) |
| 226 | + |
| 227 | + # Save the CA certificate if not already exists |
| 228 | + if os.path.exists(self._root_cert_path) is False and save_root_cert: |
| 229 | + root_cert_bytes = self._root_cert.public_bytes((serialization.Encoding.PEM)) |
| 230 | + with open(self._root_cert_path, "wb") as fh: |
| 231 | + fh.write(root_cert_bytes) |
| 232 | + |
| 233 | + # Save the client certificate if not already exists |
| 234 | + if os.path.exists(self._client_cert_path) is False: |
| 235 | + cert_chain = self.__create_cert_chain() |
| 236 | + with open(self._client_cert_path, "wb") as fh: |
| 237 | + fh.write(cert_chain.encode("utf-8")) |
| 238 | + |
| 239 | + return client_privkey_pem |
0 commit comments