Exemple #1
0
 def _verify_signature(
     self,
     transmission_id,
     timestamp,
     webhook_id,
     event_body,
     cert,
     actual_sig,
     auth_algo,
 ):
     """Verify that the webhook payload received is from PayPal,
     unaltered and targeted towards correct recipient
     """
     expected_sig = self._get_expected_sig(transmission_id, timestamp,
                                           webhook_id, event_body)
     try:
         crypto.verify(
             cert,
             base64.b64decode(actual_sig),
             expected_sig.encode("utf-8"),
             auth_algo,
         )
         return True
     except Exception as e:
         raise PaypalError(e)
Exemple #2
0
def validate_key_cert(key_file, cert_file):
    try:
        error_key_name = "private key"
        error_filename = key_file
        key_str = open(key_file, "r").read()
        key = crypto.load_privatekey(crypto.FILETYPE_PEM, key_str)

        error_key_name = "certficate"
        error_filename = cert_file
        cert_str = open(cert_file, "r").read()
        cert = crypto.load_certificate(crypto.FILETYPE_PEM, cert_str)
    except IOError as ioe:
        raise RuntimeError(
            _("There is a problem with your %s "
              "%s.  Please verify it.  Error: %s") %
            (error_key_name, error_filename, ioe))
    except crypto.Error as ce:
        raise RuntimeError(
            _("There is a problem with your %s "
              "%s.  Please verify it. OpenSSL error: %s") %
            (error_key_name, error_filename, ce))

    try:
        data = str(uuid.uuid4())
        digest = "sha1"

        out = crypto.sign(key, data, digest)
        crypto.verify(cert, out, data, digest)
    except crypto.Error as ce:
        raise RuntimeError(
            _("There is a problem with your key pair.  "
              "Please verify that cert %s and key %s "
              "belong together.  OpenSSL error %s") %
            (cert_file, key_file, ce))
Exemple #3
0
def verify_signature(cert, signature, signed_data):
    try:
        signature = base64.b64decode(signature)
        crypto.verify(cert, signature, signed_data, 'sha1')
    except crypto.Error:
        return False
    return True
 def _is_key_consistent(self, key_public_data, key_private_data):
     openssl_key_type = self.key.type()
     if crypto.TYPE_RSA == openssl_key_type:
         try:
             return self.key.check()
         except crypto.Error:
             # OpenSSL error means that key is not consistent
             return False
     if crypto.TYPE_DSA == openssl_key_type:
         result = _check_dsa_consistency(key_public_data, key_private_data)
         if result is not None:
             return result
         signature = crypto.sign(self.key, SIGNATURE_TEST_DATA, 'sha256')
         # Verify wants a cert (where it can get the public key from)
         cert = crypto.X509()
         cert.set_pubkey(self.key)
         try:
             crypto.verify(cert, signature, SIGNATURE_TEST_DATA, 'sha256')
             return True
         except crypto.Error:
             return False
     # If needed and if possible, fall back to cryptography
     if PYOPENSSL_VERSION >= LooseVersion('16.1.0') and CRYPTOGRAPHY_FOUND:
         return _is_cryptography_key_consistent(
             self.key.to_cryptography_key(), key_public_data,
             key_private_data)
     return None
Exemple #5
0
    def _validate_signature(self):
        """Generate signing string and validate signature"""
        signing_string = '{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n'.format(
            'Message',
            self._message_encoded,
            'MessageId',
            self._message_id,
            'Timestamp',
            self._timestamp,
            'TopicArn',
            self._topic_arn,
            'Type',
            self._type)

        crt = crypto.load_certificate(crypto.FILETYPE_PEM, self._pem)
        signature = base64.b64decode(self._signature)

        try:
            crypto.verify(
                crt,
                signature,
                signing_string.encode('utf-8'),
                'sha1')
        except:
            self.error = 'Invalid signature.'
            raise ValueError('Invalid signature.')

        return True
Exemple #6
0
def verifyCertificateSignature(certificate, ca_certificate):

    # Get the signature algorithm
    algorithm = certificate.get_signature_algorithm()
    cert_asn1 = crypto.dump_certificate(crypto.FILETYPE_ASN1, certificate)

    # Decode the certificate
    der = asn1.DerSequence()
    der.decode(cert_asn1)

    # Der is [certificate, signature algorithm, signature]
    der_cert = der[0]
    der_algo = der[1]
    der_sig = der[2]

    # Decode signature
    der_sigTemp = asn1.DerObject()
    der_sigTemp.decode(der_sig)

    # Get the signature
    sig = der_sigTemp.payload[1:]

    # Verify the certificate
    try:
        crypto.verify(ca_certificate, sig, der_cert, bytesToString(algorithm))
        return True
    except crypto.Error as e:
        return False
Exemple #7
0
    def _verify_signature(self, post_data):
        """
        校验响应内容
        :param string post_data: 银联返回数据
        :return: 是否验证通过
        """
        # TODO: 银联SB, 回传的数据都没有经过URI_ENCODE
        param = dict(urlparse.parse_qsl(post_data))
        param["signature"] = param["signature"].replace(" ", "+")

        # 公钥
        cert_id = int(param["certId"])
        if cert_id not in self.pubkey_dict:
            logging.error("certid %s (%s) not exist", cert_id, param)
            return False, None

        pub_x509 = self.pubkey_dict[cert_id]

        # 构造带签名字符串
        signature = base64.b64decode(param["signature"])
        param = self._filter_param(param)
        temp_str, param_keys = "", param.keys()
        for k in sorted(param_keys):
            temp_str += "%s=%s&" % (k, param[k])
        temp_str = hashlib.sha1(temp_str[:-1]).hexdigest()
        try:
            crypto.verify(pub_x509, signature, temp_str, "sha1")
            return True, param
        except crypto.Error:
            logging.error("fail to verify signature:%s", param, exc_info=True)
            return False, None
Exemple #8
0
    def verify_signature(self, pycert, signature, msg):
        # OpenSSL expects the signature to be ASN1-encoded.

        # r and s must be positive ints, so if the high bit is set in 
        # the first byte, prepend 0x00 to indicate an unsigned value.

        r= signature[0:32]
        if r[0] & 0x80:
            r= bytes([0])+r

        s= signature[32:]
        if s[0] & 0x80:
            s= bytes([0])+s

        # ASN1 encode as a sequnce of two integers:
        # 0x30 || len(following) || 0x02 || len(r) || r || 0x02 || len(s) || s

        sig= bytes([0x30,len(r)+len(s)+4,2,len(r)]) + r + bytes([2,len(s)]) + s

        try:
            crypto.verify(pycert, sig, msg, "sha256")
        except crypto.Error as e:
            self.error('Signature verification failed: {:s}'.format(str(e)))
            return False

        return True
Exemple #9
0
    def check_document_signature(self, source, path):
        """ Digital signature validation.

            References:
                SMPTE ST 429-7:2006 6.13
                SMPTE ST 429-8:2007 5.10
                IETF RFC 3275
                IETF RFC 4051
        """
        # Check digest (XML document hash)
        signed_info = source['Signature']['SignedInfo']
        xml_digest = signed_info['Reference']['DigestValue']
        c14n_doc = canonicalize_xml(path,
                                    ns=DCP_SETTINGS['xmlns']['xmldsig'],
                                    strip='{*}Signature')

        c14n_digest = base64.b64encode(self.digest_func(c14n_doc).digest())
        c14n_digest = c14n_digest.decode("utf-8")
        if xml_digest != c14n_digest:
            self.error("XML Digest mismatch, signature can't be checked")

        # Check signature (XML document hash encrypted with certifier
        # private key)
        c14n_sign = canonicalize_xml(path,
                                     root='SignedInfo',
                                     ns=DCP_SETTINGS['xmlns']['xmldsig'])

        xml_sig = ''.join(source['Signature']['SignatureValue'].split('\n'))
        xml_sig = base64.b64decode(xml_sig)

        try:
            crypto.verify(self.cert_list[-1], xml_sig, c14n_sign,
                          self.sig_algorithm_map[self.dcp.schema])
        except crypto.Error as e:
            self.error("Signature validation failed")
