예제 #1
0
def main():
    # Create argument parser to document script use
    parser = argparse.ArgumentParser(description='Generate atcacert_def_t structure from sample certificate.')
    group = parser.add_argument_group('group')
    group.add_argument(
        '--signer-cert',
        dest='signer_cert_filename',
        nargs='?',
        default='signer-ca.crt',
        metavar='file',
        help='Generate signer certificate definition from sample certificate.')
    group.add_argument(
        '--device-cert',
        dest='device_cert_filename',
        nargs='?',
        default='device.crt',
        metavar='file',
        help='Generate device certificate definition from sample certificate.')

    args = parser.parse_args()

    if args.signer_cert_filename is not None:
        cert_der = pem.readPemFromFile(open(args.signer_cert_filename))
        print(gen_cert_def_c_signer(cert_der))


    if args.device_cert_filename is not None:
        cert_der = pem.readPemFromFile(open(args.device_cert_filename))
        print(gen_cert_def_c_device(cert_der))

    print('certdef output finishied')

    return
예제 #2
0
def main():
    # Create argument parser to document script use
    parser = argparse.ArgumentParser(
        description='Generate atcacert_def_t structure from sample certificate.'
    )
    group = parser.add_argument_group('group')
    group.add_argument(
        '--signer-cert',
        dest='signer_cert_filename',
        nargs='?',
        default='signer-ca.crt',
        metavar='file',
        help='Generate signer certificate definition from sample certificate.')
    group.add_argument(
        '--device-cert',
        dest='device_cert_filename',
        nargs='?',
        default='device.crt',
        metavar='file',
        help='Generate device certificate definition from sample certificate.')
    group.add_argument('--device-csr',
                       dest='device_csr_filename',
                       nargs='?',
                       default=None,
                       metavar='file',
                       help='Generate device CSR definition from sample CSR.')
    args = parser.parse_args()

    if args.signer_cert_filename is not None:
        cert_der = pem.readPemFromFile(open(args.signer_cert_filename))
        print(gen_cert_def_c_signer(cert_der))
        with open("cert_chain.c", mode='w', encoding="utf-8") as f:
            f.write(gen_cert_def_c_signer(cert_der))

    if args.device_cert_filename is not None:
        cert_der = pem.readPemFromFile(open(args.device_cert_filename))
        print(gen_cert_def_c_device(cert_der))
        with open("cert_chain.c", mode='a', encoding="utf-8") as f:
            f.write(gen_cert_def_c_device(cert_der))

    if args.device_csr_filename is not None:
        csr_der = pem.readPemFromFile(
            open(args.device_csr_filename),
            startMarker='-----BEGIN CERTIFICATE REQUEST-----',
            endMarker='-----END CERTIFICATE REQUEST-----')
        print(gen_cert_def_c_device_csr(csr_der))
        return
    return
def get_symmetric_key(file_path):
    csr_der = pem.readPemFromFile(open(file_path),
                                  startMarker='-----BEGIN SYMMETRIC KEY-----',
                                  endMarker='-----END SYMMETRIC KEY-----')
    data = bytearray()
    data.extend(csr_der[17:((csr_der[14] - 2) + 17)])
    return data
예제 #4
0
    def test_all_extensions(self):

        out = _(
            "req -x509 "
            "-extensions all_exts "
            '-subj "/CN=www.mydom.com/O=My Dom, Inc./C=US/ST=Oregon/L=Portland" '
            "-new -key priv.key -out %s" % self.CERT_FILE
        )

        cert, rest = decode(readPemFromFile(open(self.CERT_FILE)), asn1Spec=rfc2459.Certificate())
        self.assertFalse(rest)
        self._asn_print(cert)

        self._assert_extensions(cert,
                                [
                                    '2.5.29.35',
                                    '2.5.29.14',
                                    '2.5.29.15',
                                    '2.5.29.32',
                                    '2.5.29.17',
                                    '2.5.29.18',
                                    '2.5.29.19',
                                    '2.5.29.30',
                                    '2.5.29.36',
                                    '2.5.29.37',
                                    '2.5.29.31',
                                    '2.5.29.54',
                                    '1.3.6.1.5.5.7.1.1',
                                ]
        )
예제 #5
0
    def test_https_cert_invalid(self):
        """Verify vikidia SSL certificate is invalid."""
        try:
            from pyasn1_modules import pem, rfc2459
            from pyasn1.codec.der import decoder
        except ImportError:
            raise unittest.SkipTest('pyasn1 and pyasn1_modules not available.')

        import ssl
        import io

        cert = ssl.get_server_certificate(addr=('en.vikidia.org', 443))
        s = io.StringIO(unicode(cert))
        substrate = pem.readPemFromFile(s)
        cert = decoder.decode(substrate, asn1Spec=rfc2459.Certificate())[0]
        tbs_cert = cert.getComponentByName('tbsCertificate')
        issuer = tbs_cert.getComponentByName('issuer')
        organisation = None
        for rdn in issuer.getComponent():
            for attr in rdn:
                attr_type = attr.getComponentByName('type')
                if attr_type == rfc2459.id_at_organizationName:
                    value, _ = decoder.decode(attr.getComponentByName('value'),
                                              asn1Spec=rfc2459.X520name())
                    organisation = str(value.getComponent())
                    break

        self.assertEqual(organisation, 'TuxFamily.org non-profit organization')
