Beispiel #1
0
def smime_verify(ca_path, message):
    """Verify S/MIME pkcs7 signed message.

    You may debug certificate errors with command::

        openssl smime -verify -in
            .tmp/test_verify_signature_file0/signed/signature.sig -CApath
            .tmp/test_verify_signature_file0/certs

    :param str ca_path: Path to CA certificate store
    :param bytes message: Message to verify

    :returns: Message data on succesful verification
    :rtype: bytes
    """

    # SSLContext expects a byte string on Python 2 and Unicode on Python 3
    ca_path = _to_str_path(ca_path)

    buf = BIO.MemoryBuffer(message)
    pkcs7, data = SMIME.smime_load_pkcs7_bio(buf)

    certificate_x509 = pkcs7.get0_signers(X509.X509_Stack())

    context = SSL.Context()
    context.load_verify_locations(capath=ca_path)
    ca_store = context.get_cert_store()

    smime = SMIME.SMIME()

    smime.set_x509_store(ca_store)
    smime.set_x509_stack(certificate_x509)

    return smime.verify(pkcs7, data)
Beispiel #2
0
    def scan(self, data, file, options, expire_at):
        tmp_directory = options.get('tmp_directory', '/tmp/')

        self.event['total'] = {'certificates': 0, 'extracted': 0}

        with tempfile.NamedTemporaryFile(dir=tmp_directory) as tmp_data:
            tmp_data.write(data)
            tmp_data.flush()

            if data[:1] == b'0':
                pkcs7 = SMIME.load_pkcs7_der(tmp_data.name)
            else:
                pkcs7 = SMIME.load_pkcs7(tmp_data.name)

            certs = pkcs7.get0_signers(X509.X509_Stack())
            if certs:
                self.event['total']['certificates'] = len(certs)
                for cert in certs:
                    extract_file = strelka.File(
                        name=f'sn_{cert.get_serial_number()}',
                        source=self.name,
                    )

                    for c in strelka.chunk_string(cert.as_der()):
                        self.upload_to_coordinator(
                            extract_file.pointer,
                            c,
                            expire_at,
                        )

                    self.files.append(extract_file)
                    self.event['total']['extracted'] += 1
Beispiel #3
0
def verify_signature_block(certificate_file, content, signature):
    """
    Verifies the 'signature' over the 'content', trusting the
    'certificate'.

    :param certificate_file: the trusted certificate (PEM format)
    :type certificate_file: str
    :param content: The signature should match this content
    :type content: str
    :param signature: data (DER format) subject to check
    :type signature: str
    :return None if the signature validates.
    :exception SignatureBlockVerificationError
    """

    sig_bio = BIO.MemoryBuffer(signature)
    pkcs7 = SMIME.PKCS7(m2.pkcs7_read_bio_der(sig_bio._ptr()), 1)
    signers_cert_stack = pkcs7.get0_signers(X509.X509_Stack())
    trusted_cert_store = X509.X509_Store()
    trusted_cert_store.set_verify_cb(ignore_missing_email_protection_eku_cb)
    trusted_cert_store.load_info(certificate_file)
    smime = SMIME.SMIME()
    smime.set_x509_stack(signers_cert_stack)
    smime.set_x509_store(trusted_cert_store)
    data_bio = BIO.MemoryBuffer(content)

    try:
        smime.verify(pkcs7, data_bio)
    except SMIME.PKCS7_Error as message:
        raise SignatureBlockVerificationError(message)
    else:
        return None
Beispiel #4
0
def decrypt_verify(p7file, recip_key, signer_cert, ca_cert):
    s = SMIME.SMIME()

    # Load decryption private key.
    s.load_key(recip_key)

    # Extract PKCS#7 blob from input.
    p7, bio = SMIME.smime_load_pkcs7_bio(p7file)

    # Decrypt.
    data = s.decrypt(p7)

    # Because we passed in a SignAndEnveloped blob, the output
    # of our decryption is a Signed blob. We now verify it.

    # Load the signer's cert.
    sk = X509.X509_Stack()
    s.set_x509_stack(sk)

    # Load the CA cert.
    st = X509.X509_Store()
    st.load_info(ca_cert)
    s.set_x509_store(st)

    # Verify.
    p7, bio = SMIME.smime_load_pkcs7_bio(BIO.MemoryBuffer(data))
    if bio is not None:
        # Netscape Messenger clear-signs, when also encrypting.
        data = s.verify(p7, bio)
    else:
        # M2Crypto's sendsmime.py opaque-signs, when also encrypting.
        data = s.verify(p7)

    print data