Exemple #10
0
 def verify(self, data, signature, digest):
     """Verifies the signature for string containing data."""
     try:
         crypto.verify(self._cert, signature, data, digest)
     except crypto.Error, exc:
         raise SecurityError, SecurityError("Bad signature: %r" %
                                            (exc, )), sys.exc_info()[2]
Exemple #11
0
    def validate_cert(self, cacert_pem):
        #print cacert_pem
        # Create an X509 object for cacert_pem (CA Certificate).
        cacert = X509.load_certificate_from_PEM(
            cacert_pem).get_certificate()[0]
        # Get the X509 object of this certifcate.
        cert = self.get_certificate()[0]
        sig_algo = cert.get_signature_algorithm()

        # Let's start with the ASN1 format of this certificate
        ASN1_cert = crypto.dump_certificate(crypto.FILETYPE_ASN1, cert)
        # We need everything in DER format
        der_seq = asn1.DerSequence()
        der_seq.decode(ASN1_cert)
        der_cert = der_seq[0]
        der_algo = der_seq[1]
        der_sig = asn1.DerObject()
        der_sig.decode(der_seq[2])
        cert_sig_payload = der_sig.payload
        if cert_sig_payload[0] != '\x00':
            raise Exception('Unused bits found!')
        cert_sig = cert_sig_payload[1:]
        # Verify this cert with cacert
        try:
            crypto.verify(cacert, cert_sig, der_cert, sig_algo)
            #print "Certifcate Valid!"
            return True
        except crypto.Error as e:
            #print "Certrifcate Invalid: \n"+str(e)
            return False
Exemple #12
0
def process_invoicerequest(message, id):

    resolver = PluginManager.get_plugin('RESOLVER', config.resolver_type)

    if isinstance(message, ProtocolMessage):

        invoice_request = InvoiceRequest()
        invoice_request.ParseFromString(message.serialized_message)

        # Validate Public Key
        vk = from_sec(request.headers.get('x-identity').decode('hex')) or VerifyingKey.from_der(request.headers.get('x-identity').decode('hex'))
        allowed_keys = [vk.to_der(), to_sec(vk, False), to_sec(vk, True)]

        if invoice_request.sender_public_key not in allowed_keys:
            log.warn("InvoiceRequest Public Key Does Not Match X-Identity Public Key")
            return create_json_response(False, 'InvoiceRequest Public Key Does Not Match X-Identity Public Key', 400)

        if invoice_request.pki_type == 'x509+sha256':
            log.debug("InvoiceRequest Contains X509 Certificate, Validating")

            if invoice_request.pki_data and not invoice_request.signature:
                log.warn('Submitted InvoiceRequest Missing Signature')
                return create_json_response(False, 'Requests including x509 cert must include signature', 400)

            # Verify signature if cert and signature are present
            if invoice_request.pki_data and invoice_request.signature:

                try:
                    x509_certs = X509Certificates()
                    x509_certs.ParseFromString(invoice_request.pki_data)

                    cert_data = ssl.DER_cert_to_PEM_cert(x509_certs.certificate[0])
                    cert = crypto.load_certificate(crypto.FILETYPE_PEM, cert_data)
                except Exception as e:
                    log.warn('Unable to load given x509 certificate [ID: %s]: %s' % (id, str(e)))
                    return create_json_response(False, 'Invalid x509 Certificate', 400)

                try:
                    sig_validate_ir = InvoiceRequest()
                    sig_validate_ir.ParseFromString(message.serialized_message)
                    sig_validate_ir.signature = ""
                    crypto.verify(cert, invoice_request.signature, sig_validate_ir.SerializeToString(), 'sha256')
                    log.info("InvoiceRequest Signature is Valid")
                except Exception as e:
                    log.info('Bad Signature Encountered During Signature Validation [ID: %s]: %s' % (id, str(e)))
                    return create_json_response(False, 'InvoiceRequest Signature Verification Error', 401)

    try:
        log.info('Adding InvoiceRequest %s' % id)
        ret_tx_id = resolver.add_paymentprotocol_message(message, id=id)
        if not ret_tx_id:
            log.error("Unexpected Add InvoiceRequest Failure [ID: %s]" % (id))
            return create_json_response(False, 'Unknown System Error, Please Try Again Later', 503)

        pp_tx_url = '%s/paymentprotocol/%s' % (request.host_url.rstrip('/'), ret_tx_id)
        log.debug('Accepted InvoiceRequest [ID: %s]' % id)
        return create_json_response(status=202, headers={'Access-Control-Expose-Headers': 'Location', 'Location':pp_tx_url})
    except Exception as e:
        log.error("Unexpected exception adding InvoiceRequest [ID: %s]: %s" % (id, str(e)))
        return create_json_response(False, 'Unknown System Error, Please Try Again Later', 503)
def confirmSignature(cert, signature):
    try:
        certificate = crypto.load_certificate(crypto.FILETYPE_ASN1,
                                              bytes(cert))
    except crypto.Error:
        print("Invalid certificate")
        return False

    if not verifyCert(certificate):
        print("Certificate is not valid.")
        return False

    try:
        signature = bytes(ckbytelist(bytes(json.loads(signature))))
    except PyKCS11Error:
        print("Signature is not valid.")
        return False

    BI = [
        x[1] for x in certificate.get_subject().get_components()
        if "serialNumber" in str(x[0])
    ][0]
    try:
        crypto.verify(certificate, signature, BI, 'RSA-SHA1')
    except crypto.Error:
        print("Signature is not valid")
        return False

    return True
Exemple #14
0
    def verify(self, params):
        # params - json
        # raise exception if signature is invalid
        message = params['message']
        signature = decode_hex(params['signature'])[0]

        crypto.verify(self.cert, signature, message, 'sha256')
Exemple #15
0
def handle_sign_warrant(act_json):
    answer = {}
    warrant = pep3_pb2.DepseudonymizationRequest.Warrant()
    pb.json_format.ParseDict(act_json, warrant.act)

    actor = warrant.act.actor.decode('ascii')
    assert (actor.startswith("PEP3 "))
    type_name = actor[len("PEP3 "):]

    ctx = pep3.PepContext(config,
                          secrets,
                          my_type_name=type_name,
                          my_instance_name=None)
    ctx.encrypt([warrant.act.name])

    try:
        warrant.signature = crypto.sign(
            crypto.load_privatekey(crypto.FILETYPE_PEM,
                                   secrets.root_certificate_keys.warrants),
            warrant.act.SerializeToString(), 'sha256')
        crypto.verify(
            crypto.load_certificate(
                crypto.FILETYPE_PEM,
                ctx.global_config.root_certificates.warrants),
            warrant.signature, warrant.act.SerializeToString(), 'sha256')
        answer['warrant'] = pb.json_format.MessageToDict(warrant)
        answer['actor'] = type_name
        answer['serialized_act'] = str(warrant.act.SerializeToString())
    except Exception:
        answer['error'] = traceback.format_exc()
    return answer