예제 #6
0
def print_block(pemData):
    substrate = pem.readPemFromFile(io.StringIO(pemData.decode("utf-8")))
    cert, rest = decoder.decode(substrate, asn1Spec=rfc5280.Certificate())
    der_subject = encoder.encode(cert['tbsCertificate']['subject'])
    octets = hex_string_for_struct(der_subject)

    cert = x509.load_pem_x509_certificate(pemData, default_backend())
    common_name = cert.subject.get_attributes_for_oid(NameOID.COMMON_NAME)[0]
    block_name = "CA{}DN".format(re.sub(r'[-:=_. ]', '', common_name.value))

    fingerprint = hex_string_human_readable(cert.fingerprint(hashes.SHA256()))

    dn_parts = ["/{id}={value}".format(id=nameOIDtoString(part.oid),
                                       value=part.value) for part in cert.subject]
    distinguished_name = "".join(dn_parts)

    print("// {dn}".format(dn=distinguished_name))
    print("// SHA256 Fingerprint: " + ":".join(fingerprint[:16]))
    print("//                     " + ":".join(fingerprint[16:]))
    print("// https://crt.sh/?id={crtsh} (crt.sh ID={crtsh})"
          .format(crtsh=crtshId))
    print("static const uint8_t {}[{}] = ".format(block_name, len(octets)) + "{")

    while len(octets) > 0:
        print("  " + ", ".join(octets[:13]) + ",")
        octets = octets[13:]

    print("};")
    print()

    return block_name
예제 #7
0
    def test_https_cert_invalid(self):
        """Verify vikidia SSL certificate is invalid."""
        try:
            from pyasn1_modules import pem, rfc2459
            from pyasn1.codec.der import decoder
        except ImportError:
            raise unittest.SkipTest('pyasn1 and pyasn1_modules not available.')

        import ssl
        import io

        cert = ssl.get_server_certificate(addr=('en.vikidia.org', 443))
        s = io.StringIO(unicode(cert))
        substrate = pem.readPemFromFile(s)
        cert = decoder.decode(substrate, asn1Spec=rfc2459.Certificate())[0]
        tbs_cert = cert.getComponentByName('tbsCertificate')
        issuer = tbs_cert.getComponentByName('issuer')
        organisation = None
        for rdn in issuer.getComponent():
            for attr in rdn:
                attr_type = attr.getComponentByName('type')
                if attr_type == rfc2459.id_at_organizationName:
                    value, _ = decoder.decode(attr.getComponentByName('value'),
                                              asn1Spec=rfc2459.X520name())
                    organisation = str(value.getComponent())
                    break

        self.assertEqual(organisation, 'TuxFamily.org non-profit organization')
예제 #8
0
def print_block(pemData):
    substrate = pem.readPemFromFile(io.StringIO(pemData.decode("utf-8")))
    cert, rest = decoder.decode(substrate, asn1Spec=rfc5280.Certificate())
    der_subject = encoder.encode(cert['tbsCertificate']['subject'])
    octets = hex_string_for_struct(der_subject)

    cert = x509.load_pem_x509_certificate(pemData, default_backend())
    common_name = cert.subject.get_attributes_for_oid(NameOID.COMMON_NAME)[0]
    block_name = "CA{}DN".format(re.sub(r'[-:=_. ]', '', common_name.value))

    fingerprint = hex_string_human_readable(cert.fingerprint(hashes.SHA256()))

    dn_parts = [
        "/{id}={value}".format(id=nameOIDtoString(part.oid), value=part.value)
        for part in cert.subject
    ]
    distinguished_name = "".join(dn_parts)

    print("// {dn}".format(dn=distinguished_name))
    print("// SHA256 Fingerprint: " + ":".join(fingerprint[:16]))
    print("//                     " + ":".join(fingerprint[16:]))
    print("// https://crt.sh/?id={crtsh} (crt.sh ID={crtsh})".format(
        crtsh=crtshId))
    print("static const uint8_t {}[{}] = ".format(block_name, len(octets)) +
          "{")

    while len(octets) > 0:
        print("  " + ", ".join(octets[:13]) + ",")
        octets = octets[13:]

    print("};")
    print()

    return block_name
예제 #9
0
def validateCertChain (certPem):
    # Ensure this is a good cert
    certs = extractPems(certPem)
    valid = False

    for indvCertPem in certs:
        wrappedPem = StringIO.StringIO(indvCertPem)

        substrate = pem.readPemFromFile(wrappedPem)
        cert = decoder.decode(substrate, asn1Spec=rfc2459.Certificate())[0]
        tbsCertificate = cert[0]
        subj = tbsCertificate['subject']
        validity = tbsCertificate['validity']
        extensions = tbsCertificate['extensions']

        dateformat = '%y%m%d%H%M%SZ'
        notBefore = datetime.strptime(str(validity.getComponentByPosition(0).getComponentByPosition(0)), dateformat)
        notAfter = datetime.strptime(str(validity.getComponentByPosition(1).getComponentByPosition(0)), dateformat)

        #print ('not before: ' + str(notBefore) + ', not after: ' + str(notAfter))

        now = datetime.utcnow()

        if now >= notBefore:
            if now <= notAfter:
                print ('Cert is still valid')
                valid = True
            else:
                print ('expired cert!')
        else:
            print ('cert not valid yet!')

    return valid