Beispiel #5
0
def ed():
    print 'test encrypt/decrypt...',
    buf = makebuf()
    s = SMIME.SMIME()

    # Load target cert to encrypt to.
    x509 = X509.load_cert('client.pem')
    sk = X509.X509_Stack()
    sk.push(x509)
    s.set_x509_stack(sk)

    # Add a cipher.
    s.set_cipher(SMIME.Cipher('bf_cbc'))

    # Encrypt.
    p7 = s.encrypt(buf)

    # Load target's private key.
    s.load_key('client.pem')

    # Decrypt.
    data = s.decrypt(p7)

    if data:
        print 'ok'
    else:
        print 'not ok'
Beispiel #6
0
def verify_payload(msg, raw_sig, cert, ca_cert, verify_cert):
    # Load the public certificate of the signer
    signer = SMIME.SMIME()
    signer_key = X509.X509_Stack()
    signer_key.push(X509.load_cert(cert))
    signer.set_x509_stack(signer_key)
    signer_store = X509.X509_Store()
    signer_store.load_info(ca_cert)
    signer.set_x509_store(signer_store)

    # Extract the pkcs7 signature and the data
    if raw_sig:
        raw_sig.strip()
        sig = "-----BEGIN PKCS7-----\n%s\n-----END PKCS7-----\n" % raw_sig.replace('\r\n', '\n')
        p7 = SMIME.load_pkcs7_bio(BIO.MemoryBuffer(sig))
        data_bio = BIO.MemoryBuffer(msg)
    else:
        p7, data_bio = SMIME.smime_load_pkcs7_bio(BIO.MemoryBuffer(msg))

    # Verify the signature against the message
    if verify_cert:
        signer.verify(p7, data_bio)
    else:
        # Don't verify the signer certificate if this flag is set
        signer.verify(p7, data_bio, SMIME.PKCS7_NOVERIFY)
Beispiel #7
0
def sv():
    print 'test sign/verify...',
    buf = makebuf()
    s = SMIME.SMIME()

    # Load a private key.
    s.load_key('client.pem')

    # Sign.
    p7 = s.sign(buf, SMIME.PKCS7_DETACHED)

    # Output the stuff.
    buf = makebuf()  # Recreate buf, because sign() has consumed it.
    bio = BIO.MemoryBuffer()
    s.write(bio, p7, buf)

    # Plumbing for verification: CA's cert.
    st = X509.X509_Store()
    st.load_info('ca.pem')
    s.set_x509_store(st)

    # Plumbing for verification: Signer's cert.
    x509 = X509.load_cert('client.pem')
    sk = X509.X509_Stack()
    sk.push(x509)
    s.set_x509_stack(sk)

    # Verify.
    p7, buf = SMIME.smime_load_pkcs7_bio(bio)
    v = s.verify(p7, buf, flags=SMIME.PKCS7_DETACHED)

    if v:
        print 'ok'
    else:
        print 'not ok'
Beispiel #8
0
def encrypt(input_bio, cert, keyring_source, cypher):
    """
    Encrypts the input data with the public key in the certificate from keyring
    source with selected cypher.

    @type input_bio: M2Crypto.BIO
    @param input_bio: input data to encrypt.
    @type cert:  filepath or M2Crypto.BIO or M2Crypto.X509.X509
    @param cert: the recipient certificate reference from filepath, could be
        from file, from memory or from pkcs11 smartcard, based on
        keyring_soruce input parameter.
    @type keyring_source: str
    @keyword keyring_source: the type of the source for input certificate, used
        to recall the appropriate method for encrypter settings. Ammitted
        values are: file, memory, pkcs11.
    @type cypher: str
    @keyword cypher: the cypher to use for encryption of the data, run
        "openssl enc -help" for supported cyphers, you have to choose a public
        key cypher from availables.
    @rtype: M2Crypto.SMIME.PKCS7
    @return: the PKCS#7 encrypted data in PEM format.
    """
    encrypter = SMIME.SMIME()
    x509 = set_certificate(cert, keyring_source)
    sk = X509.X509_Stack()
    sk.push(x509)
    encrypter.set_x509_stack(sk)
    encrypter.set_cipher(SMIME.Cipher(cypher))
    Rand.load_file('randpool.dat', -1)
    try:
        p7 = encrypter.encrypt(input_bio)
    except SMIME.SMIME_Error, e:
        logging.error('smime error: ' + str(e))
        raise