Exemple #16
0
def verify_notification(payload):
    """
    Verify notification came from a trusted source
    Returns True if verified, False if not
    """
    pemfile = get_pemfile(payload['SigningCertURL'])
    cert = crypto.load_certificate(crypto.FILETYPE_PEM, pemfile)
    signature = b64decode(payload['Signature'].encode('utf-8'))

    if payload['Type'] == "Notification":
        if payload.get('Subject'):
            hash_format = NOTIFICATION_HASH_FORMAT
        else:
            hash_format = NOTIFICATION_HASH_FORMAT_NO_SUBJECT
    else:
        hash_format = SUBSCRIPTION_HASH_FORMAT

    try:
        crypto.verify(
            cert, signature, hash_format.format(**payload).encode('utf-8'), 'sha1')
    except crypto.Error as e:
        logger.error('Verification of signature raised an Error: %s', e)
        return False

    return True
Exemple #17
0
async def notifications(request):
    """Handle the Travis notifications."""
    signature = request.headers.get('Signature', '')
    signature = base64.b64decode(signature)

    ok = False
    try:
        body = await request.post()
        payload = body['payload']
        certificate = request.app['config']['certificate']
        if not certificate:
            certificate = await travis_certificate()
            request.app['config']['certificate'] = certificate

        crypto.verify(certificate, signature, payload.encode('utf-8'), 'sha1')
        data = json.loads(payload)
        # enqueue the payload
        await request.app['config']['put'](data)
        ok = True
    except crypto.Error:
        print("signature failure.")
    except KeyError:
        print("no payload?")
    except json.JSONDecodeError:
        print("no json?")

    return web.json_response({'ok': ok})
def detectForgery(CERT_FILE, signaturePath, received):

    try:
        #open certificate
        f = open(CERT_FILE)
        ss_buf = f.read()
        f.close()
        ss_cert = crypto.load_certificate(crypto.FILETYPE_PEM, ss_buf)

        #open the signed content received
        f = open(signaturePath, 'rb')
        sig = f.read()
        f.close()

        # verify the integrity of received image with the certificate and signature
        crypto.verify(ss_cert, sig, hash_file(received), 'sha256')
        f = open("verificationFolder\\Report.txt", "w")
        f.write("Authenticated")
        f.close()
        print("Authenticated")

    except Exception as e:
        f = open("verificationFolder\\Report.txt", "w")
        f.write("Forgery Detected")
        f.close()
        print("Forgery Detected" + e)
    def test_issue_certificate_without_csr(self):
        """
            Tests issuance of a certificate
        """
        cmd = issueCertificate.issueCertificateCmd()
        cmd.domain = 'apache.org,cloudstack.apache.org'
        cmd.ipaddress = '10.1.1.1,10.2.2.2'
        cmd.provider = 'root'

        response = self.apiclient.issueCertificate(cmd)
        self.assertTrue(len(response.privatekey) > 0)
        self.assertTrue(len(response.cacertificates) > 0)
        self.assertTrue(len(response.certificate) > 0)

        cert =  x509.load_pem_x509_certificate(str(response.certificate), default_backend())

        # Validate basic certificate attributes
        self.assertEqual(cert.signature_hash_algorithm.name, 'sha256')
        self.assertEqual(cert.subject.get_attributes_for_oid(x509.oid.NameOID.COMMON_NAME)[0].value, 'apache.org')

        # Validate alternative names
        altNames = cert.extensions.get_extension_for_oid(x509.oid.ExtensionOID.SUBJECT_ALTERNATIVE_NAME)
        for domain in cmd.domain.split(','):
            self.assertTrue(domain in altNames.value.get_values_for_type(x509.DNSName))
        for address in cmd.ipaddress.split(','):
            self.assertTrue(address in map(lambda x: str(x), altNames.value.get_values_for_type(x509.IPAddress)))

        # Validate certificate against CA public key
        global PUBKEY_VERIFY
        if not PUBKEY_VERIFY:
            return
        caCert =  x509.load_pem_x509_certificate(str(self.getCaCertificate()), default_backend())
        x = X509()
        x.set_pubkey(load_publickey(FILETYPE_PEM, str(caCert.public_key().public_bytes(serialization.Encoding.PEM, serialization.PublicFormat.SubjectPublicKeyInfo))))
        verify(x, cert.signature, cert.tbs_certificate_bytes, cert.signature_hash_algorithm.name)
    def test_issue_certificate_with_csr(self):
        """
            Tests issuance of a certificate
        """
        cmd = issueCertificate.issueCertificateCmd()
        cmd.csr = "-----BEGIN CERTIFICATE REQUEST-----\nMIIBHjCByQIBADBkMQswCQYDVQQGEwJJTjELMAkGA1UECAwCSFIxETAPBgNVBAcM\nCEd1cnVncmFtMQ8wDQYDVQQKDAZBcGFjaGUxEzARBgNVBAsMCkNsb3VkU3RhY2sx\nDzANBgNVBAMMBnYtMS1WTTBcMA0GCSqGSIb3DQEBAQUAA0sAMEgCQQD46KFWKYrJ\nF43Y1oqWUfrl4mj4Qm05Bgsi6nuigZv7ufiAKK0nO4iJKdRa2hFMUvBi2/bU3IyY\nNvg7cdJsn4K9AgMBAAGgADANBgkqhkiG9w0BAQUFAANBAIta9glu/ZSjA/ncyXix\nyDOyAKmXXxsRIsdrEuIzakUuJS7C8IG0FjUbDyIaiwWQa5x+Lt4oMqCmpNqRzaGP\nfOo=\n-----END CERTIFICATE REQUEST-----"
        cmd.provider = 'root'

        response = self.apiclient.issueCertificate(cmd)
        self.assertTrue(response.privatekey is None)
        self.assertTrue(len(response.cacertificates) > 0)
        self.assertTrue(len(response.certificate) > 0)

        cert =  x509.load_pem_x509_certificate(str(response.certificate), default_backend())

        # Validate basic certificate attributes
        self.assertEqual(cert.signature_hash_algorithm.name, 'sha256')
        self.assertEqual(cert.subject.get_attributes_for_oid(x509.oid.NameOID.COMMON_NAME)[0].value, 'v-1-VM')

        # Validate certificate against CA public key
        global PUBKEY_VERIFY
        if not PUBKEY_VERIFY:
            return
        caCert =  x509.load_pem_x509_certificate(str(self.getCaCertificate()), default_backend())
        x = X509()
        x.set_pubkey(load_publickey(FILETYPE_PEM, str(caCert.public_key().public_bytes(serialization.Encoding.PEM, serialization.PublicFormat.SubjectPublicKeyInfo))))
        verify(x, cert.signature, cert.tbs_certificate_bytes, cert.signature_hash_algorithm.name)