예제 #10
0
def parse_certificate(certificate_path):
    fqdns = set()

    substrate = pem.readPemFromFile(open(certificate_path))
    cert = decoder.decode(substrate, asn1Spec=rfc2459.Certificate())[0]
    core = cert['tbsCertificate']

    # Extract CommonName
    for rdnss in core['subject']:
        for rdns in rdnss:
            for name in rdns:
                if name.getComponentByName('type') == rfc2459.id_at_commonName:
                    value = decoder.decode(
                        name.getComponentByName('value'),
                        asn1Spec=rfc2459.DirectoryString())[0]
                    fqdns.add(str(value.getComponent()))

    # extract notAfter datetime
    notAfter = str(core['validity'].getComponentByName(
        'notAfter').getComponent()).strip('Z')
    (year, month, day, hour, minute,
     seconds) = [int(notAfter[i:i + 2]) for i in range(0, len(notAfter), 2)]
    expiration_date = datetime(2000 + year, month, day, hour, minute, seconds)

    # Extract SubjectAltName
    for extension in core['extensions']:
        if extension['extnID'] == rfc2459.id_ce_subjectAltName:
            (san_list,
             r) = decoder.decode(extension.getComponentByName('extnValue'),
                                 rfc2459.SubjectAltName())
            for san_struct in san_list:
                if san_struct.getName() == 'dNSName':
                    fqdns.add(str(san_struct.getComponent()))
    return (fqdns, expiration_date)
예제 #11
0
def parse_certificate(certificate_path):
    fqdns = set()

    substrate = pem.readPemFromFile(open(certificate_path))
    cert = decoder.decode(substrate, asn1Spec=rfc2459.Certificate())[0]
    core = cert['tbsCertificate']

    # Hash public key
    der = encoder.encode(core.getComponentByName('subjectPublicKeyInfo'))
    hash_der = hashlib.sha256()
    hash_der.update(der)
    pkhash = hash_der.hexdigest()

    # Extract CommonName
    for rdnss in core['subject']:
        for rdns in rdnss:
            for name in rdns:
                if name.getComponentByName('type') == rfc2459.id_at_commonName:
                    value = decoder.decode(
                        name.getComponentByName('value'),
                        asn1Spec=rfc2459.DirectoryString())[0]
                    fqdns.add(str(value.getComponent()))

    # Extract SubjectAltName
    for extension in core['extensions']:
        if extension['extnID'] == rfc2459.id_ce_subjectAltName:
            octet_string = decoder.decode(
                extension.getComponentByName('extnValue'),
                asn1Spec=OctetString())[0]
            (san_list, r) = decoder.decode(octet_string,
                                           rfc2459.SubjectAltName())
            for san_struct in san_list:
                if san_struct.getName() == 'dNSName':
                    fqdns.add(str(san_struct.getComponent()))
    return (pkhash, fqdns)
예제 #12
0
def insert_cert(conn, ip, port, der, cert):
    (md5, sha1, sha256) = hashdata(der)
    print(sha1)
    c = conn.cursor()
    c.execute('select * from certs where sha256=? and recdate=? and ip=?', (
        sha256,
        date,
        ip,
    ))
    certrec = c.fetchone()
    if certrec == None:
        x509obj = x509.load_pem_x509_certificate(cert, default_backend())
        try:
            cert_str = str(x509obj.subject)
            print('IP: ' + ip + ' - ' + cert_str)
        except:
            cert_str = ("Empty")
            print('IP: ' + ip + ' - ' + cert_str)
        substrate = pem.readPemFromFile(io.BytesIO(cert))
        certobj = decoder.decode(substrate, asn1Spec=rfc2459.Certificate())[0]
        cert_str += certobj.prettyPrint()
        sql = '''insert into certs
			values (NULL, ?, ?, ?, ?, ?, ?, ?,?);'''
        c.execute(sql, [
            ip, port, md5, sha1, sha256,
            sqlite3.Binary(cert), cert_str, date
        ])
        certid = c.lastrowid
        conn.commit()
    else:
        certid = certrec[0]
    return certid
예제 #13
0
def cert_fingerprint(path):
    with open(path, "r") as f:
        bits = pem.readPemFromFile(f)
        digest = hashlib.sha256(bits).hexdigest()
        # Thanks stack overflow!
        chunked = ":".join(digest[i:i + 2] for i in range(0, len(digest), 2))
        # 04 is the TLS Hash ID
        return "04:" + chunked
예제 #14
0
def main():
    # Create argument parser to document script use
    parser = argparse.ArgumentParser(
        description='Generate atcacert_def_t structure from sample certificate.'
    )
    group = parser.add_mutually_exclusive_group(required=True)
    group.add_argument(
        '--signer-cert',
        dest='signer_cert_filename',
        nargs='?',
        default=None,
        metavar='file',
        help='Generate signer certificate definition from sample certificate.')
    group.add_argument(
        '--device-cert',
        dest='device_cert_filename',
        nargs='?',
        default=None,
        metavar='file',
        help='Generate device certificate definition from sample certificate.')
    group.add_argument('--device-csr',
                       dest='device_csr_filename',
                       nargs='?',
                       default=None,
                       metavar='file',
                       help='Generate device CSR definition from sample CSR.')
    args = parser.parse_args()

    if args.signer_cert_filename is not None:
        cert_der = pem.readPemFromFile(open(args.signer_cert_filename))
        print(gen_cert_def_c_signer(cert_der))
        return

    if args.device_cert_filename is not None:
        cert_der = pem.readPemFromFile(open(args.device_cert_filename))
        print(gen_cert_def_c_device(cert_der))
        return

    if args.device_csr_filename is not None:
        csr_der = pem.readPemFromFile(
            open(args.device_csr_filename),
            startMarker='-----BEGIN CERTIFICATE REQUEST-----',
            endMarker='-----END CERTIFICATE REQUEST-----')
        print(gen_cert_def_c_device_csr(csr_der))
        return
