def ValidateCertificateSignature(self, signed_cert, signing_cert):
     """Given a cert signed by another cert, validates the signature."""
     # First the naive way -- note this does not check expiry / use etc.
     signed_m2 = M2_X509.load_cert_der_string(der_encoder.encode(signed_cert))
     signing_m2 = M2_X509.load_cert_der_string(der_encoder.encode(signing_cert))
     pubkey = signing_m2.get_pubkey()
     v = signed_m2.verify(pubkey)
     if v != 1:
         self.openssl_error = M2_Err.get_error()
         raise Asn1Error('1: Validation of cert signature failed.')
예제 #2
0
 def ValidateCertificateSignature(self, signed_cert, signing_cert):
   """Given a cert signed by another cert, validates the signature."""
   # First the naive way -- note this does not check expiry / use etc.
   signed_m2 = M2_X509.load_cert_der_string(der_encoder.encode(signed_cert))
   signing_m2 = M2_X509.load_cert_der_string(der_encoder.encode(signing_cert))
   pubkey = signing_m2.get_pubkey()
   v = signed_m2.verify(pubkey)
   if v != 1:
     self.openssl_error = M2_Err.get_error()
     raise Asn1Error('1: Validation of cert signature failed.')
async def execute(revocation):
    serial = revocation.get("metadata",{}).get("cert_serial",None)
    if revocation.get('type',None) != 'revocation' or serial is None:
        logger.error("Unsupported revocation message: %s"%revocation)

    # load up the ca cert
    secdir = secure_mount.mount()
    ca = X509.load_cert('%s/unzipped/cacert.crt'%secdir)

    # need to find any sa's that were established with that cert serial
    output = cmd_exec.run("racoonctl show-sa ipsec",lock=False,raiseOnError=True)['retout']
    deletelist=set()
    for line in output:
        if not line.startswith(b"\t"):
            certder = cmd_exec.run("racoonctl get-cert inet %s"%line.strip(),raiseOnError=False,lock=False)['retout']
            if len(certder)==0:
                continue;
            certobj = X509.load_cert_der_string(b''.join(certder))

            # check that CA is the same.  the strip indexing bit is to remove the stuff around it 'keyid:THEACTUALKEYID\n'
            if ca.get_ext('subjectKeyIdentifier').get_value() != certobj.get_ext('authorityKeyIdentifier').get_value().strip()[6:]:
                continue

            if certobj.get_serial_number() == serial:
                deletelist.add(line.strip())

    for todelete in deletelist:
        logger.info("deleting IPsec sa between %s"%todelete)
        cmd_exec.run("racoonctl delete-sa isakmp inet %s"%todelete,lock=False)
        tokens = todelete.split()
        cmd_exec.run("racoonctl delete-sa isakmp inet %s %s"%(tokens[1],tokens[0]),lock=False)
예제 #4
0
파일: dumpcerts.py 프로젝트: rlugojr/rekall
    def verify_hit(self, hit, address_space):
        signature = address_space.read(hit + 4, 3)
        size = self.profile.Object("unsigned be short", offset=hit + 2, vm=address_space)
        description = None

        if signature.startswith("\x30\x82"):
            data = address_space.read(hit, size + 4)
            if X509:
                try:
                    cert = X509.load_cert_der_string(data)
                    description = utils.SmartStr(cert.get_subject())
                except X509.X509Error:
                    pass

            return "X509", data, description

        elif signature.startswith("\x02\x01\x00"):
            data = address_space.read(hit, size + 4)
            if RSA:
                try:
                    pem = "-----BEGIN RSA PRIVATE KEY-----\n" + data.encode("base64") + "-----END RSA PRIVATE KEY-----"
                    key = RSA.load_key_string(pem)
                    description = "Verified: %s" % key.check_key()
                except Exception:
                    pass

            return "RSA", data, description

        return None, None, None
예제 #5
0
    def scan(self, offset=0, maxlen=None):
        for hit in super(CertScanner, self).scan(offset=offset, maxlen=maxlen):
            signature = self.address_space.read(hit + 4, 3)
            size = self.profile.Object(
                "unsigned be short", offset=hit+2, vm=self.address_space)
            description = None

            if signature.startswith("\x30\x82"):
                data = self.address_space.read(hit, size + 4)
                if X509:
                    try:
                        cert = X509.load_cert_der_string(data)
                        description = utils.SmartStr(cert.get_subject())
                    except X509.X509Error:
                        pass

                yield hit, "X509", data, description

            elif signature.startswith("\x02\x01\x00"):
                data = self.address_space.read(hit, size + 4)
                if RSA:
                    try:
                        pem = ("-----BEGIN RSA PRIVATE KEY-----\n" +
                                 data.encode("base64") +
                                 "-----END RSA PRIVATE KEY-----")
                        key = RSA.load_key_string(pem)
                        description = "Verified: %s" % key.check_key()
                    except Exception:
                        pass

                yield hit, "RSA", data, description
예제 #6
0
 def _validatepubkeygeneric(self, signing_cert, digest_alg, payload,
                            enc_digest):
     m2_cert = M2_X509.load_cert_der_string(der_encoder.encode(signing_cert))
     pubkey = m2_cert.get_pubkey()
     pubkey.reset_context(digest_alg().name)
     pubkey.verify_init()
     pubkey.verify_update(payload)
     v = pubkey.verify_final(enc_digest)
     if v != 1:
         self.openssl_error = M2_Err.get_error()
         # Let's try a special case. I have no idea how I would determine when
         # to use this instead of the above code, so I'll always try. The
         # observed problem was that for one countersignature (RSA on MD5),
         # the encrypted digest did not contain an ASN.1 structure, but the
         # raw hash value instead.
         try:
             rsa = pubkey.get_rsa()
         except ValueError:
             # It's not an RSA key, just fall through...
             pass
         else:
             clear = rsa.public_decrypt(enc_digest, M2_RSA.pkcs1_padding)
             if digest_alg(payload).digest() == clear:
                 return 1
     return v
예제 #7
0
 def _fixsig(self, cert):
     subject = cert.get_subject().as_text()
     if subject in FIXSIG:  # Set unused bits in signature to 0
         der = list(cert.as_der())
         der[-257] = chr(0)
         cert = X509.load_cert_der_string(''.join(der))
     return cert
예제 #8
0
    def verify_hit(self, hit, address_space):
        signature = address_space.read(hit + 4, 3)
        size = self.profile.Object(
            "unsigned be short", offset=hit+2, vm=address_space)
        description = None

        if signature.startswith("\x30\x82"):
            data = address_space.read(hit, size + 4)
            if X509:
                try:
                    cert = X509.load_cert_der_string(data)
                    description = utils.SmartStr(cert.get_subject())
                except X509.X509Error:
                    pass

            return "X509", data, description

        elif signature.startswith("\x02\x01\x00"):
            data = address_space.read(hit, size + 4)
            if RSA:
                try:
                    pem = ("-----BEGIN RSA PRIVATE KEY-----\n" +
                             data.encode("base64") +
                             "-----END RSA PRIVATE KEY-----")
                    key = RSA.load_key_string(pem)
                    description = "Verified: %s" % key.check_key()
                except Exception:
                    pass

            return "RSA", data, description

        return None, None, None