Beispiel #9
0
    def _get_digital_signers(self):
        if not self.pe:
            return None

        retlist = None

        if HAVE_CRYPTO:
            address = self.pe.OPTIONAL_HEADER.DATA_DIRECTORY[pefile.DIRECTORY_ENTRY['IMAGE_DIRECTORY_ENTRY_SECURITY']].VirtualAddress

            #check if file is digitally signed
            if address == 0:
                return retlist

            signature = self.pe.write()[address+8:]
            bio = BIO.MemoryBuffer(signature)

            if bio:
                swig_pkcs7 = m2.pkcs7_read_bio_der(bio.bio_ptr())

                if swig_pkcs7:
                    p7 = SMIME.PKCS7(swig_pkcs7)
                    xst = p7.get0_signers(X509.X509_Stack())
                    retlist = []
                    if xst:
                        for cert in xst:
                            sn = cert.get_serial_number()
                            sha1_fingerprint = cert.get_fingerprint('sha1').lower()
                            md5_fingerprint = cert.get_fingerprint('md5').lower()
                            subject_str = str(cert.get_subject())
                            cn = subject_str[subject_str.index("/CN=")+len("/CN="):]
                            retlist.append({"sn":str(sn), "cn":cn, "sha1_fingerprint" : sha1_fingerprint, "md5_fingerprint" : md5_fingerprint })

        return retlist
Beispiel #10
0
def plist_from_pkcs7(pkcs7):
    """Extract a plist from PKCS7 encoded data."""
    # DEP request

    # base64 encode the DER data, and wrap in a PEM-ish format for SMIME.load_pkcs7_bio()
    req_data = base64_to_pem('PKCS7', pkcs7)

    p7_bio = BIO.MemoryBuffer(str(req_data))
    pkcs7 = SMIME.load_pkcs7_bio(p7_bio)

    p7_signers = pkcs7.get0_signers(X509.X509_Stack())

    signer = SMIME.SMIME()
    signer.set_x509_store(X509.X509_Store())
    signer.set_x509_stack(p7_signers)

    # TODO/XXX: not verifying ANY certificates!
    #
    # spec says we should verify against the "Apple Root CA" and that this
    # CMS message contains all intermediates to do that verification.
    # M2Crypto has no way to get at all the intermediate certificates to
    # do this manually we'd need to extract all of the certificates and
    # verify the chain aginst it. Note as of 2016-03-14 on a brand new
    # iPad Apple was including an expired certificate in this chain. Note
    # also that at least one of the intermediate certificates had a
    # certificate purpose apparently not appropraite for CMS/SMIME
    # verification. For now just verify with no CA and skip any
    # verification.
    plist_text = signer.verify(pkcs7, None, flags=SMIME.PKCS7_NOVERIFY)

    plist = plistlib.readPlistFromString(plist_text)

    return plist
    def sign_m2(keyfile, content):
        """
        Sign content with a keyfile using M2Crypto
        """

        try:
            # load intermediate certs if any
            stack = M2X509.X509_Stack()
            _, _, certificates = parse_keyfile(keyfile)
            for c in certificates:
                cert = M2X509.load_cert_string(c)
                # skip the main CA cert, as this must be built-in anyway
                if (cert.check_ca()
                        and str(cert.get_issuer()) == str(cert.get_subject())):
                    continue
                stack.push(cert)

            # actual signing
            smime = M2S.SMIME()
            smime.load_key(keyfile)
            smime.set_x509_stack(stack)

            pkcs7 = M2Buffer()
            smime.sign(M2Buffer(content),
                       M2S.PKCS7_DETACHED | M2S.PKCS7_BINARY).write_der(pkcs7)
            return pkcs7.read()

        except M2EVPError, ex:
            if re.search("ANY PRIVATE KEY", ex.message):
                raise ValueError("Key file does not contain a private key")
            raise ValueError("Signing failed. Wrong password?")