Exemple #21
0
def validate_key_cert(key_file, cert_file):
    try:
        error_key_name = "private key"
        error_filename = key_file
        with open(key_file, 'r') as keyfile:
            key_str = keyfile.read()
        key = crypto.load_privatekey(crypto.FILETYPE_PEM, key_str)

        error_key_name = "certificate"
        error_filename = cert_file
        with open(cert_file, 'r') as certfile:
            cert_str = certfile.read()
        cert = crypto.load_certificate(crypto.FILETYPE_PEM, cert_str)
    except IOError as ioe:
        raise RuntimeError(
            _("There is a problem with your %(error_key_name)s "
              "%(error_filename)s.  Please verify it."
              "  Error: %(ioe)s") % {
                  'error_key_name': error_key_name,
                  'error_filename': error_filename,
                  'ioe': ioe
              })
    except crypto.Error as ce:
        raise RuntimeError(
            _("There is a problem with your %(error_key_name)s "
              "%(error_filename)s.  Please verify it. OpenSSL"
              " error: %(ce)s") % {
                  'error_key_name': error_key_name,
                  'error_filename': error_filename,
                  'ce': ce
              })

    try:
        data = str(uuid.uuid4())
        # On Python 3, explicitly encode to UTF-8 to call crypto.sign() which
        # requires bytes. Otherwise, it raises a deprecation warning (and
        # will raise an error later).
        data = encodeutils.to_utf8(data)
        digest = CONF.digest_algorithm
        if digest == 'sha1':
            LOG.warn(
                _LW('The FIPS (FEDERAL INFORMATION PROCESSING STANDARDS)'
                    ' state that the SHA-1 is not suitable for'
                    ' general-purpose digital signature applications (as'
                    ' specified in FIPS 186-3) that require 112 bits of'
                    ' security. The default value is sha1 in Kilo for a'
                    ' smooth upgrade process, and it will be updated'
                    ' with sha256 in next release(L).'))
        out = crypto.sign(key, data, digest)
        crypto.verify(cert, out, data, digest)
    except crypto.Error as ce:
        raise RuntimeError(
            _("There is a problem with your key pair.  "
              "Please verify that cert %(cert_file)s and "
              "key %(key_file)s belong together.  OpenSSL "
              "error %(ce)s") % {
                  'cert_file': cert_file,
                  'key_file': key_file,
                  'ce': ce
              })
Exemple #22
0
def validate_request_certificate(headers, data):
    """Ensure that the certificate and signature specified in the
    request headers are truely from Amazon and correctly verify.

    Returns True if certificate verification succeeds, False otherwise.

    :param headers: Dictionary (or sufficiently dictionary-like) map of request
        headers.
    :param data: Raw POST data attached to this request.
    """

    # Make sure we have the appropriate headers.
    if 'SignatureCertChainUrl' not in headers or \
       'Signature' not in headers:
        log.error('invalid request headers')
        return False

    cert_url = headers['SignatureCertChainUrl']
    sig = base64.b64decode(headers['Signature'])

    cert = _get_certificate(cert_url)

    if not cert:
        return False

    try:
        # ... wtf kind of API decision is this
        crypto.verify(cert, sig, data, 'sha1')
        return True
    except:
        log.error('invalid request signature')
        return False
Exemple #23
0
def verify(cert, signature, data, digest="sha256"):
    try:
        signature = base64.b64decode(signature.encode())
        crypto.verify(cert, signature, data, digest)
        return True
    except:
        return False
Exemple #24
0
def check_registration_data(attestation_cert, app_id, client_data,
                            user_pub_key, key_handle, signature):
    """
    See example in fido spec
    https://fidoalliance.org/specs/fido-u2f-v1.0-nfc-bt-amendment-20150514/fido-u2f-raw-message-formats.html#registration-example

    In case of signature error an exception is raised

    :param attestation_cert: The Attestation cert of the FIDO device
    :type attestation_cert: x509 Object
    :param app_id: The appId
    :type app_id: basestring
    :param client_data: The ClientData
    :type client_data: basestring
    :param user_pub_key: The public key for this AppID
    :type user_pub_key: hex string
    :param key_handle: The keyHandle on the FIDO device
    :type key_handle: hex string
    :param signature: The signature of the registration request
    :type signature: hex string
    :return: Bool
    """
    app_id_hash = sha256(app_id).digest()
    client_data_hash = sha256(client_data).digest()
    try:
        crypto.verify(
            attestation_cert, binascii.unhexlify(signature),
            chr(0x00) + app_id_hash + client_data_hash +
            binascii.unhexlify(key_handle) + binascii.unhexlify(user_pub_key),
            "sha256")
    except Exception as exx:
        raise Exception("Error checking the signature of the registration "
                        "data. %s" % exx)
    return True
 def verify(self, data, signature, digest):
     """Verifies the signature for string containing data."""
     try:
         crypto.verify(self._cert, signature, data, digest)
     except crypto.Error, exc:
         raise SecurityError, SecurityError(
                 "Bad signature: %r" % (exc, )), sys.exc_info()[2]
Exemple #26
0
def validate_request_certificate(headers, data):
    """Ensure that the certificate and signature specified in the
    request headers are truely from Amazon and correctly verify.

    Returns True if certificate verification succeeds, False otherwise.

    :param headers: Dictionary (or sufficiently dictionary-like) map of request
        headers.
    :param data: Raw POST data attached to this request.
    """

    # Make sure we have the appropriate headers.
    if 'SignatureCertChainUrl' not in headers or \
       'Signature' not in headers:
        log.error('invalid request headers')
        return False

    cert_url = headers['SignatureCertChainUrl']
    sig = base64.b64decode(headers['Signature'])

    cert = _get_certificate(cert_url)

    if not cert:
        return False

    try:
        # ... wtf kind of API decision is this
        crypto.verify(cert, sig, data, 'sha1')
        return True
    except:
        log.error('invalid request signature')
        return False
Exemple #27
0
    def post(self):
        payload = tornado.escape.json_decode(self.request.body)
        signature = base64.b64decode(self.request.headers.get('Signature'))

        status = requests.get('https://api.travis-ci.org/config').json()
        pubkey = status['config']['notifications']['webhook']['public_key']

        public_key = crypto.load_publickey(crypto.FILETYPE_PEM, pubkey)
        certificate = crypto.X509()
        certificate.set_pubkey(public_key)

        try:
            crypto.verify(certificate, signature, payload, 'sha1')
        except crypto.Error:
            return self.write({'status': 'error',
                               'message': 'Invalid signature for Travis ' \
                                          'payload'})

        status = ("error" if (payload["status"] == "1") else "success")
        commit = payload["commit"]
        repo = payload["repository"]["owner_name"] + "/" + \
               payload["repository"]["name"]

        gh = github.Github(config["github"]["personal_access_token"])
        repo = gh.get_repo(repo)
        commit = repo.get_commit(commit)
        commit.create_status(
            status,
            target_url=payload["build_url"],
            description='Dependent build completed',
            context='continuous-integration/dependent-build-server')
Exemple #28
0
    def validate(self, data):
        '''
        @data: a dict ready for validate, must contain "signature" key name
        '''
        signature_orignal = data.pop('signature')
        signature_string = signature_orignal.replace(' ', '+')
        signature_bytes = signature_string.encode('utf-8')
        signature = base64.b64decode(signature_bytes)

        if 'fileContent' in data and data['fileContent']:
            file_content = data['fileContent'].replace(' ', '+')
            data.update(fileContent=file_content)
        stringData = self.simple_urlencode(data)
        digest = sha1(stringData).hexdigest()

        #print('---------------------')
        #print('verify signature')
        #print(signature)
        #print(data)
        #print(stringData)
        #print(digest)
        #print('---------------------')

        # calc signature
        crypto.verify(self.X509, signature, digest, self.digest_method)