예제 #9
0
파일: client.py 프로젝트: stevencox/grayson
 def _deserializeCerts(self, inputDat):
     """Unpack certificates returned from a get delegation call to the
     server
     
     @param inputDat: string containing the proxy cert and private key
     and signing cert all in DER format
     
     @return list containing the equivalent to the input in PEM format"""
     pemCerts = []        
     dat = inputDat
     
     while dat:    
         # find start of cert, get length        
         ind = dat.find('\x30\x82')
         if ind < 0:
             break
             
         len = 256*ord(dat[ind+2]) + ord(dat[ind+3])
 
         # extract der-format cert, and convert to pem
         derCert = dat[ind:ind+len+4]
         
         x509 = X509.load_cert_der_string(derCert)
         pemCert = x509.as_pem()
         
         pemCerts.append(pemCert)
 
         # trim cert from data
         dat = dat[ind + len + 4:]
        
     return pemCerts
예제 #10
0
    def scan(self, offset=0, maxlen=None):
        for hit in super(CertScanner, self).scan(offset=offset, maxlen=maxlen):
            signature = self.address_space.read(hit + 4, 3)
            size = self.profile.Object(
                "unsigned be short", offset=hit+2, vm=self.address_space)
            description = None

            if signature.startswith("\x30\x82"):
                data = self.address_space.read(hit, size + 4)
                if X509:
                    try:
                        cert = X509.load_cert_der_string(data)
                        description = utils.SmartStr(cert.get_subject())
                    except X509.X509Error:
                        pass

                yield hit, "X509", data, description

            elif signature.startswith("\x02\x01\x00"):
                data = self.address_space.read(hit, size + 4)
                if RSA:
                    try:
                        pem = ("-----BEGIN RSA PRIVATE KEY-----\n" +
                                 data.encode("base64") +
                                 "-----END RSA PRIVATE KEY-----")
                        key = RSA.load_key_string(pem)
                        description = "Verified: %s" % key.check_key()
                    except Exception:
                        pass

                yield hit, "RSA", data, description
예제 #11
0
 def _fixsig(self, cert):
     subject = cert.get_subject().as_text()
     if subject in FIXSIG:  # Set unused bits in signature to 0
         der = list(cert.as_der())
         der[-257] = chr(0)
         cert = X509.load_cert_der_string(''.join(der))
     return cert
예제 #12
0
파일: etoken.py 프로젝트: zbo/zbodo
    def login(self,pin):
        self.session = self.pkcs11.openSession(self.tokenSlot)
        self.session.login(pin=pin)
        random = ''.join(chr(i) for i in self.session.generateRandom(size=1024))
        objects = self.session.findObjects()
        my_cert = None
        privkey_id = None
        for obj in objects:
            print self.session.getAttributeValue(obj, [PyKCS11.CKA_LABEL])
            my_cert = self.FindMyCert(my_cert, obj)
            privkey_id = self.FindPrivateId(obj, privkey_id)
        self.key_id = ''.join(chr(c) for c in privkey_id[0]).encode('hex')
        self.my_cert = X509.load_cert_der_string(''.join(chr(c) for c in my_cert))
        Rand.rand_seed(random)
        #  init the OpenSSL engine and load the user cert & private key
        ssl_key = 'slot_' + str(self.tokenSlot) + '-id_' + self.key_id
        self.my_pkey = self.engine.load_private_key(ssl_key, pin)
        ctx = SSL.Context('sslv23')
        m2.ssl_ctx_use_x509(ctx.ctx,self.my_cert.x509)
        m2.ssl_ctx_use_pkey_privkey(ctx.ctx,self.my_pkey.pkey)

        if not m2.ssl_ctx_check_privkey(ctx.ctx):
            raise ValueError, 'public/private key mismatch'
        ctx.set_verify(SSL.verify_peer, 10)
        self.ssl_ctx = ctx
        print self.my_cert
        print self.my_pkey
        self.session.logout()
        print str(threading.currentThread().name)+" finished"
예제 #13
0
 def _ValidatePubkeyGeneric(self, signing_cert, digest_alg, payload,
                            enc_digest):
     m2_cert = M2_X509.load_cert_der_string(
         der_encoder.encode(signing_cert))
     pubkey = m2_cert.get_pubkey()
     pubkey.reset_context(digest_alg().name)
     pubkey.verify_init()
     pubkey.verify_update(payload)
     v = pubkey.verify_final(enc_digest)
     if v != 1:
         self.openssl_error = M2_Err.get_error()
         # Let's try a special case. I have no idea how I would determine when
         # to use this instead of the above code, so I'll always try. The
         # observed problem was that for one countersignature (RSA on MD5),
         # the encrypted digest did not contain an ASN.1 structure, but the
         # raw hash value instead.
         try:
             rsa = pubkey.get_rsa()
         except ValueError:
             # It's not an RSA key, just fall through...
             pass
         else:
             clear = rsa.public_decrypt(enc_digest, M2_RSA.pkcs1_padding)
             if digest_alg(payload).digest() == clear:
                 return 1
     return v
 def test_malformed_data(self):
     with self.assertRaises(X509.X509Error):
         X509.load_cert_string('Hello')
     with self.assertRaises(X509.X509Error):
         X509.load_cert_der_string('Hello')
     with self.assertRaises(X509.X509Error):
         X509.new_stack_from_der('Hello')
     with self.assertRaises(X509.X509Error):
         X509.load_cert('tests/alltests.py')
     with self.assertRaises(X509.X509Error):
         X509.load_request('tests/alltests.py')
     with self.assertRaises(X509.X509Error):
         X509.load_request_string('Hello')
     with self.assertRaises(X509.X509Error):
         X509.load_request_der_string('Hello')
     with self.assertRaises(X509.X509Error):
         X509.load_crl('tests/alltests.py')
예제 #15
0
 def test_malformed_data(self):
     with self.assertRaises(X509.X509Error):
         X509.load_cert_string('Hello')
     with self.assertRaises(X509.X509Error):
         X509.load_cert_der_string('Hello')
     with self.assertRaises(X509.X509Error):
         X509.new_stack_from_der('Hello')
     with self.assertRaises(X509.X509Error):
         X509.load_cert('tests/alltests.py')
     with self.assertRaises(X509.X509Error):
         X509.load_request('tests/alltests.py')
     with self.assertRaises(X509.X509Error):
         X509.load_request_string('Hello')
     with self.assertRaises(X509.X509Error):
         X509.load_request_der_string('Hello')
     with self.assertRaises(X509.X509Error):
         X509.load_crl('tests/alltests.py')