Beispiel #12
0
    def decrypt_and_verify(self):
        # Instantiate an SMIME object.
        s = SMIME.SMIME()

        # Load private key and cert.
        s.load_key(recipient_key, recipient_cert)

        # Load the signed/encrypted data.
        p7, data = SMIME.smime_load_pkcs7('smime-m2-sign-encrypt.txt')

        # After the above step, 'data' == None.
        # Decrypt p7. 'out' now contains a PKCS #7 signed blob.
        out = s.decrypt(p7)

        # Load the signer's cert.
        x509 = X509.load_cert(signer_cert)
        sk = X509.X509_Stack()
        sk.push(x509)
        s.set_x509_stack(sk)

        # Load the signer's CA cert.
        st = X509.X509_Store()
        st.load_info(ca_cert)
        s.set_x509_store(st)

        # Recall 'out' contains a PKCS #7 blob.
        # Transform 'out'; verify the resulting PKCS #7 blob.
        p7_bio = BIO.MemoryBuffer(out)
        p7, data = SMIME.smime_load_pkcs7_bio(p7_bio)
        v = s.verify(p7)

        print v
Beispiel #13
0
def verify_mdm_signature(mdm_sig, req_data):
    '''Verify the client's supplied MDM signature and return the client certificate included in the signature.'''

    p7_bio = BIO.MemoryBuffer(str(mdm_sig))
    p7 = SMIME.load_pkcs7_bio(p7_bio)

    p7_signers = p7.get0_signers(X509.X509_Stack())

    mdm_ca = get_ca()

    # can probably directly use m2 certificate here
    ca_x509_bio = BIO.MemoryBuffer(mdm_ca.get_cacert().to_pem())
    ca_x509 = X509.load_cert_bio(ca_x509_bio)

    cert_store = X509.X509_Store()
    cert_store.add_x509(ca_x509)

    signer = SMIME.SMIME()
    signer.set_x509_store(cert_store)
    signer.set_x509_stack(p7_signers)

    # NOTE: may need to do something special if we can't cleanly convert
    # to string from Unicode. must be byte-accurate as the signature won't
    # match otherwise
    data_bio = BIO.MemoryBuffer(req_data)

    # will raise an exception if verification fails
    # if no CA certificate we get an:
    #   PKCS7_Error: certificate verify error
    signer.verify(p7, data_bio)

    return p7_signers[0].as_pem()
Beispiel #14
0
def encrypt_email_body(client: Client, args: Dict):
    """ generate an S/MIME-encrypted message

    Args:
        client: Client
        args: Dict

    """
    message_body = args.get('message', '').encode('utf-8')
    buf = makebuf(message_body)

    x509 = X509.load_cert(client.public_key_file)
    sk = X509.X509_Stack()
    sk.push(x509)
    client.smime.set_x509_stack(sk)
    client.smime.set_cipher(SMIME.Cipher('des_ede3_cbc'))
    p7 = client.smime.encrypt(buf)
    out = BIO.MemoryBuffer()

    client.smime.write(out, p7)
    encrypted_message = out.read().decode('utf-8')
    message = encrypted_message.split('\n\n')
    headers = message[0]
    new_headers = headers.replace(': ', '=').replace('\n', ',')

    entry_context = {
        'SMIME.Encrypted': {
            'Message': encrypted_message,
            'Headers': new_headers
        }
    }
    return encrypted_message, entry_context
Beispiel #15
0
    def _encrypt(self):
        """Use your key thing to encrypt things."""
        from M2Crypto import BIO, SMIME, X509
        CERT = self.settings.private_cert
        PUB_CERT = self.settings.public_cert
        PAYPAL_CERT = self.settings.paypal_cert
        CERT_ID = self.settings.cert_id

        # Iterate through the fields and pull out the ones that have a value.
        plaintext = 'cert_id=%s' % CERT_ID
        for name, value in self.items.iteritems():
            plaintext += '\n%s=%s' % (name, value)
        #plaintext = plaintext.encode('utf-8')

        # Begin crypto weirdness.
        s = SMIME.SMIME()    
        s.load_key_bio(BIO.openfile(CERT), BIO.openfile(PUB_CERT))
        p7 = s.sign(BIO.MemoryBuffer(plaintext), flags=SMIME.PKCS7_BINARY)
        x509 = X509.load_cert_bio(BIO.openfile(PAYPAL_CERT))
        sk = X509.X509_Stack()
        sk.push(x509)
        s.set_x509_stack(sk)
        s.set_cipher(SMIME.Cipher('des_ede3_cbc'))
        tmp = BIO.MemoryBuffer()
        p7.write_der(tmp)
        p7 = s.encrypt(tmp, flags=SMIME.PKCS7_BINARY)
        out = BIO.MemoryBuffer()
        p7.write(out)
        return out.read()