Exemple #29
0
def validate_key_cert(key_file, cert_file):
    try:
        error_key_name = "private key"
        error_filename = key_file
        key_str = open(key_file, "r").read()
        key = crypto.load_privatekey(crypto.FILETYPE_PEM, key_str)

        error_key_name = "certficate"
        error_filename = cert_file
        cert_str = open(cert_file, "r").read()
        cert = crypto.load_certificate(crypto.FILETYPE_PEM, cert_str)
    except IOError as ioe:
        raise RuntimeError(_("There is a problem with your %s "
                             "%s.  Please verify it.  Error: %s")
                           % (error_key_name, error_filename, ioe))
    except crypto.Error as ce:
        raise RuntimeError(_("There is a problem with your %s "
                             "%s.  Please verify it. OpenSSL error: %s")
                           % (error_key_name, error_filename, ce))

    try:
        data = str(uuid.uuid4())
        digest = "sha1"

        out = crypto.sign(key, data, digest)
        crypto.verify(cert, out, data, digest)
    except crypto.Error as ce:
        raise RuntimeError(_("There is a problem with your key pair.  "
                             "Please verify that cert %s and key %s "
                             "belong together.  OpenSSL error %s")
                           % (cert_file, key_file, ce))
Exemple #30
0
def verify_signature(signature_input,
                     signature,
                     pubkey_pem,
                     digest_algo='sha256'):
    '''Verify if `signature` over `signature_input` was created using
    `digest_algo` by the private key of the `pubkey_pem`.

    A signature is the private key encrypted hash over the signature input data.

    Args:
        signature_input(bytes): signed data
        signature(bytes):
        pubkey_pem(str): PEM formatted pubkey
        digest_algo(str): name of the used digest hash algorithm
                          (default: 'sha256')

    Return:
        True, if signature could be verified
        False, else
    '''
    cryptography_key = serialization.load_pem_public_key(pubkey_pem, backend)
    pkey = pkey_from_cryptography_key(cryptography_key)

    auxiliary_cert = X509()
    auxiliary_cert.set_pubkey(pkey)

    try:
        verify(cert=auxiliary_cert,
               signature=signature,
               data=signature_input,
               digest=digest_algo)
    except OpenSSL_crypto_Error:
        return False

    return True
Exemple #31
0
def cmd_verify( filename ):
    """usage: %prog [<opts>] verify <filename>"""

    # load public certificates:
    certs = load_certificates()
    if len(certs) <= 0:
        print >>sys.stderr, "error: no certificates found"
        sys.exit(1)

    # load pythoncode data for matching:
    with open( filename ) as fp:
        source = fp.read()
    source, signatures = strip_signature( source )
    if len(signatures) <= 0:
        print "no signature found"
        return

    # loop all lines and verify a found signature:
    valid = False
    for signature in signatures:
        for cert in certs:
            try:
                crypto.verify( cert, signature, source, "sha256" )
                valid = True
                break
            except crypto.Error:
                pass

        if not valid:
            continue

        print "signature ok"
        return

    print "invalid signature"
Exemple #32
0
    def validate_cert(self, cacert_pem): 
        #print cacert_pem
        # Create an X509 object for cacert_pem (CA Certificate).
        cacert = X509.load_certificate_from_PEM(cacert_pem).get_certificate()[0]
        # Get the X509 object of this certifcate.
        cert = self.get_certificate()[0]
        sig_algo = cert.get_signature_algorithm()

        # Let's start with the ASN1 format of this certificate
        ASN1_cert = crypto.dump_certificate(crypto.FILETYPE_ASN1, cert)
        # We need everything in DER format
        der_seq=asn1.DerSequence()
        der_seq.decode(ASN1_cert)
        der_cert = der_seq[0]
        der_algo = der_seq[1]
        der_sig = asn1.DerObject()
        der_sig.decode(der_seq[2])
        cert_sig_payload = der_sig.payload
        if cert_sig_payload[0]!='\x00':
            raise Exception('Unused bits found!')
        cert_sig = cert_sig_payload[1:]
        # Verify this cert with cacert
        try:
            crypto.verify(cacert, cert_sig, der_cert,sig_algo)
            #print "Certifcate Valid!"
            return True
        except crypto.Error as e:
            #print "Certrifcate Invalid: \n"+str(e)
            return False
Exemple #33
0
    def verify(self, signing_cert_str, cert_str):
        """
        Verifies if a certificate is valid and signed by a given certificate.

        :param signing_cert_str: This certificate will be used to verify the
                                  signature. Must be a string representation
                                 of the certificate. If you only have a file
                                 use the method read_str_from_file to
                                 get a string representation.
        :param cert_str:         This certificate will be verified if it is
                                  correct. Must be a string representation
                                 of the certificate. If you only have a file
                                 use the method read_str_from_file to
                                 get a string representation.
        :return:                 Valid, Message
                                 Valid = True if the certificate is valid,
                                 otherwise false.
                                 Message = Why the validation failed.
        """
        try:
            ca_cert = crypto.load_certificate(crypto.FILETYPE_PEM,
                                              signing_cert_str)
            cert = crypto.load_certificate(crypto.FILETYPE_PEM, cert_str)

            if self.certificate_not_valid_yet(ca_cert):
                return False, "CA certificate is not valid yet."

            if ca_cert.has_expired() == 1:
                return False, "CA certificate is expired."

            if cert.has_expired() == 1:
                return False, "The signed certificate is expired."

            if self.certificate_not_valid_yet(cert):
                return False, "The signed certificate is not valid yet."

            if ca_cert.get_subject().CN == cert.get_subject().CN:
                return False, (
                    "CN may not be equal for CA certificate and the "
                    "signed certificate.")

            cert_algorithm = cert.get_signature_algorithm()
            if six.PY3:
                cert_algorithm = cert_algorithm.decode('ascii')
                cert_str = cert_str.encode('ascii')

            cert_crypto = saml2_tophat.cryptography.pki.load_pem_x509_certificate(
                cert_str)

            try:
                crypto.verify(ca_cert, cert_crypto.signature,
                              cert_crypto.tbs_certificate_bytes,
                              cert_algorithm)
                return True, "Signed certificate is valid and correctly signed by CA certificate."
            except crypto.Error as e:
                return False, "Certificate is incorrectly signed."
        except Exception as e:
            return False, "Certificate is not valid for an unknown reason. %s" % str(
                e)
Exemple #34
0
def verify_sns_notification(message: Dict) -> bool:
    """Takes a notification request from Amazon push service SNS and verifies the origin of the notification.
    This implementation uses OpenSSL Crypto, inspired by the implementation of
    Artur Rodrigues with M2Crypto: http://goo.gl/KAgPPc
    Args:
        message (dictionary):
            The parsed message content
    Returns (bool):
        True if he message passes the verification, False otherwise
    """

    canonical_sub_unsub_format = [
        "Message",
        "MessageId",
        "SubscribeURL",
        "Timestamp",
        "Token",
        "TopicArn",
        "Type",
    ]
    canonical_notification_format = [
        "Message",
        "MessageId",
        "Subject",
        "Timestamp",
        "TopicArn",
        "Type",
    ]

    content = message
    decoded_signature = b64decode(content["Signature"])

    # Depending on the message type, canonical message format varies: http://goo.gl/oSrJl8
    if (message["Type"] == SNS_MESSAGE_TYPE_SUB_NOTIFICATION
            or message["Type"] == SNS_MESSAGE_TYPE_UNSUB_NOTIFICATION):

        canonical_message = canonical_message_builder(
            content, canonical_sub_unsub_format)

    elif message["Type"] == SNS_MESSAGE_TYPE_NOTIFICATION:

        canonical_message = canonical_message_builder(
            content, canonical_notification_format)

    else:
        raise ValueError("Message Type (%s) is not recognized" %
                         message["Type"])

    # Load the certificate and extract the public key
    cert = load_certificate(
        FILETYPE_PEM,
        urlopen(content["SigningCertURL"]).read().decode("utf-8"))

    try:
        verify(cert, decoded_signature, str.encode(canonical_message), "sha1")
    except OpenSSL.crypto.Error:
        return False

    return True