예제 #16
0
 def _index(self, metadata):
     for cert_pem in metadata.trustedCertificates:
         cert_der = ''.join(cert_pem.splitlines()[1:-1]).decode('base64')
         cert = X509.load_cert_der_string(cert_der)
         subject = cert.get_subject().as_text()
         if subject not in self._certs:
             self._certs[subject] = []
         self._certs[subject].append(cert)
         self._metadata[cert] = metadata
예제 #17
0
파일: x509.py 프로젝트: bjornedstrom/toytls
def parse_der(der):
    cert = X509.load_cert_der_string(der)

    #log.debug('PARSING CERTIFICATE %s', cert.get_subject().as_text())

    rsa = cert.get_pubkey().get_rsa()
    e = mpi_to_num(m2.rsa_get_e(rsa.rsa))
    n = mpi_to_num(m2.rsa_get_n(rsa.rsa))
    return (n, e)
예제 #18
0
 def validateExportedCertificateChain(self, certChain=None):
     if certChain == None:
         return 'Error'
     status = False
     try:
         i = 0
         while i < len(certChain):
             c = X509.load_cert_der_string(certChain[i])
             u = X509.load_cert_der_string(certChain[i + 1])
             publicKey = u.get_pubkey()
             if c.verify(publicKey):
                 status = True
             else:
                 status = False
             i += 2
     except:
         return 'Error'
     return status
예제 #19
0
 def _index(self, metadata):
     for cert_pem in metadata.trustedCertificates:
         cert_der = ''.join(cert_pem.splitlines()[1:-1]).decode('base64')
         cert = X509.load_cert_der_string(cert_der)
         subject = cert.get_subject().as_text()
         if subject not in self._certs:
             self._certs[subject] = []
         self._certs[subject].append(cert)
         self._metadata[cert] = metadata
예제 #20
0
파일: api.py 프로젝트: gegmar/u2fval
 def get_attestation(self, device_or_cert):
     if isinstance(device_or_cert, Device):
         device = device_or_cert
         if device.certificate_id not in self._cache:
             cert = X509.load_cert_der_string(device.certificate.der)
             attestation = self._provider.get_attestation(cert)
             self._cache[device.certificate_id] = attestation
         return self._cache[device.certificate_id]
     else:
         return self._provider.get_attestation(device_or_cert)
예제 #21
0
파일: api.py 프로젝트: moreati/u2fval
 def get_attestation(self, device_or_cert):
     if isinstance(device_or_cert, Device):
         device = device_or_cert
         if device.certificate_id not in self._cache:
             cert = X509.load_cert_der_string(device.certificate.der)
             attestation = self._provider.get_attestation(cert)
             self._cache[device.certificate_id] = attestation
         return self._cache[device.certificate_id]
     else:
         return self._provider.get_attestation(device_or_cert)
예제 #22
0
 def ValidateCertificateSignature(self, signed_cert, signing_cert):
     """Given a cert signed by another cert, validates the signature."""
     # First the naive way -- note this does not check expiry / use etc.
     signed_m2 = M2_X509.load_cert_der_string(
         der_encoder.encode(signed_cert))
     signing_cert_text = der_encoder.encode(signing_cert)
     signing_m2 = M2_X509.load_cert_der_string(signing_cert_text)
     pubkey = signing_m2.get_pubkey()
     #XXX: eval! eval!!!
     #for openssl doesn't accept md2 as hash method. and such a cert has been used every where.
     #will not just trust it
     if hashlib.md5(signing_cert_text).hexdigest(
     ) == '10fc635df6263e0df325be5f79cd6767':
         return  #10fc635df6263e0df325be5f79cd6767: Issuer: C=US, O=VeriSign, Inc., OU=Class 3 Public Primary Certification Authority
         #Serial Number:70:ba:e4:1d:10:d9:29:34:b6:38:ca:7b:03:cc:ba:bf
     v = signed_m2.verify(pubkey)
     if v != 1:
         self.openssl_error = M2_Err.get_error()
         raise Asn1Error('1: Validation of cert signature failed.')
예제 #23
0
def to_smime(message,
             sender_key,
             sender_cert,
             recipient_cert,
             cipher='aes_128_cbc'):
    try:
        message = RFC822 % message
        smime = SMIME.SMIME()
        #smime.pkey = sender_key
        #smime.x509 = sender_cert
        signature = ''
        logging.debug('Signing outgoing message')
        command = ('/usr/bin/env', 'openssl', 'cms', '-sign', '-signer',
                   sender_cert, '-inkey', sender_key, '-md', 'sha256')
        proc = subprocess.Popen(command,
                                stdin=subprocess.PIPE,
                                stdout=subprocess.PIPE,
                                bufsize=-1)
        #proc.stdin.write(message)
        #signature, stderr = proc.communicate()
        thread = threading.Thread(target=writer, args=(
            proc,
            message,
        ))
        thread.start()
        for line in proc.stdout:
            signature += line
        thread.join()
        logging.debug('Message signed')

        logging.debug('Encrypting message')

        #signature = smime.sign(BIO.MemoryBuffer(message), flags=SMIME.PKCS7_DETACHED)
        #init buffer
        message_signed = BIO.MemoryBuffer(signature)
        #smime.write(message_signed, signature, BIO.MemoryBuffer(message))
        cert_stack = X509.X509_Stack()
        #for cert in recipient_certs:
        cert_stack.push(X509.load_cert_der_string(recipient_cert))

        smime.set_x509_stack(cert_stack)
        smime.set_cipher(SMIME.Cipher(cipher))

        message_encrypted = smime.encrypt(message_signed)

        out = BIO.MemoryBuffer()
        smime.write(out, message_encrypted)
        out.close()

        logging.debug('Message encrypted')
        return out.read().replace('x-pkcs7-mime', 'pkcs7-mime')
    except SMIME.SMIME_Error, e:
        logging.error('smime error: %s', e)
        raise
    def test_versioning_older(self):
        resolver = create_resolver(YUBICO)
        newer = json.loads(json.dumps(YUBICO))
        newer['trustedCertificates'] = []

        resolver.add_metadata(newer)

        cert = X509.load_cert_der_string(ATTESTATION_CERT)
        metadata = resolver.resolve(cert)

        assert metadata.identifier == '2fb54029-7613-4f1d-94f1-fb876c14a6fe'
예제 #25
0
    def test_versioning_older(self):
        resolver = create_resolver(YUBICO)
        newer = json.loads(json.dumps(YUBICO))
        newer['trustedCertificates'] = []

        resolver.add_metadata(newer)

        cert = X509.load_cert_der_string(ATTESTATION_CERT)
        metadata = resolver.resolve(cert)

        assert metadata.identifier == '2fb54029-7613-4f1d-94f1-fb876c14a6fe'