Beispiel #16
0
    def test_verify_with_static_callback(self):
        s = SMIME.SMIME()

        x509 = X509.load_cert('tests/signer.pem')
        sk = X509.X509_Stack()
        sk.push(x509)
        s.set_x509_stack(sk)

        st = X509.X509_Store()
        st.load_info('tests/ca.pem')
        st.set_verify_cb(verify_cb_rejects_cert_from_heikki_toivonen)
        s.set_x509_store(st)

        p7, data = SMIME.smime_load_pkcs7_bio(self.signed)
        self.assertIsInstance(p7, SMIME.PKCS7, p7)

        # Should reject certificate issued by Heikki Toivonen:
        with self.assertRaises(SMIME.PKCS7_Error):
            s.verify(p7, data)

        st.set_verify_cb(verify_cb_dummy_function)
        v = s.verify(p7, data)
        self.assertEqual(v, self.cleartext)

        st.set_verify_cb()
        v = s.verify(p7, data)
        self.assertEqual(v, self.cleartext)
Beispiel #17
0
def verify(certificate_path, ca_certificate_path, sign_request_path, output):
    certificate = None
    try:
        certificate = X509.load_cert(certificate_path)
    except (X509.X509Error, IOError):
        print('ERROR verify: Could not load certificate for verifying')
        exit(1)
    smime = SMIME.SMIME()
    stack = X509.X509_Stack()
    stack.push(certificate)
    smime.set_x509_stack(stack)
    store = X509.X509_Store()
    store.load_info(ca_certificate_path)
    smime.set_x509_store(store)
    pks7, data = SMIME.smime_load_pkcs7(sign_request_path)
    clear_text = smime.verify(pks7, data)
    if not output:
        output = path.abspath(path.curdir) + '/%s.csr' % DEFAULT_FIELDS['CN']
    if clear_text:
        request = X509.load_request_string(clear_text)
        request.save(output)
        print('Verification OK')
        print('Request file was saved to %s' % output)
    else:
        print('Verification failed')
Beispiel #18
0
    def test_encrypt(self):
        buf = BIO.MemoryBuffer(self.cleartext)
        s = SMIME.SMIME()

        x509 = X509.load_cert('tests/recipient.pem')
        sk = X509.X509_Stack()
        sk.push(x509)
        s.set_x509_stack(sk)

        with self.assertRaises(ValueError):
            SMIME.Cipher('nosuchcipher')

        s.set_cipher(SMIME.Cipher('des_ede3_cbc'))
        p7 = s.encrypt(buf)

        self.assertEqual(len(buf), 0)
        self.assertEqual(p7.type(), SMIME.PKCS7_ENVELOPED, p7.type())
        self.assertIsInstance(p7, SMIME.PKCS7, p7)
        out = BIO.MemoryBuffer()
        p7.write(out)

        buf = out.read()

        self.assertTrue(buf.startswith(b'-----BEGIN PKCS7-----'))
        buf = buf.strip()
        self.assertTrue(buf.endswith(b'-----END PKCS7-----'))
        self.assertGreater(
            len(buf),
            len(b'-----END PKCS7-----') + len(b'-----BEGIN PKCS7-----'))

        s.write(out, p7)
        return out
Beispiel #19
0
def verify_signature_block(certificate_file, content_file, signature):
    """Verifies the 'signature' over the 'content', trusting the 'certificate'.

    :param certificate_file: the trusted certificate (PEM format)
    :type certificate_file: str
    :param content_file: The signature should match this content
    :type content_file: str
    :param signature: data (DER format) subject to check
    :type signature: str
    :return: Error message, or None if the signature validates.
    :rtype: str
    """

    sig_bio = BIO.MemoryBuffer(signature)
    pkcs7 = SMIME.PKCS7(m2.pkcs7_read_bio_der(sig_bio._ptr()), 1)
    signers_cert_stack = pkcs7.get0_signers(X509.X509_Stack())
    trusted_cert_store = X509.X509_Store()
    trusted_cert_store.load_info(certificate_file)
    smime = SMIME.SMIME()
    smime.set_x509_stack(signers_cert_stack)
    smime.set_x509_store(trusted_cert_store)
    data_bio = BIO.openfile(content_file)
    try:
        smime.verify(pkcs7, data_bio)
    except SMIME.PKCS7_Error, message:
        return "Signature verification error: %s" % message