Exemple #35
0
    def __verify_codefile_signature(self, is_mfr, codefile):
        """Verify the signature in codefile.

        :is_mfr:
        :return: SUCCESS or ERROR list

        """
        digest_verified_failed = False
        if is_mfr == True:
            signerInfo = self.mfr_signerInfo
            cert = self.mfr_cvc
            attrs = self.mfr_signer_attrs
            message_digest = self.mfr_message_digest
        else:
            signerInfo = self.mso_signerInfo
            cert = self.mso_cvc
            attrs = self.mso_signer_attrs
            message_digest = self.mso_message_digest

        if signerInfo == None or attrs == None:
            self.logger.error("No signer info or attributes in codefile when try to verify signature!")
            return False, digest_verified_failed

        try:
            # Get the encrypted digest
            encryptedDigest = str(signerInfo['encryptedDigest'])

            # Get the digest type, sha1, sha256...
            hash_algo = str(signerInfo['digestAlgorithm']['algorithm'])
            if hash_algo != self.SHA256_OID:
                # Only sha256 is used in CM/RPD certificate/signature
                self.logger.error("The hash algorithm in CVC is not sha256!")
                return False, digest_verified_failed

            # With the attributes in PKCS7, the encryptedDigest is for attributes (no -noattr in openssl)
            # So, here signedContent should not be used
            try:
                c.verify(cert, encryptedDigest, str(attrs), "sha256")
            except Exception as e:
                self.logger.error("Failed to verify encrypted digest, reason: " + str(e))
                return False, digest_verified_failed

            # Continue to verify the message digest, sha256(signedContent) == messagedigest
            hash_sha = hashlib.sha256()
            with open(codefile, 'r') as f:
                f.seek(self.signedContentOffset, 0)
                buf = f.read(self.limit_block)
                while buf:
                    hash_sha.update(buf)
                    buf = f.read(self.limit_block)
            digest = hash_sha.hexdigest()
            if digest != message_digest.prettyPrint()[2:]:  # remove the "0x"
                self.logger.error("Failed to verify the message digest!")
                digest_verified_failed = True
                return False, digest_verified_failed

        except Exception, e:
            self.logger.error("Failed to verify signature, reason: " + str(e))
            return False, digest_verified_failed
Exemple #36
0
 def verify_sig(self, encoded_cert):
     der = asn1.DerSequence()
     der.decode(encoded_cert)
     der_sig = asn1.DerObject()
     der_sig.decode(der[2])
     sig = der_sig.payload
     self.assertIs('\x00', sig[0])
     crypto.verify(self.ca.cert, sig[1:], der[0], 'sha256')
    def verify_sig(self, encoded_cert):
        cert = x509.load_der_x509_certificate(encoded_cert, default_backend())

        crypto.verify(
            self.ca.cert,
            cert.signature,
            cert.tbs_certificate_bytes,
            'sha256')
 def verify_sig(self, encoded_cert):
     der = asn1.DerSequence()
     der.decode(encoded_cert)
     der_sig = asn1.DerObject()
     der_sig.decode(der[2])
     sig = der_sig.payload
     self.assertEqual(b'\x00', sig[:1])
     crypto.verify(self.ca.cert, sig[1:], der[0], 'sha256')
Exemple #39
0
    def verify(self, signing_cert_str, cert_str):
        """
        Verifies if a certificate is valid and signed by a given certificate.

        :param signing_cert_str: This certificate will be used to verify the
                                  signature. Must be a string representation
                                 of the certificate. If you only have a file
                                 use the method read_str_from_file to
                                 get a string representation.
        :param cert_str:         This certificate will be verified if it is
                                  correct. Must be a string representation
                                 of the certificate. If you only have a file
                                 use the method read_str_from_file to
                                 get a string representation.
        :return:                 Valid, Message
                                 Valid = True if the certificate is valid,
                                 otherwise false.
                                 Message = Why the validation failed.
        """
        try:
            ca_cert = crypto.load_certificate(crypto.FILETYPE_PEM,
                                              signing_cert_str)
            cert = crypto.load_certificate(crypto.FILETYPE_PEM, cert_str)

            if self.certificate_not_valid_yet(ca_cert):
                return False, "CA certificate is not valid yet."

            if ca_cert.has_expired() == 1:
                return False, "CA certificate is expired."

            if cert.has_expired() == 1:
                return False, "The signed certificate is expired."

            if self.certificate_not_valid_yet(cert):
                return False, "The signed certificate is not valid yet."

            if ca_cert.get_subject().CN == cert.get_subject().CN:
                return False, ("CN may not be equal for CA certificate and the "
                               "signed certificate.")

            cert_algorithm = cert.get_signature_algorithm()
            if six.PY3:
                cert_algorithm = cert_algorithm.decode('ascii')
                cert_str = cert_str.encode('ascii')

            cert_crypto = saml2.cryptography.pki.load_pem_x509_certificate(
                    cert_str)

            try:
                crypto.verify(ca_cert, cert_crypto.signature,
                              cert_crypto.tbs_certificate_bytes,
                              cert_algorithm)
                return True, "Signed certificate is valid and correctly signed by CA certificate."
            except crypto.Error as e:
                return False, "Certificate is incorrectly signed."
        except Exception as e:
            return False, "Certificate is not valid for an unknown reason. %s" % str(e)
Exemple #40
0
def validate_key_cert(key_file, cert_file):
    try:
        error_key_name = "private key"
        error_filename = key_file
        with open(key_file, "r") as keyfile:
            key_str = keyfile.read()
        key = crypto.load_privatekey(crypto.FILETYPE_PEM, key_str)

        error_key_name = "certificate"
        error_filename = cert_file
        with open(cert_file, "r") as certfile:
            cert_str = certfile.read()
        cert = crypto.load_certificate(crypto.FILETYPE_PEM, cert_str)
    except IOError as ioe:
        raise RuntimeError(
            _(
                "There is a problem with your %(error_key_name)s "
                "%(error_filename)s.  Please verify it."
                "  Error: %(ioe)s"
            )
            % {"error_key_name": error_key_name, "error_filename": error_filename, "ioe": ioe}
        )
    except crypto.Error as ce:
        raise RuntimeError(
            _(
                "There is a problem with your %(error_key_name)s "
                "%(error_filename)s.  Please verify it. OpenSSL"
                " error: %(ce)s"
            )
            % {"error_key_name": error_key_name, "error_filename": error_filename, "ce": ce}
        )

    try:
        data = str(uuid.uuid4())
        digest = CONF.digest_algorithm
        if digest == "sha1":
            LOG.warn(
                "The FIPS (FEDERAL INFORMATION PROCESSING STANDARDS)"
                " state that the SHA-1 is not suitable for"
                " general-purpose digital signature applications (as"
                " specified in FIPS 186-3) that require 112 bits of"
                " security. The default value is sha1 in Kilo for a"
                " smooth upgrade process, and it will be updated"
                " with sha256 in next release(L)."
            )
        out = crypto.sign(key, data, digest)
        crypto.verify(cert, out, data, digest)
    except crypto.Error as ce:
        raise RuntimeError(
            _(
                "There is a problem with your key pair.  "
                "Please verify that cert %(cert_file)s and "
                "key %(key_file)s belong together.  OpenSSL "
                "error %(ce)s"
            )
            % {"cert_file": cert_file, "key_file": key_file, "ce": ce}
        )