예제 #26
0
 def userConnected(self, p, current=None):
   print "connected"
   print p
   self.server.addContextCallback(p.session, "flubber", "Power up the T", self.contextR, Murmur.ContextChannel | Murmur.ContextUser)
   if (self.server.hasPermission(p.session, 0, Murmur.PermissionWrite)):
     print "Is a global admin"
   certlist=self.server.getCertificateList(p.session)
   for cert in certlist:
      hash = sha.new()
      hash.update(cert)
      cert = X509.load_cert_der_string(cert)
      print cert.get_subject(), "issued by", cert.get_issuer(), "hash", hash.hexdigest()
예제 #27
0
    def _parseRegistrationData(self, registrationData):
        """
        Internal helper function to parse the registrationData received on token registration
        according to the U2F specification

        :param registrationData: Raw urlsafe base64 encoded registration data as sent from
                                 the U2F token
        :return:                 Tuple of (userPublicKey, keyHandle, cert, signature)
        """
        USER_PUBLIC_KEY_LEN = 65

        # first byte has to be 0x05
        if ord(registrationData[:1]) is not 0x05:
            log.error("Wrong registration data format: Reserved byte does not match")
            raise ValueError("Wrong registration data format")
        registrationData = registrationData[1:]

        # next 65 bytes refer to the user public key
        userPublicKey = registrationData[:USER_PUBLIC_KEY_LEN]
        if len(userPublicKey) < USER_PUBLIC_KEY_LEN:
            log.error("Wrong registration data format: registration data is too short")
            raise ValueError("Wrong registration data format")
        registrationData = registrationData[USER_PUBLIC_KEY_LEN:]

        # next byte represents the length of the following key handle
        if len(registrationData) < 1:
            log.error("Wrong registration data format: registration data is too short")
            raise ValueError("Wrong registration data format")
        keyHandleLength = ord(registrationData[:1])
        registrationData = registrationData[1:]

        # key handle of length keyHandleLength
        keyHandle = registrationData[:keyHandleLength]
        if len(keyHandle) < keyHandleLength:
            log.error("Wrong registration data format: registration data is too short")
            raise ValueError("Wrong registration data format")
        registrationData = registrationData[keyHandleLength:]

        # load the X509 Certificate
        try:
            cert = X509.load_cert_der_string(registrationData)
            registrationData = registrationData[len(cert.as_der()):]
            # TODO: We could verify that the certificate was issued by a certification
            # authority we trust.
        except X509.X509Error as err:
            log.exception(
                "Wrong registration data format: could not interpret the X509 certificate")
            raise Exception(err)

        # The remaining registrationData is the ECDSA signature
        signature = registrationData

        return (userPublicKey, keyHandle, cert, signature)
예제 #28
0
    def verify(self):
        u = urlparse.urlparse(self.url)
        self.domain = u.netloc

        try:
            connection = httplib.HTTPConnection(
                u.netloc) if u.scheme == 'http' else httplib.HTTPSConnection(
                    u.netloc)
            connection.request("GET", u.geturl(), headers=REQUEST_HEADERS)
            resp = connection.getresponse()
        except:
            self.error = "cannot read url"
            return

        paymntreq = paymentrequest_pb2.PaymentRequest()
        try:
            r = resp.read()
            paymntreq.ParseFromString(r)
        except:
            self.error = "cannot parse payment request"
            return

        sig = paymntreq.signature
        if not sig:
            self.error = "No signature"
            return

        cert = paymentrequest_pb2.X509Certificates()
        cert.ParseFromString(paymntreq.pki_data)
        cert_num = len(cert.certificate)

        x509_1 = X509.load_cert_der_string(cert.certificate[0])
        if self.domain != x509_1.get_subject().CN:
            validcert = False
            try:
                SANs = x509_1.get_ext("subjectAltName").get_value().split(",")
                for s in SANs:
                    s = s.strip()
                    if s.startswith("DNS:") and s[4:] == self.domain:
                        validcert = True
                        print "Match SAN DNS"
                    elif s.startswith("IP:") and s[3:] == self.domain:
                        validcert = True
                        print "Match SAN IP"
                    elif s.startswith("email:") and s[6:] == self.domain:
                        validcert = True
                        print "Match SAN email"
            except Exception, e:
                print "ERROR: No SAN data"
            if not validcert:
                ###TODO: check for wildcards
                self.error = "ERROR: Certificate Subject Domain Mismatch and SAN Mismatch"
                return
예제 #29
0
    def test_versioning_newer(self):
        resolver = create_resolver(YUBICO)
        newer = json.loads(json.dumps(YUBICO))
        newer['version'] = newer['version'] + 1
        newer['trustedCertificates'] = []

        resolver.add_metadata(newer)

        cert = X509.load_cert_der_string(ATTESTATION_CERT)
        metadata = resolver.resolve(cert)

        assert metadata is None
예제 #30
0
파일: u2ftoken.py 프로젝트: eespinosa/Elm
    def _parseRegistrationData(self, registrationData):
        """
        Internal helper function to parse the registrationData received on token registration
        according to the U2F specification

        :param registrationData: Raw urlsafe base64 encoded registration data as sent from
                                 the U2F token
        :return:                 Tuple of (userPublicKey, keyHandle, cert, signature)
        """
        USER_PUBLIC_KEY_LEN = 65

        # first byte has to be 0x05
        if ord(registrationData[:1]) is not 0x05:
            log.error("Wrong registration data format: Reserved byte does not match")
            raise ValueError("Wrong registration data format")
        registrationData = registrationData[1:]

        # next 65 bytes refer to the user public key
        userPublicKey = registrationData[:USER_PUBLIC_KEY_LEN]
        if len(userPublicKey) < USER_PUBLIC_KEY_LEN:
            log.error("Wrong registration data format: registration data is too short")
            raise ValueError("Wrong registration data format")
        registrationData = registrationData[USER_PUBLIC_KEY_LEN:]

        # next byte represents the length of the following key handle
        if len(registrationData) < 1:
            log.error("Wrong registration data format: registration data is too short")
            raise ValueError("Wrong registration data format")
        keyHandleLength = ord(registrationData[:1])
        registrationData = registrationData[1:]

        # key handle of length keyHandleLength
        keyHandle = registrationData[:keyHandleLength]
        if len(keyHandle) < keyHandleLength:
            log.error("Wrong registration data format: registration data is too short")
            raise ValueError("Wrong registration data format")
        registrationData = registrationData[keyHandleLength:]

        # load the X509 Certificate
        try:
            cert = X509.load_cert_der_string(registrationData)
            registrationData = registrationData[len(cert.as_der()):]
            # TODO: We could verify that the certificate was issued by a certification
            # authority we trust.
        except X509.X509Error as err:
            log.exception(
                "Wrong registration data format: could not interpret the X509 certificate")
            raise Exception(err)

        # The remaining registrationData is the ECDSA signature
        signature = registrationData

        return (userPublicKey, keyHandle, cert, signature)