예제 #15
0
 def from_open_file(f):
     try:
         der_content = pem.readPemFromFile(f)
         certificate = decoder.decode(der_content,
                                      asn1Spec=rfc2459.Certificate())[0]
         return X509Certificate(certificate)
     except Exception:
         raise X509CertificateError("Could not read X509 certificate from "
                                    "PEM data.")
예제 #16
0
 def from_open_file(f):
     try:
         der_content = pem.readPemFromFile(f)
         certificate = decoder.decode(der_content,
                                      asn1Spec=rfc5280.Certificate())[0]
         return X509Certificate(certificate)
     except Exception:
         raise X509CertificateError("Could not read X509 certificate from "
                                    "PEM data.")
예제 #17
0
파일: utils.py 프로젝트: Jakuje/tpm2-pkcs11
def pemcert_to_attrs(certpath):
    # rather than use pycryptography x509 parser, which gives native type access to certficiate
    # fields use pyASN1 to get raw ASN1 encoded values for the fields as the spec requires them
    with open(certpath, "r") as f:
        substrate = pem.readPemFromFile(f)
        cert = decoder.decode(substrate, asn1Spec=rfc2459.Certificate())[0]

    c = cert['tbsCertificate']

    # print(cert.prettyPrint())

    h = binascii.hexlify
    b = berenc.encode
    d = derenc.encode

    bercert = b(cert)
    hexbercert = h(bercert).decode()

    # the CKA_CHECKSUM attrs is the first 3 bytes of a sha1hash
    m = hashlib.sha1()
    m.update(bercert)
    bercertchecksum = m.digest()[0:3]
    hexbercertchecksum = h(bercertchecksum).decode()

    subj = c['subject']
    hexsubj = h(d(str2bytes(subj))).decode()

    return {
        # The attrs of this attribute is derived by taking the first 3 bytes of the CKA_VALUE
        # field.
        CKA_CHECK_VALUE: hexbercertchecksum,
        # Start date for the certificate (default empty)
        CKA_START_DATE: "",
        # End date for the certificate (default empty)
        CKA_END_DATE: "",
        # DER-encoding of the SubjectPublicKeyInfo for the public key
        # contained in this certificate (default empty)
        CKA_PUBLIC_KEY_INFO: "",
        # DER encoded subject
        CKA_SUBJECT: hexsubj,
        # der encoding of issuer, default empty
        CKA_ISSUER: '',
        # der encoding of the cert serial, default empty
        CKA_SERIAL_NUMBER: '',
        # BER encoding of the certificate
        CKA_VALUE: hexbercert,
        # RFC2279 string to URL where cert can be found, default empty
        CKA_URL: '',
        # hash of pub key subj, default empty
        CKA_HASH_OF_SUBJECT_PUBLIC_KEY: '',
        # Hash of pub key, default empty
        CKA_HASH_OF_ISSUER_PUBLIC_KEY: '',
        # Java security domain, default CK_SECURITY_DOMAIN_UNSPECIFIED
        CKA_JAVA_MIDP_SECURITY_DOMAIN: CK_SECURITY_DOMAIN_UNSPECIFIED,
        # Name hash algorithm, defaults to SHA1
        CKA_NAME_HASH_ALGORITHM: CKM_SHA_1
    }
    def loadPEM(cls, pemData):
        cert = X509Certificate()
        cert.__internalTwistedCert = Certificate.loadPEM(pemData)

        asn1cert = decoder.decode(pem.readPemFromFile(StringIO(pemData)),
                                  asn1Spec=rfc2459.Certificate())[0]
        cert.__internalAsn1 = asn1cert

        return cert
예제 #19
0
 def from_open_file(f):
     try:
         der_content = pem.readPemFromFile(
             f, startMarker='-----BEGIN CERTIFICATE REQUEST-----',
             endMarker='-----END CERTIFICATE REQUEST-----')
         csr = decoder.decode(der_content,
                              asn1Spec=rfc2314.CertificationRequest())[0]
         return X509Csr(csr)
     except Exception:
         raise X509CsrError("Could not read X509 certificate from "
                            "PEM data.")
예제 #20
0
 def from_open_file(f):
     try:
         der_content = pem.readPemFromFile(
             f,
             startMarker='-----BEGIN CERTIFICATE REQUEST-----',
             endMarker='-----END CERTIFICATE REQUEST-----')
         csr = decoder.decode(der_content,
                              asn1Spec=rfc2314.CertificationRequest())[0]
         return X509Csr(csr)
     except Exception:
         raise X509CsrError("Could not read X509 certificate from "
                            "PEM data.")
예제 #21
0
    def test_extensions_X509v3(self):

        out = _(
            "req -x509 "
            "-extensions single_extension "
            '-subj "/CN=www.mydom.com/O=My Dom, Inc./C=US/ST=Oregon/L=Portland" '
            "-new -key priv.key -out %s" % self.CERT_FILE)

        cert, rest = decode(readPemFromFile(open(self.CERT_FILE)), asn1Spec=rfc5208.Certificate())
        self.assertFalse(rest)
        self._asn_print(cert)

        self._assert_extensions(cert, ['2.5.29.15'])