Exemple #41
0
 def read_integrity(self, path, signature):
     md = hashlib.sha256()
     with open(path, 'rb') as fsrc:
         buf = fsrc.read(self.BLOCKSIZE)
         while len(buf) > 0:
             md.update(buf)
             buf = fsrc.read(self.BLOCKSIZE)
     # will throw exception if the verification fails
     co.verify(self.server_crt, signature, md.hexdigest(), 'sha256')
     return open(path, 'rb').read()
    def _is_valid_signature(self):
        if self._testing_mode:  # skip validation on testing mode
            return True
        elif not os.getenv('TBK_PUBLIC_CRT'):  # tbk certificate undefined
            return True

        try:  # OpenSSL return: None if the signature is correct, raise exception otherwise
            crypto.verify(self.tbk_key, self._signature_value, self._signed_info, 'sha1')
            return True
        except:
            return False
Exemple #43
0
def validate_key_cert(key_file, cert_file):
    try:
        error_key_name = "private key"
        error_filename = key_file
        with open(key_file, 'r') as keyfile:
            key_str = keyfile.read()
        key = crypto.load_privatekey(crypto.FILETYPE_PEM, key_str)

        error_key_name = "certificate"
        error_filename = cert_file
        with open(cert_file, 'r') as certfile:
            cert_str = certfile.read()
        cert = crypto.load_certificate(crypto.FILETYPE_PEM, cert_str)
    except IOError as ioe:
        raise RuntimeError(_("There is a problem with your %(error_key_name)s "
                             "%(error_filename)s.  Please verify it."
                             "  Error: %(ioe)s") %
                           {'error_key_name': error_key_name,
                            'error_filename': error_filename,
                            'ioe': ioe})
    except crypto.Error as ce:
        raise RuntimeError(_("There is a problem with your %(error_key_name)s "
                             "%(error_filename)s.  Please verify it. OpenSSL"
                             " error: %(ce)s") %
                           {'error_key_name': error_key_name,
                            'error_filename': error_filename,
                            'ce': ce})

    try:
        data = str(uuid.uuid4())
        # On Python 3, explicitly encode to UTF-8 to call crypto.sign() which
        # requires bytes. Otherwise, it raises a deprecation warning (and
        # will raise an error later).
        data = encodeutils.to_utf8(data)
        digest = CONF.digest_algorithm
        if digest == 'sha1':
            LOG.warn(
                _LW('The FIPS (FEDERAL INFORMATION PROCESSING STANDARDS)'
                    ' state that the SHA-1 is not suitable for'
                    ' general-purpose digital signature applications (as'
                    ' specified in FIPS 186-3) that require 112 bits of'
                    ' security. The default value is sha1 in Kilo for a'
                    ' smooth upgrade process, and it will be updated'
                    ' with sha256 in next release(L).'))
        out = crypto.sign(key, data, digest)
        crypto.verify(cert, out, data, digest)
    except crypto.Error as ce:
        raise RuntimeError(_("There is a problem with your key pair.  "
                             "Please verify that cert %(cert_file)s and "
                             "key %(key_file)s belong together.  OpenSSL "
                             "error %(ce)s") % {'cert_file': cert_file,
                                                'key_file': key_file,
                                                'ce': ce})
Exemple #44
0
  def _Unwrap(self, wrapped):
    self._VerifyChain(wrapped.get('other_certs', []), wrapped['cert'])

    cert = crypto.load_certificate(crypto.FILETYPE_PEM, wrapped['cert'])
    sig = codecs.decode(wrapped['sig'], 'hex')
    crypto.verify(
        cert,
        sig,
        wrapped['inner'].encode('utf8'),
        'sha256')

    return json.loads(wrapped['inner'])
 def verify(cls, transmission_id, timestamp, webhook_id, event_body, cert_url, actual_sig, auth_algo='sha1'):
     """Verify that the webhook payload received is from PayPal,
     unaltered and targeted towards correct recipient
     """
     expected_sig = WebhookEvent._get_expected_sig(transmission_id, timestamp, webhook_id, event_body)
     cert = WebhookEvent._get_cert(cert_url)
     try:
         crypto.verify(cert, b64decode(actual_sig), expected_sig.encode('utf-8'), auth_algo)
         return True
     except Exception as e:
         print(e)
         return False
Exemple #46
0
def verify_license(public_key_string, encoded_signature, product_code, name):
  base32_signature = encoded_signature.replace('8', 'O').replace('9', 'I').replace('-', '')
  base32_signature += '=' * (8 - (len(base32_signature) % 8))
  decoded_signature = base64.b32decode(base32_signature)
  public_key = crypto.load_publickey(crypto.FILETYPE_PEM, public_key_string)
  certificate = crypto.X509()
  certificate.set_pubkey(public_key)
  try:
    crypto.verify(certificate, decoded_signature, make_license_source(product_code, name), 'dss1')
    return True
  except:
    return False
Exemple #47
0
    def verifica_assinatura_texto(self, texto, assinatura):
        #
        # Carrega o arquivo do certificado
        #
        pkcs12 = crypto.load_pkcs12(open(self.arquivo, 'rb').read(), self.senha)

        try:
            crypto.verify(pkcs12.get_certificate(), assinatura, texto, 'sha1')
        except:
            return False

        return True
    def _verify_signature(cls, transmission_id, timestamp, webhook_id, event_body, cert, actual_sig, auth_algo):
        """Verify that the webhook payload received is from PayPal,
        unaltered and targeted towards correct recipient
        """
        from OpenSSL import crypto

        expected_sig = WebhookEvent._get_expected_sig(transmission_id, timestamp, webhook_id, event_body)
        try:
            crypto.verify(cert, b64decode(actual_sig), expected_sig.encode("utf-8"), auth_algo)
            return True
        except Exception as e:
            print(e)
            return False
Exemple #49
0
def verify_license(public_key_string, encoded_signature, product_code, name):
  base32_signature = encoded_signature.replace('8', 'O').replace('9', 'I').replace('-', '')
  base32_signature += '=' * (8 - (len(base32_signature) % 8))
  decoded_signature = base64.b32decode(base32_signature)
  public_key = crypto.load_publickey(crypto.FILETYPE_PEM, public_key_string)
  certificate = crypto.X509()
  certificate.set_pubkey(public_key)
  try:
    crypto.verify(certificate, decoded_signature, make_license_source(product_code, name), 'sha1')
    # Use sha1 instead of dss1 to avoid 'ValueError("No such digest method")'
    return True
  except:
    return False
Exemple #50
0
 def validate(self, data):
     '''
     @data: a dict ready for sign, must contain "signature" key name
     '''
     signature = data.pop('signature')
     signature = signature.replace(' ', '+')
     signature = base64.b64decode(signature)
     if 'fileContent' in data and data['fileContent']:
         file_content = data['fileContent'].replace(' ', '+')
         data.update(fileContent=file_content)
     stringData = self.simple_urlencode(data)
     digest = sha1(stringData).hexdigest()
     crypto.verify(self.X509, signature, digest, self.digest_method)
Exemple #51
0
def validate(token):
    try:
        # This will probably populate ValueError, 
        # if token is not correctly formatted.
        ts, hostname, uid, sig = token.split(':')
        content = '%s:%s:%s' % (ts, hostname, uid)
        sig = base64.b64decode(sig)
        cert = load_certificate(FILETYPE_PEM, open(CERT_FILE).read())

        # Openssl populates Error if verfication fails.
        verify(cert, sig, content, "sha1")
        return (ts, hostname, uid)
    except:
        return None