Beispiel #20
0
    def create_stack(recipients):

        # Getting the IDs of recipients
        ids = [item for item in recipients]

        # Getting a list of certificates (public keys)
        public_keys = Certificate.query.with_entities(
            Certificate.public,
            Certificate.serial).filter(Certificate.id.in_(ids)).all()

        # Creating the array of serial numbers
        recipients = [item[1] for item in public_keys]

        # Checking that keys are not empty
        if len(public_keys) == 0:
            return (None, 400, "Keys not found", [])

        # Creating the BIOs
        bios = []
        for key in public_keys:
            bios.append(BIO.MemoryBuffer(key.public.encode("utf-8")))

        # Checking that we have at least one recipient
        if len(bios) == 0:
            return (None, 404, "Recipients not found", [])

        # Creating the stack
        stack = X509.X509_Stack()
        for bio in bios:
            stack.push(X509.load_cert_bio(bio))
        return (stack, 200, "", recipients)
Beispiel #21
0
def encrypt_block(blob, pubkey):
    """
    Encrypt the given blob of data, given the public key provided.

    :return The encrypted blob.
    """
    # Make a MemoryBuffer of the message.
    inbuf = BIO.MemoryBuffer(blob)

    # Seed the PRNG.
    Rand.rand_seed(os.urandom(1024))

    # Instantiate an SMIME object.
    s = SMIME.SMIME()

    # Load target cert to encrypt to.
    x509 = X509.load_cert(pubkey)
    sk = X509.X509_Stack()
    sk.push(x509)
    s.set_x509_stack(sk)

    # Set cipher: AES 256 bit in CBC mode.
    s.set_cipher(SMIME.Cipher('aes_256_cbc'))

    # Encrypt the buffer.
    p7 = s.encrypt(inbuf)
    temp_buff = BIO.MemoryBuffer()
    s.write(temp_buff, p7)
    x = temp_buff.read()
    return x
def createSignature(hash, signingCertificatePkcs12,
                    signingCertificatePassword):
    # see also in AM: src/crypto-lib/signature.cpp / Signature::create()

    s = SMIME.SMIME()

    # M2Crypto has no support for PKCS#12, so we have to use pyopenssl here
    # to load the .p12. Since the internal structures are incompatible, we
    # have to export from pyopenssl and import to M2Crypto via PEM BIOs.
    pkcs12 = load_pkcs12(signingCertificatePkcs12, signingCertificatePassword)
    signKey = BIO.MemoryBuffer(
        dump_privatekey(FILETYPE_PEM, pkcs12.get_privatekey()))
    signCert = BIO.MemoryBuffer(
        dump_certificate(FILETYPE_PEM, pkcs12.get_certificate()))
    caCerts = X509.X509_Stack()
    if pkcs12.get_ca_certificates():
        for cert in pkcs12.get_ca_certificates():
            bio = BIO.MemoryBuffer(dump_certificate(FILETYPE_PEM, cert))
            caCerts.push(X509.load_cert_bio(bio, X509.FORMAT_PEM))

    bioHash = BIO.MemoryBuffer(hash)

    s.load_key_bio(signKey, signCert)
    s.set_x509_stack(caCerts)
    signature = s.sign(bioHash, SMIME.PKCS7_DETACHED + SMIME.PKCS7_BINARY)
    bioSignature = BIO.MemoryBuffer()
    signature.write(bioSignature)

    data = bioSignature.read_all()
    return data
    def test_encrypt(self):
        buf = BIO.MemoryBuffer(self.cleartext)
        s = SMIME.SMIME()

        x509 = X509.load_cert('test/recipient.pem')
        sk = X509.X509_Stack()
        sk.push(x509)
        s.set_x509_stack(sk)

        self.assertRaises(ValueError, SMIME.Cipher, 'nosuchcipher')

        s.set_cipher(SMIME.Cipher('des_ede3_cbc'))
        p7 = s.encrypt(buf)
        
        assert len(buf) == 0
        assert p7.type() == SMIME.PKCS7_ENVELOPED, p7.type()
        assert isinstance(p7, SMIME.PKCS7), p7
        out = BIO.MemoryBuffer()
        p7.write(out)
    
        buf = out.read()
        
        assert buf[:len('-----BEGIN PKCS7-----')] == '-----BEGIN PKCS7-----'
        buf = buf.strip()
        assert buf[-len('-----END PKCS7-----'):] == '-----END PKCS7-----'
        assert len(buf) > len('-----END PKCS7-----') + len('-----BEGIN PKCS7-----')
        
        s.write(out, p7)
        return out
Beispiel #24
0
def encrypt(data,
            cert_path='/workspace/personal/python_test/keys/myCert.pem',
            compact=True):
    # Make a MemoryBuffer of the message.
    buf = BIO.MemoryBuffer(data)

    # Instantiate an SMIME object.
    s = SMIME.SMIME()

    # Load target cert to encrypt to.
    x509 = X509.load_cert(cert_path)
    sk = X509.X509_Stack()
    sk.push(x509)
    s.set_x509_stack(sk)

    # Set cipher: 3-key triple-DES in CBC mode.
    s.set_cipher(SMIME.Cipher('des_ede3_cbc'))

    # Encrypt the buffer.
    p7 = s.encrypt(buf)

    # Output p7 to a MemoryBuffer.
    out = BIO.MemoryBuffer()
    s.write(out, p7)

    # Read output as string
    output = out.read()
    if compact:
        # create a single line encrypted message
        output = ''.join(output.split('\n')[5:])

    return output
Beispiel #25
0
    def _encrypt(self):
        """Use your key thing to encrypt things."""
        from M2Crypto import BIO, SMIME, X509

        # Iterate through the fields and pull out the ones that have a value.
        plaintext = 'cert_id=%s\n' % self.cert_id
        for name, field in self.fields.items():
            value = None
            if name in self.initial:
                value = self.initial[name]
            elif field.initial is not None:
                value = field.initial
            if value is not None:
                plaintext += u'%s=%s\n' % (name, value)
        plaintext = plaintext.encode('utf-8')

        # Begin crypto weirdness.
        s = SMIME.SMIME()
        s.load_key_bio(BIO.openfile(self.private_cert), BIO.openfile(self.public_cert))
        p7 = s.sign(BIO.MemoryBuffer(plaintext), flags=SMIME.PKCS7_BINARY)
        x509 = X509.load_cert_bio(BIO.openfile(self.paypal_cert))
        sk = X509.X509_Stack()
        sk.push(x509)
        s.set_x509_stack(sk)
        s.set_cipher(SMIME.Cipher('des_ede3_cbc'))
        tmp = BIO.MemoryBuffer()
        p7.write_der(tmp)
        p7 = s.encrypt(tmp, flags=SMIME.PKCS7_BINARY)
        out = BIO.MemoryBuffer()
        p7.write(out)
        return out.read().decode()
Beispiel #26
0
    def test_signEncryptDecryptVerify(self):
        # sign
        buf = BIO.MemoryBuffer(self.cleartext)
        s = SMIME.SMIME()
        s.load_key('tests/signer_key.pem', 'tests/signer.pem')
        p7 = s.sign(buf)

        # encrypt
        x509 = X509.load_cert('tests/recipient.pem')
        sk = X509.X509_Stack()
        sk.push(x509)
        s.set_x509_stack(sk)

        s.set_cipher(SMIME.Cipher('des_ede3_cbc'))

        tmp = BIO.MemoryBuffer()
        s.write(tmp, p7)

        p7 = s.encrypt(tmp)

        signedEncrypted = BIO.MemoryBuffer()
        s.write(signedEncrypted, p7)

        # decrypt
        s = SMIME.SMIME()

        s.load_key('tests/recipient_key.pem', 'tests/recipient.pem')

        p7, data = SMIME.smime_load_pkcs7_bio(signedEncrypted)

        out = s.decrypt(p7)

        # verify
        x509 = X509.load_cert('tests/signer.pem')
        sk = X509.X509_Stack()
        sk.push(x509)
        s.set_x509_stack(sk)

        st = X509.X509_Store()
        st.load_info('tests/ca.pem')
        s.set_x509_store(st)

        p7_bio = BIO.MemoryBuffer(out)
        p7, data = SMIME.smime_load_pkcs7_bio(p7_bio)
        v = s.verify(p7)
        self.assertEqual(v, self.cleartext)
Beispiel #27
0
 def get_peer_cert_chain(self):
     """Return the peer certificate chain; if the peer did not provide 
     a certificate chain, return None."""
     c = m2.ssl_get_peer_cert_chain(self.ssl)
     if c is None:
         return None
     # No need to free the pointer coz OpenSSL does.
     return X509.X509_Stack(c)
Beispiel #28
0
    def show_signer(self):
        """ List info about the signer that is in pkcs7 document"""
        sk = X509.X509_Stack()

        tempSt = self.__p7.get0_signers(sk)

        ldb = ListDb(tempSt.pop(), tip=1)
        ldb.per_info()
def smime_encrypt(raw_message, recipients):

    if not get_bool_from_cfg('smime', 'cert_path'):
        log("No valid path for S/MIME certs found in config file. S/MIME encryption aborted."
            )
        return recipients

    cert_path = cfg['smime']['cert_path'] + "/"
    s = SMIME.SMIME()
    sk = X509.X509_Stack()
    smime_to = list()
    unsmime_to = list()

    for addr in recipients:
        cert_and_email = get_cert_for_email(addr, cert_path)

        if not (cert_and_email is None):
            (to_cert, normal_email) = cert_and_email
            if verbose:
                log("Found cert " + to_cert + " for " + addr + ": " +
                    normal_email)
            smime_to.append(addr)
            x509 = X509.load_cert(to_cert, format=X509.FORMAT_PEM)
            sk.push(x509)
        else:
            unsmime_to.append(addr)

    if smime_to != list():
        s.set_x509_stack(sk)
        s.set_cipher(SMIME.Cipher('aes_192_cbc'))
        p7 = s.encrypt(BIO.MemoryBuffer(raw_message.as_string()))
        # Output p7 in mail-friendly format.
        out = BIO.MemoryBuffer()
        out.write('From: ' + from_addr + '\n')
        out.write('To: ' + raw_message['To'] + '\n')
        if raw_message['Cc']:
            out.write('Cc: ' + raw_message['Cc'] + '\n')
        if raw_message['Bcc']:
            out.write('Bcc: ' + raw_message['Bcc'] + '\n')
        if raw_message['Subject']:
            out.write('Subject: ' + raw_message['Subject'] + '\n')

        if get_bool_from_cfg('default', 'add_header', 'yes'):
            out.write('X-GPG-Mailgate: Encrypted by GPG Mailgate\n')

        s.write(out, p7)

        if verbose:
            log("Sending message from " + from_addr + " to " + str(smime_to))

        send_msg(out.read(), smime_to)
    if unsmime_to != list():
        if verbose:
            log("Unable to find valid S/MIME certificates for " +
                str(unsmime_to))

    return unsmime_to
Beispiel #30
0
    def run(self):
        """Run analysis.
        @return: analysis results dict or None.
        """
        if not os.path.exists(self.file_path):
            return None

        try:
            self.pe = pefile.PE(self.file_path)
        except pefile.PEFormatError:
            return None

        results = {}
        results["peid_signatures"] = self._get_peid_signatures()
        results["pe_imports"] = self._get_imported_symbols()
        results["pe_exports"] = self._get_exported_symbols()
        results["pe_dirents"] = self._get_directory_entries()
        results["pe_sections"] = self._get_sections()
        results["pe_overlay"] = self._get_overlay()
        results["pe_resources"] = self._get_resources()
        results["pe_versioninfo"] = self._get_versioninfo()
        results["pe_imphash"] = self._get_imphash()
        results["pe_timestamp"] = self._get_timestamp()
        results["imported_dll_count"] = len(
            [x for x in results["pe_imports"] if x.get("dll")])

        if HAVE_CRYPTO:
            address = self.pe.OPTIONAL_HEADER.DATA_DIRECTORY[
                pefile.DIRECTORY_ENTRY[
                    'IMAGE_DIRECTORY_ENTRY_SECURITY']].VirtualAddress

            #check if file is digitally signed
            if address == 0:
                return results

            signature = self.pe.write()[address + 8:]
            bio = BIO.MemoryBuffer(signature)

            if bio:
                swig_pkcs7 = m2.pkcs7_read_bio_der(bio.bio_ptr())

                if swig_pkcs7:
                    p7 = SMIME.PKCS7(swig_pkcs7)
                    xst = p7.get0_signers(X509.X509_Stack())
                    results["digital_signer"] = {}
                    if xst:
                        for cert in xst:
                            sn = cert.get_serial_number()
                            subject_str = str(cert.get_subject())
                            cn = subject_str[subject_str.index("/CN=") +
                                             len("/CN="):]
                            results["digital_signer"] = [{
                                "sn": str(sn),
                                "cn": cn
                            }]

        return results