예제 #22
0
def esp_handle_file(file_name, operation, data=None):
    if operation is "read":
        with open(file_name, "r") as cert_file:
            data = cert_file.read()
        return data
    elif operation is "pem_read":
        with open(file_name, "r") as cert_file:
            data = pem.readPemFromFile(cert_file)
        return data
    elif operation is "write":
        with open(file_name, "w+") as cert_file:
            cert_file.write(data)
        return True
예제 #23
0
def check_signature(tsa_cert: str, signature, data, hash_str):
    # TODO invoke different hash function based on hash_str
    try:
        data_ = encoder.encode(data, asn1Spec=univ.SetOf())  # encode with asn1Spec univ.SetOf()
        with open(tsa_cert, 'r') as pem_file:
            cert_pem = pem.readPemFromFile(pem_file)
        pub_key = RSA.import_key(cert_pem)
        hash_obj = SHA1.new()
        hash_obj.update(data_)
        crypto_signature.new(pub_key).verify(hash_obj, signature.asOctets())
    except Exception as e:
        logging.error('Check signature: Failure', exc_info=True)
        raise e
    logging.info('Check signature: Success')
    return True
예제 #24
0
    def test_subjectKeyIdentifier(self):

        out = _(
            "req -x509 "
            "-extensions ski_ext "
            '-subj "/CN=www.mydom.com/O=My Dom, Inc./C=US/ST=Oregon/L=Portland" '
            "-new -key priv.key -out %s" % self.CERT_FILE
        )

        cert, rest = decode(readPemFromFile(open(self.CERT_FILE)), asn1Spec=rfc5208.Certificate())
        self.assertFalse(rest)
        self._asn_print(cert)

        exts = self._assert_extensions(cert, ['2.5.29.14'])
        self.assertEqual(len(exts['2.5.29.14']), 24)
예제 #25
0
def sign(target, image_path, key_path, cert_path):
    image_length = os.path.getsize(image_path)
    signable_size = get_signable_image_size(image_path)

    if signable_size < image_length:
        print('NOTE: truncating file',
              image_path,
              'from',
              image_length,
              'to',
              signable_size,
              'bytes',
              file=sys.stderr)
        with open(image_path, 'rb+') as f:
            f.truncate(signable_size)
    elif signable_size > image_length:
        raise ValueError('Invalid image: too short, expected {} bytes'.format(
            signable_size))

    boot_signature = BootSignature.create(target, signable_size)

    with open(cert_path, 'r') as rf:
        # cert2 = x509.load_pem_x509_certificate(pem_data, default_backend())
        data = pem.readPemFromFile(rf)
        key, rest = decoder.decode(data, asn1Spec=rfc2459.Certificate())
        boot_signature['certificate'] = key
        authenticated_attributes = boot_signature['authenticatedAttributes']
        encoded_authenticated_attributes = der_encoder(
            authenticated_attributes)

        digest = get_image_hash(image_path,
                                extra_data=encoded_authenticated_attributes)

        #key = RSA.load_key(key_path)
        data = open(key_path, 'rb').read()
        key = Crypto.PublicKey.RSA.importKey(data)
        #signature = key.sign(digest, algo='sha256')
        signer = PKCS1_v1_5.new(key)
        signature = signer.sign(digest)

        boot_signature['signature'] = signature
        boot_signature['algorithmIdentifier'][
            'algorithm'] = rfc4055.sha256WithRSAEncryption

        encoded_boot_signature = der_encoder(boot_signature)

        with open(image_path, 'ab') as f:
            f.write(encoded_boot_signature)
예제 #26
0
def asn1parse_tss_key(keypath):

    tss2_startmarker = '-----BEGIN TSS2 PRIVATE KEY-----'
    tss2_endmarker = '-----END TSS2 PRIVATE KEY-----'

    with open(keypath, 'r') as f:
        substrate = pem.readPemFromFile(f,
                                        startMarker=tss2_startmarker,
                                        endMarker=tss2_endmarker)

        if len(substrate) == 0:
            sys.exit('Did not find key in tss key file: {}'.format(keypath))

        tss2_privkey, _ = decoder.decode(substrate, asn1Spec=TSSPrivKey())

        return tss2_privkey
def play():
    keys_dictionary = {}
    certificates_list = list()
    for data_file in os.listdir(CERT_DIR):  #first round
        filename = os.path.join(CERT_DIR, data_file)
        with open(filename) as f:
            binary_data = pem.readPemFromFile(f)
            cert, rest = der_decoder.decode(binary_data,
                                            asn1Spec=rfc2459.Certificate())
            tbs_cert = cert['tbsCertificate']
            certificates_list.append(cert)
            print_summary(tbs_cert)
            add_in_keys_dictionary(keys_dictionary, tbs_cert)
            print()
    for c in certificates_list:  #second round
        signature_check(c, keys_dictionary)
