def check_csr(csr: x509.CertificateSigningRequest, template: Template) -> str: """ find all differences (errors) between info in csr and template, return empty string if no errors""" extensions = { OID_NAMES.get(extension.oid, extension.oid): extension.value for extension in csr.extensions } # noinspection PyProtectedMember return '\n'.join(error for error in ( # verify csr signature '' if csr. is_signature_valid else 'hmmm... csr signature is not valid!!!', # verify signature hash algorithm '' if csr.signature_hash_algorithm.name == template.hash_algorithm.lower() else 'hmmm wrong hash algorithm!!!', # verify subject matches '' if template.subject == tuple( (OID_NAMES.get(attrib.oid), attrib.value) for attrib in csr.subject) else 'subject mismatch:\n{}\n{}\n'. format(csr.subject, template.subject), # verify subjectAltName '' if template.subject_alt_names is None and 'subject_alt_names' not in extensions else '' if tuple( x.value for x in extensions['subjectAltName']) == template. subject_alt_names else 'subject_alt_names mismatch:\n{}\n{}\n'. format(extensions['subjectAltName'], template.subject_alt_names), # verify basicConstraints ca '' if extensions['basicConstraints'].ca == template.basic_constraints. ca else 'basicConstraints ca mismatch:\n{}\n{}\n'.format( extensions['basicConstraints'].ca, template.basic_constraints.ca), # verify basicConstraints path_length '' if extensions['basicConstraints'].path_length == template.basic_constraints. path_length else 'basicConstraints path_length mismatch:\n{}\n{}\n'. format(extensions['basicConstraints'].path_length, template. basic_constraints.path_length), # verify keyUsage '' if template.key_usage is None and 'keyUsage' not in extensions else '' if all(( extensions['keyUsage'].digital_signature == template.key_usage.digital_signature, extensions['keyUsage'].content_commitment == template.key_usage.content_commitment, extensions['keyUsage'].key_encipherment == template.key_usage.key_encipherment, extensions['keyUsage'].data_encipherment == template.key_usage.data_encipherment, extensions['keyUsage'].key_agreement == template.key_usage.key_agreement, extensions['keyUsage'].key_cert_sign == template.key_usage.key_cert_sign, extensions['keyUsage'].crl_sign == template.key_usage.crl_sign, extensions['keyUsage']._encipher_only == template.key_usage.encipher_only, extensions['keyUsage']._decipher_only == template.key_usage.decipher_only, )) else 'keyUsage mismatch:\n{}\n{}\n'. format(extensions['keyUsage'], template.key_usage), # verify KeySize '' if template.key_size == csr.public_key().key_size else 'KeySize mismatch:\n{}\n{}\n'. format(csr.public_key().key_size, template.key_size), # verify KeySize >= 2048 '' if csr.public_key().key_size >= 2048 else 'weak key size {}'. format(csr.public_key().key_size)) if error != '')
def _name(self): # Lazy import to avoid an import cycle from cryptography.x509.oid import _OID_NAMES return _OID_NAMES.get(self, "Unknown OID")