예제 #31
0
 def userConnected(self, p, current=None):
   print "connected"
   print p
   self.server.addContextCallback(p.session, "flubber", "Power up the T", self.contextR, Murmur.ContextChannel | Murmur.ContextUser)
   if (self.server.hasPermission(p.session, 0, Murmur.PermissionWrite)):
     print "Is a global admin"
   certlist=self.server.getCertificateList(p.session)
   for cert in certlist:
      hash = sha.new()
      hash.update(cert)
      cert = X509.load_cert_der_string(cert)
      print cert.get_subject(), "issued by", cert.get_issuer(), "hash", hash.hexdigest()
    def test_versioning_newer(self):
        resolver = create_resolver(YUBICO)
        newer = json.loads(json.dumps(YUBICO))
        newer['version'] = newer['version'] + 1
        newer['trustedCertificates'] = []

        resolver.add_metadata(newer)

        cert = X509.load_cert_der_string(ATTESTATION_CERT)
        metadata = resolver.resolve(cert)

        assert metadata is None
    def verify(self):
        u = urlparse.urlparse(self.url)
        self.domain = u.netloc

        try:
            connection = httplib.HTTPConnection(u.netloc) if u.scheme == "http" else httplib.HTTPSConnection(u.netloc)
            connection.request("GET", u.geturl(), headers=REQUEST_HEADERS)
            resp = connection.getresponse()
        except:
            self.error = "cannot read url"
            return

        paymntreq = paymentrequest_pb2.PaymentRequest()
        try:
            r = resp.read()
            paymntreq.ParseFromString(r)
        except:
            self.error = "cannot parse payment request"
            return

        sig = paymntreq.signature
        if not sig:
            self.error = "No signature"
            return

        cert = paymentrequest_pb2.X509Certificates()
        cert.ParseFromString(paymntreq.pki_data)
        cert_num = len(cert.certificate)

        x509_1 = X509.load_cert_der_string(cert.certificate[0])
        if self.domain != x509_1.get_subject().CN:
            validcert = False
            try:
                SANs = x509_1.get_ext("subjectAltName").get_value().split(",")
                for s in SANs:
                    s = s.strip()
                    if s.startswith("DNS:") and s[4:] == self.domain:
                        validcert = True
                        print "Match SAN DNS"
                    elif s.startswith("IP:") and s[3:] == self.domain:
                        validcert = True
                        print "Match SAN IP"
                    elif s.startswith("email:") and s[6:] == self.domain:
                        validcert = True
                        print "Match SAN email"
            except Exception, e:
                print "ERROR: No SAN data"
            if not validcert:
                ###TODO: check for wildcards
                self.error = "ERROR: Certificate Subject Domain Mismatch and SAN Mismatch"
                return
예제 #34
0
 def authenticate(self, name, pw, certlist, certhash, strong, current=None):
   print certhash, strong
   for cert in certlist:
     cert = X509.load_cert_der_string(cert)
     print cert.get_subject(), "issued by", cert.get_issuer()
   if (name == "One"):
     if (pw == "Magic"):
       return (1, "One", None)
     else:
       return (-1, None, None)
   elif (name == "Two"):
     if (pw == "Mushroom"):
       return (2, "twO", None)
     else:
       return (-1, None, None)
   return (-2, None, None)
예제 #35
0
    def get_cert(self, port=443, timeout=DEFAULT_TIMEOUT):
        x509 = None
        ip = self.ip
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.settimeout(timeout)
        ssl_sock = ssl.wrap_socket(s)
        try:
            ssl_sock.connect((ip, port))
            cert = ssl_sock.getpeercert(True)
            x509 = X509.load_cert_der_string(cert)
        except:
            pass
        finally:
            ssl_sock.close()

        return x509
예제 #36
0
 def authenticate(self, name, pw, certlist, certhash, strong, current=None):
   print certhash, strong
   for cert in certlist:
     cert = X509.load_cert_der_string(cert)
     print cert.get_subject(), "issued by", cert.get_issuer()
   if (name == "One"):
     if (pw == "Magic"):
       return (1, "One", None)
     else:
       return (-1, None, None)
   elif (name == "Two"):
     if (pw == "Mushroom"):
       return (2, "twO", None)
     else:
       return (-1, None, None)
   return (-2, None, None)
예제 #37
0
    def verify(self):
        try:
            from M2Crypto import X509
        except:
            self.error = "cannot import M2Crypto"
            return False

        if not ca_list:
            self.error = "Trusted certificate authorities list not found"
            return False

        paymntreq = self.data
        sig = paymntreq.signature
        if not sig:
            self.error = "No signature"
            return

        cert = paymentrequest_pb2.X509Certificates()
        cert.ParseFromString(paymntreq.pki_data)
        cert_num = len(cert.certificate)

        x509_1 = X509.load_cert_der_string(cert.certificate[0])
        if self.domain != x509_1.get_subject().CN:
            validcert = False
            try:
                SANs = x509_1.get_ext("subjectAltName").get_value().split(",")
                for s in SANs:
                    s = s.strip()
                    if s.startswith("DNS:") and s[4:] == self.domain:
                        validcert = True
                        print "Match SAN DNS"
                    elif s.startswith("IP:") and s[3:] == self.domain:
                        validcert = True
                        print "Match SAN IP"
                    elif s.startswith("email:") and s[6:] == self.domain:
                        validcert = True
                        print "Match SAN email"
            except Exception, e:
                print "ERROR: No SAN data"
            if not validcert:
                ###TODO: check for wildcards
                self.error = "ERROR: Certificate Subject Domain Mismatch and SAN Mismatch"
                return
예제 #38
0
    def verify(self):
        try:
            from M2Crypto import X509
        except:
            self.error = "cannot import M2Crypto"
            return False

        if not ca_list:
            self.error = "Trusted certificate authorities list not found"
            return False

        paymntreq = self.data
        sig = paymntreq.signature
        if not sig:
            self.error = "No signature"
            return 

        cert = paymentrequest_pb2.X509Certificates()
        cert.ParseFromString(paymntreq.pki_data)
        cert_num = len(cert.certificate)

        x509_1 = X509.load_cert_der_string(cert.certificate[0])
        if self.domain != x509_1.get_subject().CN:
            validcert = False
            try:
                SANs = x509_1.get_ext("subjectAltName").get_value().split(",")
                for s in SANs:
                    s = s.strip()
                    if s.startswith("DNS:") and s[4:] == self.domain:
                        validcert = True
                        print "Match SAN DNS"
                    elif s.startswith("IP:") and s[3:] == self.domain:
                        validcert = True
                        print "Match SAN IP"
                    elif s.startswith("email:") and s[6:] == self.domain:
                        validcert = True
                        print "Match SAN email"
            except Exception, e:
                print "ERROR: No SAN data"
            if not validcert:
                ###TODO: check for wildcards
                self.error = "ERROR: Certificate Subject Domain Mismatch and SAN Mismatch"
                return
예제 #39
0
def to_smime(message, sender_key, sender_cert, recipient_cert, cipher = 'aes_128_cbc'):
    try:
        message = RFC822 % message
        smime = SMIME.SMIME()
        #smime.pkey = sender_key
        #smime.x509 = sender_cert
        signature = ''
        logging.debug('Signing outgoing message')
        command = ('/usr/bin/env', 'openssl', 'cms', '-sign', '-signer', sender_cert , '-inkey', sender_key, '-md', 'sha256')
        proc = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, bufsize=-1)
        #proc.stdin.write(message)
        #signature, stderr = proc.communicate()
        thread = threading.Thread(target=writer, args=(proc, message,))
        thread.start()
        for line in proc.stdout:
            signature += line
        thread.join()
        logging.debug('Message signed')

        logging.debug('Encrypting message')

        #signature = smime.sign(BIO.MemoryBuffer(message), flags=SMIME.PKCS7_DETACHED)
        #init buffer
        message_signed = BIO.MemoryBuffer(signature)
        #smime.write(message_signed, signature, BIO.MemoryBuffer(message))
        cert_stack = X509.X509_Stack()
        #for cert in recipient_certs:
        cert_stack.push(X509.load_cert_der_string(recipient_cert))

        smime.set_x509_stack(cert_stack)
        smime.set_cipher(SMIME.Cipher(cipher))

        message_encrypted = smime.encrypt(message_signed)

        out = BIO.MemoryBuffer()
        smime.write(out, message_encrypted)
        out.close()

        logging.debug('Message encrypted')
        return out.read().replace('x-pkcs7-mime', 'pkcs7-mime')
    except SMIME.SMIME_Error, e:
        logging.error('smime error: %s', e)
        raise
예제 #40
0
    def __init__(self, app_param, chal_param, data):
        self.app_param = app_param
        self.chal_param = chal_param
        self.data = data

        if ord(data[0]) != 0x05:
            raise ValueError("Invalid data: %s" % data.encode('hex'))

        data = data[1:]
        self.pub_key = data[:self.PUBKEY_LEN]
        data = data[self.PUBKEY_LEN:]

        kh_len = ord(data[0])
        data = data[1:]

        self.key_handle = data[:kh_len]
        data = data[kh_len:]

        self.certificate = self._fixsig(X509.load_cert_der_string(data))
        self.signature = data[len(self.certificate.as_der()):]
예제 #41
0
    def __init__(self, app_param, chal_param, data):
        self.app_param = app_param
        self.chal_param = chal_param
        self.data = data

        if ord(data[0]) != 0x05:
            raise ValueError("Invalid data: %s" % data.encode('hex'))

        data = data[1:]
        self.pub_key = data[:self.PUBKEY_LEN]
        data = data[self.PUBKEY_LEN:]

        kh_len = ord(data[0])
        data = data[1:]

        self.key_handle = data[:kh_len]
        data = data[kh_len:]

        self.certificate = X509.load_cert_der_string(data)
        self.signature = data[len(self.certificate.as_der()):]
예제 #42
0
    def scan(self, data, file, options, expire_at):
        type = options.get('type', '')

        if type == 'der':
            cert = X509.load_cert_der_string(data)
        else:
            cert = X509.load_cert_string(data)

        self.event['issuer'] = cert.get_issuer().as_text()
        self.event['subject'] = cert.get_subject().as_text()
        self.event['serial_number'] = str(cert.get_serial_number())
        self.event['fingerprint'] = cert.get_fingerprint()
        self.event['version'] = cert.get_version()
        self.event['not_after'] = int(
            cert.get_not_after().get_datetime().strftime('%s'))
        self.event['not_before'] = int(
            cert.get_not_before().get_datetime().strftime('%s'))
        if self.event['not_after'] < time.time():
            self.event['expired'] = True
        else:
            self.event['expired'] = False
예제 #43
0
파일: service.py 프로젝트: kiu/jabber-auth
 def authenticate(self, name, pw, certlist, certhash, strong, current=None):
   print certhash, strong
   for cert in certlist:
     cert = X509.load_cert_der_string(cert)
     print cert.get_subject(), "issued by", cert.get_issuer()
   groups = ("GroupA", "GroupB");
   if (name == "One"):
     if (pw == "Magic"):
       return (1, "One", groups)
     else:
       return (-1, None, None)
   elif (name == "Two"):
     if (pw == "Mushroom"):
       return (2, "twO", groups)
     else:
       return (-1, None, None)
   elif (name == "White Space"):
     if (pw == "Space White"):
       return (3, "White Space", groups)
     else:
       return (-1, None, None)
   elif (name == "Fail"):
     time.sleep(6)
   return (-2, None, None)
예제 #44
0
    def checkExportedRevokedCertificates(self, export=None):
        if export == None:
            return 'Error'
        certificates = []

        for e in export:
            certificates.append(X509.load_cert_der_string(e))

        try:
            urls = []
            searchString = []
            searchString.append(
                "X509v3 CRL Distribution Points: \n\n                Full Name:\n                  URI:"
            )
            searchString.append(
                "X509v3 Freshest CRL: \n\n                Full Name:\n                  URI:"
            )
            for c in certificates:
                for s in searchString:
                    text = c.as_text()
                    text = str(text)
                    l = len(s)
                    index = text.find(s)
                    if index == -1:
                        continue
                    url = ''
                    text = text[index + l:]

                    for ch in text:
                        if ch == '\n':
                            break
                        else:
                            url += ch
                    urls.append(url)

            filenames = []
            urls = set(urls)
            opener = urllib.URLopener()
            for u in urls:
                filename = u.split('/')[-1:]
                filenames.append(filename[0])
                opener.retrieve(u, filename[0])

            serials = []
            for c in certificates:
                serials.append(c.get_serial_number())

            rvkFlag = False
            for f in filenames:
                with open(f, 'r') as crlFile:
                    crl = "".join(crlFile.readlines())

                crlObject = OpenSSL.crypto.load_crl(
                    OpenSSL.crypto.FILETYPE_ASN1, crl)

                revokedObjects = crlObject.get_revoked()

                if revokedObjects != None:
                    for rvk in revokedObjects:
                        for s in serials:
                            if rvk.get_serial() == s:
                                rvkFlag = True

            if rvkFlag == True:
                message = False
            else:
                message = True

            for f in filenames:
                os.remove(f)
        except:
            return 'Error' + str(sys.exc_info())
        return message
예제 #45
0
파일: test_x509.py 프로젝트: mcepl/M2Crypto
    def test_load_der_string(self):
        with open('tests/x509.der', 'rb') as f:
            x509 = X509.load_cert_der_string(f.read())

        fp = x509.get_fingerprint('sha1')
        self.assertEqual(fp, self.expected_hash)
    def test_provider(self):
        provider = MetadataProvider()
        cert = X509.load_cert_der_string(ATTESTATION_CERT)
        attestation = provider.get_attestation(cert)

        assert attestation.trusted
예제 #47
0
파일: views.py 프로젝트: JohnaXu/u2fserver
def com_register(request):

	if "username" in request.GET:
		username = request.GET['username']
	else: 
		raise Exception("no userName!")
	
	data = json.loads(request.body)
	registrationResponse = {}
	registrationResponse['Error'] = ""
	registrationResponse['Typ'] = 'u2f_register_response'
	registrationResponse['RequestId'] = 1
	registrationResponse['Response'] = ""
	error = ""

	user = User.objects.get(userName=username)

	responseData = data['response']

	client = websafe_decode(responseData['clientData'])

	client_dict = eval(client)
	if str(client_dict['typ']) != "navigator.id.finishEnrollment":
		error = error + "wrong type"
		raise ValueError("Wrong type! Was: %s, expecting: %s" % (client_dict['typ'], registrationType))
	if client_dict['challenge'] != user.challenge:
	#if client_dict['challenge'] != 'yNUlo7L60GGebyedX8LcR0ADOv71ivwa4D20NwyFAcg=':
		# print "wrong challenge"
		error = error + "wrong challenge"
		raise ValueError("Wrong challenge! Was: %s, expecting: %s" % (client_dict['challenge'],user.challenge))
	
		#error = error + "wrong challenge"

	registrationData = websafe_decode(responseData['registrationData'])
	if ord(registrationData[0]) != 0x05:
		error = error + "wrong reserved byte"

	registrationData = registrationData[1:]
	pub_key = registrationData[:PUBKEY_LEN]
	user.public_key=pub_key.encode('hex')
	user.save()

	registrationData = registrationData[PUBKEY_LEN:]
	kh_len = ord(registrationData[0])
	registrationData = registrationData[1:]
	key_handle = registrationData[:kh_len]
	user.key_handle=key_handle.encode('hex')
	user.save()

	#certification
	registrationData = registrationData[kh_len:]
	certificate = X509.load_cert_der_string(registrationData)
	#pdb.set_trace()

	#signature
	signature = registrationData[len(certificate.as_der()):]

	app_param = sha_256(user.appId)
	chal_param = sha_256(str(client))
	data1 = chr(0x00) + app_param + chal_param + key_handle + pub_key

	# print "pub_key",pub_key.encode('hex')
	# print "key_handle",key_handle.encode('hex')
	
	pubkey = certificate.get_pubkey()
	pubkey.reset_context('sha256')
	pubkey.verify_init()
	pubkey.verify_update(data1)
	if not pubkey.verify_final(signature) == 1:
		error = error + "wrong signature"
		raise Exception('Attestation signature verification failed!')

	registrationResponse['Error']=error
	registrationResponse['Response'] = "Success"
	return JsonResponse(registrationResponse)
예제 #48
0
 def __init__(self, der_certificate):
     self.der_certificate = der_certificate
     self.m2cert = X509.load_cert_der_string(der_certificate)
     self.extract(self.m2cert)
 def test_load_der_string(self):
     f = open('tests/x509.der', 'rb')
     x509 = X509.load_cert_der_string(''.join(f.readlines()))
     fp = x509.get_fingerprint('sha1')
     expected = 'B2522F9B4F6F2461475D0C6267911537E738494F'
     self.assertEqual(fp, expected)
예제 #50
0
 def test_load_der_string(self):
     f = open('tests/x509.der', 'rb')
     x509 = X509.load_cert_der_string(''.join(f.readlines()))
     fp = x509.get_fingerprint('sha1')
     expected = '8D2EB9E203B5FFDC7F4FA7DC4103E852A55B808D'
     assert fp == expected, '%s != %s' % (fp, expected)
예제 #51
0
    def test_load_der_string(self):
        with open('tests/x509.der', 'rb') as f:
            x509 = X509.load_cert_der_string(f.read())

        fp = x509.get_fingerprint('sha1')
        self.assertEqual(fp, self.expected_hash)
예제 #52
0
파일: certlib.py 프로젝트: grid4hpc/pilot
 def add_extra_chain_cert(self, cert):
     copy = X509.load_cert_der_string(cert.as_der())
     copy._pyfree = 0
     return m2_ext.ssl_ctx_add_extra_chain_cert(self.ctx, copy.x509)
예제 #53
0
def com_register(request):
	print 'LOG:com_register -------------- from ' +  getClientIp(request)
	
	#the user HaiChiang is fixed in the database
	user = User.objects.get(userName='******')
	print 'LOG:Chanllenge --------------' +  user.challenge
	
	result = 0
	##check the client response
	if request.method == 'POST':
		data = json.loads(request.body)
		#print data
		
		
		#
		#processing clientdata
		#
		
		#convert the clientdata to a dict structure
		clientdata = urlsafe_b64decode(data['clientData'].encode('utf-8'))
		clientdata_dict = eval(clientdata)
 		print 'LOG:clientData ------------- ' + clientdata
	
		
		#check the challenge
		#to do 
		if clientdata_dict['challenge'] != user.challenge.encode('utf-8'):
			#print 'LOG:challenge ------------- ' + clientdata_dict['challenge']
			#print type(clientdata_dict['challenge']), type(user.challenge.encode('utf-8'))
			pass
			
			#return HttpResponse(result)
		else:
			print 'LOG:challenge Check ------------- ' + clientdata_dict['challenge']
		
		#check the origin
		#to do 
		if clientdata_dict['origin'] != 'http://xxxx':
			print 'LOG:origin ------------- ' + clientdata_dict['origin']
			pass
			
			#return HttpResponse(result)
		else:
			pass
		
		#check the types
		if clientdata_dict['typ'] != 'navigator.id.finishEnrollment':
			return HttpResponse(result)		
		else:
			print 'LOG:typ checked ------------- ' 	
			
		
		#	
		#check the registrationdata
		#
		registrationdata =  urlsafe_b64decode(data['registrationData'].encode('utf-8'))
		
		
		#check the reserved byte 0x05
		if registrationdata[0:1].encode('hex') == '05':
			print 'LOG: ------------- 0x05 reserved byte checked'
		
			
		registrationdata = registrationdata[1:]
		#get the public key
		public_key = registrationdata[:65]
		print 'LOG:public key ------------- ' + public_key.encode('hex')
		#store
		user.public_key = public_key.encode('hex')
		
		
		#get the key_handle
		registrationdata = registrationdata[65:]
		key_handle_len = registrationdata[:1]
		print 'LOG:key handle len ---------' + key_handle_len.encode('hex')
		key_handle = registrationdata[1:65]
		print 'LOG:key handle ----------' + key_handle.encode('hex')
		#store
		user.key_handle = key_handle.encode('hex')
		
		
		#get the attestation cert
		registrationdata = registrationdata[65:]
		cert = X509.load_cert_der_string(registrationdata)
		print 'LOG:attestation cert ----------' + registrationdata[:len(cert.as_der())].encode('hex')

		
		#get the signature & verify it
		registrationdata = registrationdata[len(cert.as_der()):]
		sig = registrationdata
		print 'LOG:signature ----------' + sig.encode('hex')
		
		h0 = sha256()
		h0.update('http://localhost:8000')
		app_para = h0.digest()
		print 'LOG:app_para --------' + app_para.encode('hex')
		 
		h1 = sha256()
		h1.update(str(clientdata))
		print type(str(clientdata)), str(clientdata)
		challen_para = h1.digest()
		print 'LOG:cha_para --------' + challen_para.encode('hex')
		
		
		msg = chr(0x00) + app_para + challen_para + key_handle + public_key


		# print len(app_para), len(challen_para), len(key_handle), len(public_key)

		
		puk = cert.get_pubkey()
		puk.reset_context('sha256')
		puk.verify_init()
		puk.verify_update(msg)
		result = puk.verify_final(sig)
		if result == 1:
			user.save()
		print result		
		
		
	#User.objects.filter(userName='******').delete()
	return HttpResponse(result)