예제 #28
0
    def test_subjectKeyIdentifier_belt_hash(self):

        out = _(
            "req -x509 "
            "-extensions ski_belt_ext "
            '-subj "/CN=www.mydom.com/O=My Dom, Inc./C=US/ST=Oregon/L=Portland" ' 
            "-new -key priv.key -out %s" % self.CERT_FILE
        )

        cert, rest = decode(readPemFromFile(open(self.CERT_FILE)), asn1Spec=rfc5208.Certificate())
        self.assertFalse(rest)
        self._asn_print(cert)

        exts = self._assert_extensions(cert, ['2.5.29.14'])
        belt_hash = exts['2.5.29.14']
        print(colored('Subject key identifier on belt is: ' + belt_hash, 'yellow'))
        self.assertEqual(len(belt_hash), 36)
예제 #29
0
def print_block(pemData, identifierType="DN", crtshId=None):
    substrate = pem.readPemFromFile(io.StringIO(pemData.decode("utf-8")))
    cert, rest = decoder.decode(substrate, asn1Spec=rfc5280.Certificate())
    octets = None

    if identifierType == "DN":
        der_subject = encoder.encode(cert["tbsCertificate"]["subject"])
        octets = hex_string_for_struct(der_subject)
    elif identifierType == "SPKI":
        der_spki = encoder.encode(
            cert["tbsCertificate"]["subjectPublicKeyInfo"])
        octets = hex_string_for_struct(der_spki)
    else:
        raise Exception("Unknown identifier type: " + identifierType)

    cert = x509.load_pem_x509_certificate(pemData, default_backend())
    common_name = cert.subject.get_attributes_for_oid(NameOID.COMMON_NAME)[0]
    block_name = "CA{}{}".format(re.sub(r"[-:=_. ]", "", common_name.value),
                                 identifierType)

    fingerprint = hex_string_human_readable(cert.fingerprint(hashes.SHA256()))

    dn_parts = [
        "/{id}={value}".format(id=nameOIDtoString(part.oid), value=part.value)
        for part in cert.subject
    ]
    distinguished_name = "".join(dn_parts)

    print("// {dn}".format(dn=distinguished_name))
    print("// SHA256 Fingerprint: " + ":".join(fingerprint[:16]))
    print("//                     " + ":".join(fingerprint[16:]))
    if crtshId:
        print("// https://crt.sh/?id={crtsh} (crt.sh ID={crtsh})".format(
            crtsh=crtshId))
    print("static const uint8_t {}[{}] = ".format(block_name, len(octets)) +
          "{")

    while len(octets) > 0:
        print("  " + ", ".join(octets[:13]) + ",")
        octets = octets[13:]

    print("};")
    print()

    return block_name
예제 #30
0
    def test_request(self):
        request_file = 'req.pem'
        out = _(
            'req -subj "/CN=www.mydom.com/O=My Dom, Inc./C=US/ST=Oregon/L=Portland" -new -key priv.key -out {out}'
            .format(out=request_file))

        out = _(
            'x509 -req -in {req_file} -signkey priv.key -out {out}'
                .format(req_file=request_file, out=self.CERT_FILE))

        cert, rest = decode(readPemFromFile(open(self.CERT_FILE)), asn1Spec=rfc5208.Certificate())
        self.assertFalse(rest)
        self._asn_print(cert)

        self.assertIsNotNone(cert.getComponentByName('signatureValue'))
        self.assertIsNotNone(cert.getComponentByName('signatureAlgorithm'))
        self.assertEqual(str(cert.getComponentByName('signatureAlgorithm').getComponentByName('algorithm')),
                         '1.2.112.0.2.0.34.101.45.12')
예제 #31
0
def check_signer(signer_cert, tsa_cert: str):
    """
    Verify signing certificate attribute
    """
    logging.info("Attribute Signing Certificate")
    try:
        cert_hash = signer_cert['certs'][0]['certHash']
        hash_obj = hashlib.sha1()
        substrate = pem.readPemFromFile(open(tsa_cert))
        hash_obj.update(substrate)
        logging.info("\tAttribute Value:\t" + str(cert_hash.asOctets().hex()))
        logging.info("\tCertificate Hash:\t" + str(hash_obj.digest().hex()))
        assert cert_hash == hash_obj.digest()
    except Exception as e:
        logging.error('Signer certificate hash is not equal to TSA certificate hash')
        logging.error('Check Attribute Signing Certificate: Failure', exc_info=True)
        raise e
    logging.info('Check Attribute Signing Certificate: Success\n')
    return True
예제 #32
0
    def test_x509(self):


        out = _(
            "req -x509 "
            '-subj "/CN=www.mydom.com/O=My Dom, Inc./C=US/ST=Oregon/L=Portland" '
            "-new -key priv.key -out %s" % self.CERT_FILE
        )

        cert, rest = decode(readPemFromFile(open(self.CERT_FILE)), asn1Spec=rfc5208.Certificate())
        self.assertFalse(rest)
        self._asn_print(cert)

        self.assertIsNotNone(cert.getComponentByName('signatureValue'))
        self.assertIsNotNone(cert.getComponentByName('signatureAlgorithm'))
        self.assertEqual(str(cert.getComponentByName('signatureAlgorithm').getComponentByName('algorithm')),
                         '1.2.112.0.2.0.34.101.45.12')

        self._assert_extensions(cert, ['2.5.29.14', '2.5.29.35', '2.5.29.19'])
    def handle_cert(self, pem_cert):
        fileobj = StringIO.StringIO()
        fileobj.write(pem_cert)
        fileobj.seek(0)

        substrate = pem.readPemFromFile(fileobj)
        cert = decoder.decode(substrate, asn1Spec=rfc2459.Certificate())[0]
        try:
            tbsCertificate = cert.getComponentByName('tbsCertificate')
            issuer = tbsCertificate.getComponentByName('issuer')
            rdns = issuer.getComponent()
            for entry in rdns:
                typ, value = entry[0]
                if str(typ) != '2.5.4.3':
                    continue
                name = str(decoder.decode(value)[0])

                self.ca = CertificateAuthority.objects.get_or_create(name=name)[0]
                log.debug('Valid certificate signed by %s', self.ca.get_display_name())
        except Exception as e:
            log.error('Could not parse CA: %s: %s', type(e).__name__, e)
            self.ca = None