Exemple #52
0
def verify(cert, cacert):
    print "cacert notBefore", cacert.get_notBefore()
    print "cacert notAfter", cacert.get_notAfter()

    # Get the signing algorithm
    algo = cert.get_signature_algorithm()

    # Get the ASN1 format of the certificate
    cert_asn1 = crypto.dump_certificate(crypto.FILETYPE_ASN1, cert)

    # Decode the certificate
    der = asn1.DerSequence()
    der.decode(cert_asn1)

    # The certificate has three parts:
    # - certificate
    # - signature algorithm
    # - signature
    # http://usefulfor.com/nothing/2009/06/10/x509-certificate-basics/
    der_cert = der[0]
    der_algo = der[1]
    der_sig = der[2]

    # The signature is a BIT STRING (Type 3)
    # Decode that as well
    der_sig_in = asn1.DerObject()
    der_sig_in.decode(der_sig)

    # Get the payload
    sig0 = der_sig_in.payload

    # Do the following to see a validation error for tests
    # der_cert=der_cert[:20]+'1'+der_cert[21:]

    # First byte is the number of unused bits. This should be 0
    # http://msdn.microsoft.com/en-us/library/windows/desktop/bb540792(v=vs.85).aspx
    if sig0[0] != "\x00":
        raise Exception("Number of unused bits is strange")

    # Now get the signature itself
    sig = sig0[1:]

    # And verify the certificate
    print algo
    try:
        crypto.verify(cacert, sig, der_cert, algo)
        print "Certificate looks good"
    except crypto.Error as e:
        print "Sorry. Nope."
Exemple #53
0
    def verify(self, message, signature):
      """Verifies a message against a signature.

      Args:
        message: string, The message to verify.
        signature: string, The signature on the message.

      Returns:
        True if message was signed by the private key associated with the public
        key that this object was constructed with.
      """
      try:
        crypto.verify(self._pubkey, signature, message, 'sha256')
        return True
      except:
        return False
Exemple #54
0
 def _verify_signature(self, req, *args, **kwargs):
     """ Throws exception if verification fails """
     cookies = kwargs.get('cookies', {})
     if 'APIC-Request-Signature' not in cookies:
         return
     url = args[0]
     payload = req + url[url.find('/api'):] + kwargs.get('data', '')
     cert_dn = ('uni/userext/user-%s/usercert-%s' %
         (APIC_USR, APIC_USR_CERT_NAME))
     if cookies.get('APIC-Certificate-DN') != cert_dn:
         raise Exception("Certificate DN mismatch")
     if (cookies.get('APIC-Certificate-Algorithm') != 'v1.0' or
         cookies.get('APIC-Certificate-Fingerprint') != 'fingerprint'):
         raise Exception("Signature verification algorithm mismatch")
     crypto.verify(self.certificate,
                   base64.b64decode(cookies.get('APIC-Request-Signature')),
                   payload, 'sha256')
Exemple #55
0
    def basic_assertions(self, cdir, cert, key, cacert=None):
        '''
        test basic certificate assumptions

        Args:
            cdir (s_certdir.CertDir): certdir object
            cert (crypto.X509): Cert to test
            key (crypto.PKey): Key for the certification
            cacert (crypto.X509): Corresponding CA cert (optional)
        '''
        self.nn(cert)
        self.nn(key)

        # Make sure the certs were generated with the expected number of bits
        self.eq(cert.get_pubkey().bits(), cdir.crypto_numbits)
        self.eq(key.bits(), cdir.crypto_numbits)

        # Make sure the certs were generated with the correct version number
        self.eq(cert.get_version(), 2)

        # ensure we can sign / verify data with our keypair
        buf = b'The quick brown fox jumps over the lazy dog.'
        sig = crypto.sign(key, buf, 'sha256')
        sig2 = crypto.sign(key, buf + b'wut', 'sha256')
        self.none(crypto.verify(cert, sig, buf, 'sha256'))
        self.raises(crypto.Error, crypto.verify, cert, sig2, buf, 'sha256')

        # ensure that a ssl context using both cert/key match
        sslcontext = SSL.Context(SSL.TLSv1_2_METHOD)
        sslcontext.use_certificate(cert)
        sslcontext.use_privatekey(key)
        self.none(sslcontext.check_privatekey())

        if cacert:

            # Make sure the cert was signed by the CA
            self.eq(cert.get_issuer().der(), cacert.get_subject().der())

            store = crypto.X509Store()
            ctx = crypto.X509StoreContext(store, cert)

            # OpenSSL should NOT be able to verify the certificate if its CA is not loaded
            store.add_cert(cert)
            self.raises(crypto.X509StoreContextError, ctx.verify_certificate)  # unable to get local issuer certificate

            # Generate a separate CA that did not sign the certificate
            try:
                cdir.genCaCert('otherca')
            except s_exc.DupFileName:
                pass

            # OpenSSL should NOT be able to verify the certificate if its CA is not loaded
            store.add_cert(cdir.getCaCert('otherca'))
            self.raises(crypto.X509StoreContextError, ctx.verify_certificate)  # unable to get local issuer certificate

            # OpenSSL should be able to verify the certificate, once its CA is loaded
            store.add_cert(cacert)
            self.none(ctx.verify_certificate())  # valid
Exemple #56
0
def signature_valid(signature, cert_text, data):
    """Verify signature against certificate text and signed data."""
    certificate = crypto.load_certificate(crypto.FILETYPE_PEM, cert_text)
    decoded_signature = b64decode(signature)
    try:
        result = crypto.verify(certificate, decoded_signature, data, 'sha1')
    except crypto.Error:
        return False
    return result is None
def validate_signature(app_root, cert):
    app_metadata_folder = os.path.join(app_root, META_DATA_FOLDER)
    app_manifest_file = os.path.join(app_metadata_folder, MANIFEST_FILE)
    signature_file = os.path.join(app_metadata_folder, SIGNATURE_FILE)

    with open(signature_file, 'rb') as sf:
        signature = sf.read()
        checksum = file_checksum(hashlib.sha256,
                                 file=app_manifest_file).encode('utf-8')

        if cert:
            try:
                crypto.verify(cert, signature, checksum, 'sha256')
            except Exception as e:
                raise InvalidSignature('Invalid Signature: ' + e)
        else:
            if checksum != signature:
                raise InvalidSignature('Invalid Signature')
Exemple #58
0
    def verify_signature(self, signature, digest):
        signature = str(signature)
        pk_string = open(self.transaction.channel.cert_file.path, 'rb').read()
        cert = load_certificate(FILETYPE_PEM, pk_string)

        if crypto.verify(cert, b64decode(signature), digest, 'sha1') is None:
            return True
        else:
            return False
Exemple #59
0
def verify_signature(amazon_cert: crypto.X509, signature: str, request_body: bytes) -> bool:
    """Verifies Alexa request signature.

    Args:
        amazon_cert: Pycrypto X509 Amazon certificate.
        signature: Base64 decoded Alexa request signature from Signature HTTP header.
        request_body: full HTTPS request body
    Returns:
        result: True if verification was successful, False if not.
    """
    signature = base64.b64decode(signature)

    try:
        crypto.verify(amazon_cert, signature, request_body, 'sha1')
        result = True
    except crypto.Error:
        result = False

    return result