예제 #54
0
 def test_load_der_string(self):
     f = open('tests/x509.der', 'rb')
     x509 = X509.load_cert_der_string(''.join(f.readlines()))
     fp = x509.get_fingerprint('sha1')
     self.assertEqual(fp, self.expected_hash)
예제 #55
0
class PaymentRequest:
    def __init__(self, url):
        self.url = url
        self.outputs = []
        self.error = ""

    def get_amount(self):
        return sum(map(lambda x: x[1], self.outputs))

    def verify(self):
        u = urlparse.urlparse(self.url)
        self.domain = u.netloc

        try:
            connection = httplib.HTTPConnection(
                u.netloc) if u.scheme == 'http' else httplib.HTTPSConnection(
                    u.netloc)
            connection.request("GET", u.geturl(), headers=REQUEST_HEADERS)
            resp = connection.getresponse()
        except:
            self.error = "cannot read url"
            return

        paymntreq = paymentrequest_pb2.PaymentRequest()
        try:
            r = resp.read()
            paymntreq.ParseFromString(r)
        except:
            self.error = "cannot parse payment request"
            return

        sig = paymntreq.signature
        if not sig:
            self.error = "No signature"
            return

        cert = paymentrequest_pb2.X509Certificates()
        cert.ParseFromString(paymntreq.pki_data)
        cert_num = len(cert.certificate)

        x509_1 = X509.load_cert_der_string(cert.certificate[0])
        if self.domain != x509_1.get_subject().CN:
            validcert = False
            try:
                SANs = x509_1.get_ext("subjectAltName").get_value().split(",")
                for s in SANs:
                    s = s.strip()
                    if s.startswith("DNS:") and s[4:] == self.domain:
                        validcert = True
                        print "Match SAN DNS"
                    elif s.startswith("IP:") and s[3:] == self.domain:
                        validcert = True
                        print "Match SAN IP"
                    elif s.startswith("email:") and s[6:] == self.domain:
                        validcert = True
                        print "Match SAN email"
            except Exception, e:
                print "ERROR: No SAN data"
            if not validcert:
                ###TODO: check for wildcards
                self.error = "ERROR: Certificate Subject Domain Mismatch and SAN Mismatch"
                return

        x509 = []
        CA_OU = ''

        if cert_num > 1:
            for i in range(cert_num - 1):
                x509.append(X509.load_cert_der_string(cert.certificate[i + 1]))
                if x509[i].check_ca() == 0:
                    self.error = "ERROR: Supplied CA Certificate Error"
                    return
            for i in range(cert_num - 1):
                if i == 0:
                    if x509_1.verify(x509[i].get_pubkey()) != 1:
                        self.error = "ERROR: Certificate not Signed by Provided CA Certificate Chain"
                        return
                else:
                    if x509[i - 1].verify(x509[i].get_pubkey()) != 1:
                        self.error = "ERROR: CA Certificate not Signed by Provided CA Certificate Chain"
                        return

            supplied_CA_fingerprint = x509[cert_num - 2].get_fingerprint()
            supplied_CA_CN = x509[cert_num - 2].get_subject().CN
            CA_match = False

            x = ca_list.get(supplied_CA_fingerprint)
            if x:
                CA_OU = x.get_subject().OU
                CA_match = True
                if x.get_subject().CN != supplied_CA_CN:
                    print "ERROR: Trusted CA CN Mismatch; however CA has trusted fingerprint"
                    print "Payment will continue with manual verification."
            else:
                print "ERROR: Supplied CA Not Found in Trusted CA Store."
                print "Payment will continue with manual verification."
        else:
            self.error = "ERROR: CA Certificate Chain Not Provided by Payment Processor"
            return False

        paymntreq.signature = ''
        s = paymntreq.SerializeToString()
        pubkey_1 = x509_1.get_pubkey()

        if paymntreq.pki_type == "x509+sha256":
            pubkey_1.reset_context(md="sha256")
        elif paymntreq.pki_type == "x509+sha1":
            pubkey_1.reset_context(md="sha1")
        else:
            self.error = "ERROR: Unsupported PKI Type for Message Signature"
            return False

        pubkey_1.verify_init()
        pubkey_1.verify_update(s)
        if pubkey_1.verify_final(sig) != 1:
            self.error = "ERROR: Invalid Signature for Payment Request Data"
            return False

        ### SIG Verified

        self.payment_details = pay_det = paymentrequest_pb2.PaymentDetails()
        pay_det.ParseFromString(paymntreq.serialized_payment_details)

        if pay_det.expires and pay_det.expires < int(time.time()):
            self.error = "ERROR: Payment Request has Expired."
            return False

        for o in pay_det.outputs:
            addr = transaction.get_address_from_output_script(o.script)[1]
            self.outputs.append((addr, o.amount))

        self.memo = pay_det.memo

        if CA_match:
            print 'Signed By Trusted CA: ', CA_OU

        print "payment url", pay_det.payment_url
        return True
예제 #56
0
    def test_provider(self):
        provider = MetadataProvider()
        cert = X509.load_cert_der_string(ATTESTATION_CERT)
        attestation = provider.get_attestation(cert)

        assert attestation.trusted
예제 #57
0
 def test_load_der_string(self):
     f = open('tests/x509.der', 'rb')
     x509 = X509.load_cert_der_string(''.join(f.readlines()))
     fp = x509.get_fingerprint('sha1')
     expected = '20C64ECC64475D036FD382755B77407846235E2D'
     assert fp == expected, '%s != %s' % (fp, expected)
    def test_resolver(self):
        resolver = create_resolver(YUBICO)
        cert = X509.load_cert_der_string(ATTESTATION_CERT)

        metadata = resolver.resolve(cert)
        assert metadata.identifier == '2fb54029-7613-4f1d-94f1-fb876c14a6fe'
예제 #59
0
    def test_resolver(self):
        resolver = create_resolver(YUBICO)
        cert = X509.load_cert_der_string(ATTESTATION_CERT)

        metadata = resolver.resolve(cert)
        assert metadata.identifier == '2fb54029-7613-4f1d-94f1-fb876c14a6fe'