예제 #34
0
def main():
    parser = argparse.ArgumentParser(
        description="Decode PEM encoded certificates")
    parser.add_argument("filenames",
                        nargs="+",
                        metavar="filename",
                        type=str,
                        help="Input files")
    args = parser.parse_args()
    CERT_DIR = 'example_certificates'
    key_store = {}
    certs = []
    for filename in args.filenames:
        print(filename)
        filename = os.path.join(CERT_DIR, filename)
        with open(filename) as f:
            binary_data = pem.readPemFromFile(f)
        cert, rest = der_decoder.decode(binary_data,
                                        asn1Spec=rfc2459.Certificate())
        certs.append(cert)
        tbs_cert = cert['tbsCertificate']
        issuer = common_name(tbs_cert['issuer'])
        subject = common_name(tbs_cert['subject'])
        notBefore = tbs_cert['validity']['notBefore'][0]
        notAfter = tbs_cert['validity']['notAfter'][0]
        extensions = tbs_cert['extensions']
        print('Issuer:', issuer)
        print('Subject:', subject)
        print('Validity: from')
        print('\tfrom:', notBefore.asDateTime.strftime("%d %B %Y"))
        print('\tto:', notAfter.asDateTime.strftime("%d %B %Y"))
        if can_be_used_for_signing_certificates(extensions):
            print("This key can be used to sign PK certificates")
            key_store[subject] = get_rsa_public_key(tbs_cert)
        print("_________________________________________")

    for cert in certs:
        verify_cert(cert, key_store)
    def handle_cert(self, pem_cert):
        fileobj = StringIO.StringIO()
        fileobj.write(pem_cert)
        fileobj.seek(0)

        substrate = pem.readPemFromFile(fileobj)
        cert = decoder.decode(substrate, asn1Spec=rfc2459.Certificate())[0]
        try:
            tbsCertificate = cert.getComponentByName('tbsCertificate')
            issuer = tbsCertificate.getComponentByName('issuer')
            rdns = issuer.getComponent()
            for entry in rdns:
                typ, value = entry[0]
                if str(typ) != '2.5.4.3':
                    continue
                name = str(decoder.decode(value)[0])

                self.ca = CertificateAuthority.objects.get_or_create(
                    name=name)[0]
                log.debug('Valid certificate signed by %s',
                          self.ca.get_display_name())
        except Exception as e:
            log.error('Could not parse CA: %s: %s', type(e).__name__, e)
            self.ca = None
from pyasn1.codec.der import decoder, encoder
from hashlib import sha256
import os
import binascii
import argparse
import sys
import base64

#Usage: name_certificate.pem [key_filename]

root = False
if (len(sys.argv) > 2):
    root = True

#Extract the certificate
substrate = pem.readPemFromFile(open(sys.argv[1]))
certType = rfc2459.Certificate()
cert = decoder.decode(substrate, asn1Spec=certType)[0]
tbs = cert.getComponentByName("tbsCertificate")  # Dump the TBS

if (root):
    # If the root certificate we have to change the public key with the one prodused by dkg funcionality
    f = open(sys.argv[2], "r")
    x = int(f.readline())
    y = int(f.readline())
    tbs['subjectPublicKeyInfo']['subjectPublicKey'] = format(
        "0x%02x" % 0x04) + format("%064x" % x) + format("%064x" % y)
    f = open(sys.argv[1][:-4] + ".der", "wb")
    cert.setComponentByName("tbsCertificate", tbs)
    f.write(encoder.encode(cert))
    f.close()
예제 #37
0
파일: cert.py 프로젝트: Diamorotic/pyxmpp2
 def from_file(cls, filename):
     """Load certificate from a file.
     """
     with open(filename, "r") as pem_file:
         data = pem.readPemFromFile(pem_file)
     return cls.from_der_data(data)
예제 #38
0
def read_certificate(pemfile):
    """Reads an X509-encoded certificate file."""

    substrate = pem.readPemFromFile(open(pemfile))
    return decoder.decode(substrate, asn1Spec=rfc2459.Certificate())[0]
예제 #39
0
    help=
    "Optional certificate destination, if missing, the certificate will be displayed on the screen. \
         Otherwise, it will be saved in the file.")

args = vars(ap.parse_args())

# check that sign-algorithm is present if ca-priv-key-dilithium is true
if args['ca_priv_key_dilithium'] and not args['sign_algorithm']:
    ap.error('The --ca-priv-key-dilithium argument requires --sign-algorithm')

# Load the existing certificate
ftype = None
f = open(args["cert"], 'rb')
cert_substrate = None
if f.read(27) == b'-----BEGIN CERTIFICATE-----':  # PEM handling
    cert_substrate = pem.readPemFromFile(open(args["cert"], 'r'))
    ftype = 0
else:  # DER default
    f.seek(0)
    cert_substrate = f.read()
    ftype = 1
cert = decoder.decode(cert_substrate, asn1Spec=rfc2459.Certificate())[0]
f.close()

# if ca-priv-key-dilithium is not true, we must check that the signing algorithm in place is known and uses a known hash function, otherwise, we can't do much
if args['ca_priv_key_dilithium'] and str(
        cert["tbsCertificate"]["signature"]["algorithm"]) not in SignOIDToAlgo:
    ap.error(
        "The provided certificate, which is not to be signed with Dilithium, is signed with an unknown algorithm"
    )
예제 #40
0
def read_pem_b64(path):
    with open(path, "r") as f:
        bits = pem.readPemFromFile(f)
        return base64.b64encode(bits).decode("utf-8")
예제 #41
0
 def from_file(cls, filename):
     """Load certificate from a file.
     """
     with open(filename, "r") as pem_file:
         data = pem.readPemFromFile(pem_file)
     return cls.from_der_data(data)
from pyasn1_modules import pem, rfc2437, rfc2459
from pyasn1.codec.der import decoder, encoder
from hashlib import sha256
import os
import binascii
import argparse
import sys
import ecpy
from ecpy import ecdsa

#Usage: name_certificate.pem signature_filename
if len(sys.argv) < 3:
    print("Usage: " + sys.argv[0] + " name_cert.pem and signature_filename")

substrate = pem.readPemFromFile(open(sys.argv[1]))  # Read the certificate
certType = rfc2459.Certificate()
cert = decoder.decode(substrate, asn1Spec=certType)[0]  #Extract the der format

f = open(sys.argv[2], "r")
r = int(f.readline())
s = int(f.readline())
sig = ecdsa.encode_sig(r, s, 'DER')

# Add new signature
#os.system("openssl dgst -sha256 -sign privkey_root.pem new_admin_dump.der > new_admin_sign.der")
#f = open(sys.argv[2], "rb")
#sig = f.read()
sig = int(binascii.hexlify(sig), 16)
cert.setComponentByName("signatureValue", "00" + bin(sig)[2:])

#Store the new Certificate
예제 #43
0
try:
    fhand = open(file)
except:
    print "bad file name"
    exit()

### make directory of first file the new default directory
##os.chdir(os.path.dirname(file))
##
##    # get saveas filename for output
##root = Tkinter.Tk()
##root.withdraw()
##myFormats = [
##    ('text','*.txt'),
##    ]
##
##fileName = tkFileDialog.asksaveasfilename(filetypes=myFormats ,title="Save the output text file as...")
##if len(fileName ) < 1:
##    print "bad file name"
##    exit()
##try:
##    whand = open(fileName,'w')
##except:
##    print "bad file name"
##    exit()

debug.setLogger(debug.Debug('all'))
decoder.decode.defaultErrorState = decoder.stDumpRawValue
substrate = pem.readPemFromFile(open(file))
decoder.decode(substrate)
예제 #44
0
            response0.getComponentByName('certID'),
            response0.getComponentByName('certStatus').getName(),
            response0.getComponentByName('thisUpdate'))


if len(sys.argv) != 2:
    print("""Usage:
$ cat CACertificate.pem userCertificate.pem | %s <ocsp-responder-url>""" %
          sys.argv[0])
    sys.exit(-1)
else:
    ocspUrl = sys.argv[1]

# Parse CA and user certificates

issuerCert, _ = decoder.decode(pem.readPemFromFile(sys.stdin)[1],
                               asn1Spec=rfc2459.Certificate())
userCert, _ = decoder.decode(pem.readPemFromFile(sys.stdin)[1],
                             asn1Spec=rfc2459.Certificate())

# Build OCSP request

ocspReq = mkOcspRequest(issuerCert, userCert)

# Use HTTP POST to get response (see Appendix A of RFC 2560)
# In case you need proxies, set the http_proxy env variable

httpReq = urllib2.Request(ocspUrl, encoder.encode(ocspReq),
                          {'Content-Type': 'application/ocsp-request'})
httpRsp = urllib2.urlopen(httpReq).read()
예제 #45
0
from pyasn1.codec.der import decoder, encoder

from base64 import b64encode, b64decode
from binascii import unhexlify

"""
Get a byte array for an ASN1 integer
"""
def getASNIntegerBytes(asnInt):
    hexstr = "%X" % (int(asnInt))
    print "hex string is ",hexstr
    if len(hexstr) % 2 == 1:
        return unhexlify('0'+hexstr)
    return unhexlify(hexstr)

substrate = pem.readPemFromFile(open(sys.argv[1]))
encoded = ''
lines = open(sys.argv[1],'r').readlines()
for line in lines:
    if -1 == line.find('-'):
        encoded = encoded + line.strip()
#substrate = open(sys.argv[1],'r').read()
substrate = b64decode(encoded)
cert = decoder.decode(substrate, asn1Spec=rfc2459.Certificate())[0]
#print(cert.prettyPrint())

#print("raw issuer is"+cert[0][5].prettyPrint())

print("issuer is: "+b64encode(encoder.encode(cert[0][3])))
print("serial is: "+b64encode(getASNIntegerBytes(cert[0][1])));
#for i in encoder.encode(cert[0][1])[2:]: