def verify_certificate_chain(certificate_chain):
    """ Verify the certificate chain to be valid

    input:
    certificate_chain: [cert1,cert2,cert3]
    List of certificates (*in PEM FORMAT*) in the certificate chain. It assumes that the last certificate is the Root CA certificate.

    output:
    [True|False]
    Boolean value
    """
    CAfile_contents = _create_CAfile_contents_from_cert_chain(certificate_chain)

    CAfile_tempfile_name=utility_functions.store_data_to_temp_file(CAfile_contents)

    level1_cert_to_verify_contents = certificate_chain[0]

    level1_cert_to_verify_tempfile_name=utility_functions.store_data_to_temp_file(level1_cert_to_verify_contents)
    try:
        verify_level1_cert_command_out = utility_functions.system_command_logged([openssl_binary_path, 'verify', '-CAfile', CAfile_tempfile_name, level1_cert_to_verify_tempfile_name])
    except:
        logger.critical("verify_certificate_chain: OPENSSL could not verify cert chain")
    logger.debug("OpenSSL verify command output: " + verify_level1_cert_command_out)
    logger.debug("Deleting temporary files: " + CAfile_tempfile_name +", " + level1_cert_to_verify_tempfile_name)
    os.unlink(CAfile_tempfile_name)
    os.unlink(level1_cert_to_verify_tempfile_name)

    if verify_level1_cert_command_out.rstrip() == level1_cert_to_verify_tempfile_name + ": OK":
        logger.debug("The certificate chain is verified")
        return True
    else:
        logger.debug("The certificate chain is not verified")
        return False
def _get_hmacparams_from_certificate_subject_dictionary(certificate_subject_dictionary):
    """ Return a dictionary of the HMAC params from the certificate subject dictionary
    input:
        certificate_subject_dictionary = dictionary of subject params from certificate

    output:
        hmac_params = Dictionary of HMAC parameters from certificate subject
    """

    sw_id_re=re.compile(r'01 ([0-9A-F]{16}) SW_ID')
    hw_id_re=re.compile(r'02 ([0-9A-F]{16}) HW_ID')
    if 'OU' in certificate_subject_dictionary.keys() and type(certificate_subject_dictionary['OU'])==list:
        certificate_subject_dictionary['OU'].sort()
    sw_id_element = sw_id_re.match(certificate_subject_dictionary['OU'][0])
    hw_id_element = hw_id_re.match(certificate_subject_dictionary['OU'][1])
    if sw_id_element == None:
        logger.critical("Error in certificate subject. SW_ID field not found. Not a valid certificate. Exiting")
        raise RuntimeError("Error in certificate subject. SW_ID field not found. Not a valid certificate. Exiting")
    elif hw_id_element == None:
        logger.critical("Error in certificate subject. HW_ID field not found. Not a valid certificate. Exiting")
        raise RuntimeError("Error in certificate subject. HW_ID field not found. Not a valid certificate. Exiting")
    else:
        logger.debug("Valid certificate: Found SW_ID and HW_ID")
        sw_id_text = sw_id_element.group(1)
        hw_id_text = hw_id_element.group(1)
        logger.debug('SW_ID = ' + sw_id_text)
        logger.debug('HW_ID = ' + hw_id_text)
        hw_id_int = int(hw_id_text, 16)
        sw_id_int = int(sw_id_text, 16)
        hmac_params = HmacParams(hw_id_int, sw_id_int)
        return hmac_params
 def discover_openSSL_implementation(self):
     logger.debug("Beginning discovery of openssl implementation")
     logger.debug("Looking for openssl binary")
     openssl_binaries = self.which_cmd('openssl')
     if len(openssl_binaries)>0:
         logger.debug("Found OpenSSL binary at {0}".format(openssl_binaries[0]))
         import openssl_binary_implementation as openssl_impl
         if sys.platform!='linux2':
             openssl_impl.openssl_binary_path=self.relative_path_to_packaged_openssl_binary
         else:
             openssl_impl.openssl_binary_path=openssl_binaries[0]
         if 'OPENSSL_DIR' in os.environ:
             if sys.platform!='linux2':
                 openssl_impl.openssl_binary_path=os.path.join(os.environ['OPENSSL_DIR'],'openssl.exe')
             else:
                 openssl_impl.openssl_binary_path=os.path.join(os.environ['OPENSSL_DIR'],'openssl')
         openssl_impl.ccm_crypto_path=self.relative_path_to_packaged_ccm_binary
         openssl_impl.cbc_crypto_path=self.relative_path_to_packaged_cbc_binary
     else:
         try:
             logger.debug("Looking for M2Crypto")
             import M2Crypto as openssl_impl
         except ImportError:
             logger.debug("Could not find M2Crypto module")
             logger.critical("Could not find OpenSSL Implementation")
             raise RuntimeError("Could not find OpenSSL Implementation")
     return openssl_impl
def privkey_pem_to_der(pem_privkey):
    """ Convert PEM format PRIVATE key into DER format
    input:
    pem_privkey: String containing base64 PEM Private key

    output
    der_privkey: String containing binary Private key
    """
    der_privkey = ''
    pem_tempfile_name = utility_functions.store_data_to_temp_file(pem_privkey)
    try:
        der_privkey = utility_functions.system_command_logged(
            [
                openssl_binary_path, 'rsa', '-in', pem_tempfile_name,
                '-inform', 'PEM', '-outform', 'DER'
            ],
            stderr_to_temp=True)
        logger.debug2("PEM Format private key: " + hexdump(der_privkey))
    except:
        logger.critical(
            "privkey_pem_to_der: OPENSSL Could not convert PEM key to DER key")
    finally:
        os.unlink(pem_tempfile_name)
        logger.debug("Deleting temporary file: " + pem_tempfile_name)
    return der_privkey
def privkey_der_to_pem(der_privkey):
    """ Convert binary DER format PRIVATE key into base64 coded ASCII PEM format
    input:
    der_privkey: String containing binary PRIVATE KEY

    output
    pem_privkey: String containing base64 PEM PRIVATE KEY
    """
    pem_privkey = ''
    der_tempfile_name = utility_functions.store_data_to_temp_file(der_privkey)
    try:
        pem_privkey = utility_functions.system_command_logged(
            [
                openssl_binary_path, 'rsa', '-in', der_tempfile_name,
                '-inform', 'DER', '-outform', 'PEM'
            ],
            stderr_to_temp=True)
        logger.debug2("PEM Format Private Key: " + pem_privkey)
    except:
        logger.critical(
            "privkey_der_to_pem: OPENSSL Could not convert DER key to PEM")
    finally:
        os.unlink(der_tempfile_name)
        logger.debug("Deleting temporary file: " + der_tempfile_name)
    return pem_privkey
def cert_der_to_pem(der_certificate):
    """ Convert binary DER format certificate into base64 coded ASCII PEM format
    input:
    der_certificate: String containing binary certificate

    output
    pem_certificate: String containing base64 PEM certificate
    """

    der_tempfile_name = utility_functions.store_data_to_temp_file(
        der_certificate)
    try:
        pem_certificate = utility_functions.system_command_logged(
            [
                openssl_binary_path, 'x509', '-in', der_tempfile_name,
                '-inform', 'DER', '-outform', 'PEM'
            ],
            stderr_to_temp=True)
    except:
        logger.critical(
            "cert_der_to_pem: OPENSSL could not convert DER cert to PEM")
    logger.debug2("PEM Format certificate: " + pem_certificate)
    logger.debug("Deleting temporary file: " + der_tempfile_name)
    os.unlink(der_tempfile_name)
    return pem_certificate
 def discover_openSSL_implementation(self):
     logger.debug("Beginning discovery of openssl implementation")
     logger.debug("Looking for openssl binary")
     openssl_binaries = self.which_cmd('openssl')
     if len(openssl_binaries)>0:
         logger.debug("Found OpenSSL binary at {0}".format(openssl_binaries[0]))
         import openssl_binary_implementation as openssl_impl
         if sys.platform!='linux2':
             openssl_impl.openssl_binary_path=self.relative_path_to_packaged_openssl_binary
         else:
             openssl_impl.openssl_binary_path=openssl_binaries[0]
         if 'OPENSSL_DIR' in os.environ:
             if sys.platform!='linux2':
                 openssl_impl.openssl_binary_path=os.path.join(os.environ['OPENSSL_DIR'],'openssl.exe')
             else:
                 openssl_impl.openssl_binary_path=os.path.join(os.environ['OPENSSL_DIR'],'openssl')
         openssl_impl.ccm_crypto_path=self.relative_path_to_packaged_ccm_binary
         openssl_impl.cbc_crypto_path=self.relative_path_to_packaged_cbc_binary
     else:
         try:
             logger.debug("Looking for M2Crypto")
             import M2Crypto as openssl_impl
         except ImportError:
             logger.debug("Could not find M2Crypto module")
             logger.critical("Could not find OpenSSL Implementation")
             raise RuntimeError("Could not find OpenSSL Implementation")
     return openssl_impl
def cert_pem_to_der(pem_certificate):
    """ Convert PEM format certificate into DER format
    input:
    pem_certificate: String containing base64 PEM certificate

    output
    der_certificate: String containing binary certificate
    """

    pem_tempfile_name = utility_functions.store_data_to_temp_file(
        pem_certificate)
    try:
        der_certificate = utility_functions.system_command_logged(
            [
                openssl_binary_path, 'x509', '-in', pem_tempfile_name,
                '-inform', 'PEM', '-outform', 'DER'
            ],
            stderr_to_temp=True)
    except:
        logger.critical(
            "cert_pem_to_der: OPENSSL could not convert PEM cert to DER")
    logger.debug2("PEM Format certificate: " + hexdump(der_certificate))
    logger.debug("Deleting temporary file: " + pem_tempfile_name)
    os.unlink(pem_tempfile_name)
    return der_certificate
def encrypt_with_private_key(message, private_key):
    """ Encrypt a message with a private key
    input:
        message: String representing message
        private_key: String representing the private key

    output:
        signature: String representing encrypted message
    """

    private_key_tempfile_name = utility_functions.store_data_to_temp_file(
        private_key)
    message_tempfile_name = utility_functions.store_data_to_temp_file(message)

    command_list = [
        openssl_binary_path, "rsautl", "-sign", "-pkcs", "-inkey",
        private_key_tempfile_name, '-in', message_tempfile_name
    ]
    try:
        encrypted_message = utility_functions.system_command_logged(
            command_list, stderr_to_temp=True)
    except:
        logger.critical(
            "encrypt_with_private_key: OPENSSL could not perform RSA sign operation"
        )

    return encrypted_message
def decrypt_with_public_key(encrypted_message, public_key):
    """ Decrypt an encrypted message with a public key
    input:
        encrypted_message = String representation of encrypted message
        public_key = String representation of public key

    output:
        message = String representing decrypted message
    """
    public_key_tempfile_name = utility_functions.store_data_to_temp_file(
        public_key)
    encrypted_message_tempfile_name = utility_functions.store_data_to_temp_file(
        encrypted_message)

    command_list = [
        openssl_binary_path, 'rsautl', '-inkey', public_key_tempfile_name,
        '-pubin', '-in', encrypted_message_tempfile_name
    ]
    try:
        message = utility_functions.system_command_logged(command_list,
                                                          stderr_to_temp=True)
    except:
        logger.critical(
            "decrypt_with_public_key: OPENSSL could not decrypt with public key"
        )
    return message
Example #11
0
    def _validate_certificate_params_dict(self, certificate_params_dict):
        certificate_params_is_valid = False
        generate_new_certificate = False
        for key in certificate_params_dict:
            if key not in ['C', 'CN', 'L', 'O', 'ST', 'OU', 'emailAddress']:
                if key not in ['private_key_path', 'certificate_path']:
                    logger.error("Invalid Key is being passed in configuration!" + repr(key))
                    raise RuntimeError("Invalid Key is being passed in configuration!")
                else:
                    # pre-generated cert/key, check if exist
                    if os.path.exists(certificate_params_dict['private_key_path']) is False:
                        err_str = "private_key_path does not exist: {0}!".format(certificate_params_dict['private_key_path'])
                        logger.error(err_str)
                        certificate_params_is_valid = False
                        raise RuntimeError(err_str)

                    if os.path.exists(certificate_params_dict['certificate_path']) is False:
                        err_str = "certificate_path does not exist: {0}!".format(certificate_params_dict['certificate_path'])
                        logger.error(err_str)
                        certificate_params_is_valid = False
                        raise RuntimeError(err_str)

                    cert_version = crypto.cert.get_version(crypto.cert.get_text(c_path.load_data_from_file(certificate_params_dict['certificate_path'])))
                    if cert_version == crypto.cert.CERT_V3:
                        generate_new_certificate = False
                        certificate_params_is_valid = True
                    else:
                        logger.critical('Certificate version is incorrect: ' + str(cert_version))
                        raise RuntimeError('Invalid certificate: ' + certificate_params_dict['certificate_path'])

            else: # generate new cert/key
                certificate_params_is_valid = True
                generate_new_certificate = True

        return certificate_params_is_valid, generate_new_certificate
def _execute_openssl_certificate_command(command_list, key_pair, key_tempfile_name, shell=False):
    try:
        certificate_request = utility_functions.system_command_logged(command_list, stderr_to_temp=True, shell=shell)
    except subprocess.CalledProcessError, e:
        logger.critical("call to OpenSSL binary returned an error!: retval = " + str(e.returncode) + " Command = " + str(e.cmd))
        raise RuntimeError("call to OpenSSL binary returned an error!: retval = " + str(e.returncode) +
                                                                    " \nCommand = " + ' '.join(e.cmd))
def get_public_key_from_cert_chain(certificate_chain_list):
    """ Verify certificate chain and extract public key from chain list

    """
    if verify_certificate_chain(certificate_chain_list):
        return _extract_public_key_from_certificate(certificate_chain_list[0])
    else:
        logger.critical("The certificate chain could not be verified!")
        raise RuntimeError("The certificate chain could not be verified!")
def get_public_key_from_cert_chain(certificate_chain_list):
    """ Verify certificate chain and extract public key from chain list

    """
    if verify_certificate_chain(certificate_chain_list):
        return _extract_public_key_from_certificate(certificate_chain_list[0])
    else:
        logger.critical("The certificate chain could not be verified!")
        raise RuntimeError("The certificate chain could not be verified!")
def gen_rsa_key_pair(key_size_in_bits, key_exponent, priv_key_output_file,
                     pub_key_output_file):
    """ Generate RSA Key pair

        input:

        key_size_in_bits: Size of the key in bits.
        key_exponent: [3, 65537]
                      Exponent used in key calculation.
        priv_key_output_file: File name for storing private key
        pub_key_output_file: File name for storing public key

        output:

        returned value: {"public_key": [Generated public key],
                         "private_key": [Generated private key] }
                         Dictionary holding the values of public and private keys
    """

    logger.debug("the openssl_binary is:{0}".format(openssl_binary_path))
    if key_exponent == 3:
        exponent_str = "-3"
    elif key_exponent == 65537:
        exponent_str = "-f4"
    else:
        logger.warning(
            "Exponent value supplied is INVALID! going with default exponent of 65537."
        )
        exponent_str = "-f4"

    key_size_str = str(key_size_in_bits)

    if priv_key_output_file is not None:
        pk_file = open(priv_key_output_file, "wb")
    else:
        pk_file = tempfile.NamedTemporaryFile(delete=False)
        logger.debug(
            "No output file specified for private key storage, so creating temp file: "
            + pk_file.name)

    try:
        private_key = utility_functions.system_command_logged(
            [openssl_binary_path, "genrsa", exponent_str, key_size_str],
            stderr_to_temp=True)
    except subprocess.CalledProcessError, e:
        os.unlink(pk_file.name)
        logger.critical(
            "gen_rsa_key_pair: OPENSSL Errored out on generation of RSA key.")
        logger.critical(
            "call to OpenSSL binary returned an error!: retval = " +
            str(e.returncode) + " Command = " + str(e.cmd))
        raise RuntimeError(
            "call to OpenSSL binary returned an error!: retval = " +
            str(e.returncode) + " Command = " + str(e.cmd))
Example #16
0
    def init_from_cert(self, cert):
        # Extract the params from the cert
        cert_text = cert_functions.get_text(cert)
        params = cert_functions.get_subject_params(
            cert_functions.get_subject(cert_text))

        # Patterns to look for
        sw_id_re = re.compile(r'01 ([0-9A-F]{16}) SW_ID')
        hw_id_re = re.compile(r'02 ([0-9A-F]{16}) HW_ID')
        hash_algo_re = re.compile(r'07 ([0-9]{4}) SHA([0-9]+)')

        # Extract the fields
        if 'OU' in params.keys() and type(params['OU']) == list:
            params['OU'].sort()
        sw_id_element, hw_id_element, hash_algo_element = None, None, None
        for p in params['OU']:
            if sw_id_element is None:
                sw_id_element = sw_id_re.match(p)
            if hw_id_element is None:
                hw_id_element = hw_id_re.match(p)
            if hash_algo_element is None:
                hash_algo_element = hash_algo_re.match(p)

        # Check if fields are missing
        if sw_id_element is None:
            logger.critical(
                "Error in certificate subject. SW_ID field not found. Not a valid certificate. Exiting"
            )
            raise RuntimeError(
                "Error in certificate subject. SW_ID field not found. Not a valid certificate. Exiting"
            )
        elif hw_id_element is None:
            logger.critical(
                "Error in certificate subject. HW_ID field not found. Not a valid certificate. Exiting"
            )
            raise RuntimeError(
                "Error in certificate subject. HW_ID field not found. Not a valid certificate. Exiting"
            )

        # Update the fields
        logger.debug("Valid certificate: Found SW_ID and HW_ID")
        sw_id_text = sw_id_element.group(1)
        hw_id_text = hw_id_element.group(1)
        hash_algo_text = hash_algo_element.group(
            2) if hash_algo_element is not None else '256'
        logger.debug('SW_ID = ' + sw_id_text)
        logger.debug('HW_ID = ' + hw_id_text)
        self.msm_id = int(hw_id_text, 16)
        self.sw_id = int(sw_id_text, 16)
        self.hash_algo = 'sha' + hash_algo_text
def get_public_key_from_private_key(private_key):
    """ Extracts public key from provided private key
    input:
    private_key: String representation of private key

    output:
    public key: String representation of public key
    """

    privkey_tempfile = utility_functions.store_data_to_temp_file(private_key)
    try:
        public_key = utility_functions.system_command_logged([openssl_binary_path, "rsa", "-in", privkey_tempfile, "-pubout"], stderr_to_temp=True)
    except subprocess.CalledProcessError, e:
        logger.critical("call to OpenSSL binary returned an error!: retval = " + str(e.returncode) + " Command = " + str(e.cmd))
        raise RuntimeError("call to OpenSSL binary returned an error!: retval = " + str(e.returncode) + " Command = " + str(e.cmd))
def privkey_der_to_pem(der_privkey):
    """ Convert binary DER format PRIVATE key into base64 coded ASCII PEM format
    input:
    der_privkey: String containing binary PRIVATE KEY

    output
    pem_privkey: String containing base64 PEM PRIVATE KEY
    """
    der_tempfile_name = utility_functions.store_data_to_temp_file(der_privkey)
    try:
        pem_privkey = utility_functions.system_command_logged([openssl_binary_path, 'rsa', '-in', der_tempfile_name, '-inform', 'DER', '-outform', 'PEM'], stderr_to_temp=True)
    except:
        logger.critical("privkey_der_to_pem: OPENSSL Could not convert DER key to PEM")
    logger.debug2("PEM Format Private Key: " + pem_privkey)
    logger.debug("Deleting temporary file: " + der_tempfile_name)
    os.unlink(der_tempfile_name)
    return pem_privkey
def privkey_pem_to_der(pem_privkey):
    """ Convert PEM format PRIVATE key into DER format
    input:
    pem_privkey: String containing base64 PEM Private key

    output
    der_privkey: String containing binary Private key
    """
    pem_tempfile_name = utility_functions.store_data_to_temp_file(pem_privkey)
    try:
        der_privkey = utility_functions.system_command_logged([openssl_binary_path, 'rsa', '-in', pem_tempfile_name, '-inform', 'PEM', '-outform', 'DER'], stderr_to_temp=True)
    except:
        logger.critical("privkey_pem_to_der: OPENSSL Could not convert PEM key to DER key")
    logger.debug2("PEM Format private key: " + hexdump(der_privkey))
    logger.debug("Deleting temporary file: " + pem_tempfile_name)
    os.unlink(pem_tempfile_name)
    return der_privkey
def _extract_public_key_from_certificate(certificate):
    """ Pulls out public key stored in certificate.
    input:
        certificate = String representation of PEM certificate

    output:
        public_key = String representation of public key in certificate
    """
    certificate_tempfile_name=utility_functions.store_data_to_temp_file(certificate)

    command_list = [openssl_binary_path, 'x509', '-in', certificate_tempfile_name, '-pubkey', '-noout', '-inform', 'PEM']
    try:
        public_key = utility_functions.system_command_logged(command_list)
    except:
        logger.critical("_extract_public_key_from_certificate: OPENSSL could not extract public key from cert")

    return public_key
def cert_der_to_pem(der_certificate):
    """ Convert binary DER format certificate into base64 coded ASCII PEM format
    input:
    der_certificate: String containing binary certificate

    output
    pem_certificate: String containing base64 PEM certificate
    """

    der_tempfile_name = utility_functions.store_data_to_temp_file(der_certificate)
    try:
        pem_certificate = utility_functions.system_command_logged([openssl_binary_path, 'x509', '-in', der_tempfile_name, '-inform', 'DER', '-outform', 'PEM'], stderr_to_temp=True)
    except:
        logger.critical("cert_der_to_pem: OPENSSL could not convert DER cert to PEM")
    logger.debug2("PEM Format certificate: " + pem_certificate)
    logger.debug("Deleting temporary file: " + der_tempfile_name)
    os.unlink(der_tempfile_name)
    return pem_certificate
def cert_pem_to_der(pem_certificate):
    """ Convert PEM format certificate into DER format
    input:
    pem_certificate: String containing base64 PEM certificate

    output
    der_certificate: String containing binary certificate
    """

    pem_tempfile_name = utility_functions.store_data_to_temp_file(pem_certificate)
    try:
        der_certificate = utility_functions.system_command_logged([openssl_binary_path, 'x509', '-in', pem_tempfile_name, '-inform', 'PEM', '-outform', 'DER'], stderr_to_temp=True)
    except:
        logger.critical("cert_pem_to_der: OPENSSL could not convert PEM cert to DER")
    logger.debug2("PEM Format certificate: " + hexdump(der_certificate))
    logger.debug("Deleting temporary file: " + pem_tempfile_name)
    os.unlink(pem_tempfile_name)
    return der_certificate
def decrypt_with_public_key(encrypted_message, public_key):
    """ Decrypt an encrypted message with a public key
    input:
        encrypted_message = String representation of encrypted message
        public_key = String representation of public key

    output:
        message = String representing decrypted message
    """
    public_key_tempfile_name =utility_functions.store_data_to_temp_file(public_key)
    encrypted_message_tempfile_name = utility_functions.store_data_to_temp_file(encrypted_message)

    command_list=[openssl_binary_path, 'rsautl', '-inkey', public_key_tempfile_name, '-pubin', '-in', encrypted_message_tempfile_name]
    try:
        message = utility_functions.system_command_logged(command_list, stderr_to_temp=True)
    except:
        logger.critical("decrypt_with_public_key: OPENSSL could not decrypt with public key")
    return message
def encrypt_with_private_key(message, private_key):
    """ Encrypt a message with a private key
    input:
        message: String representing message
        private_key: String representing the private key

    output:
        signature: String representing encrypted message
    """

    private_key_tempfile_name =utility_functions.store_data_to_temp_file(private_key)
    message_tempfile_name = utility_functions.store_data_to_temp_file(message)

    command_list = [openssl_binary_path, "rsautl", "-sign", "-pkcs", "-inkey", private_key_tempfile_name, '-in', message_tempfile_name]
    try:
        encrypted_message = utility_functions.system_command_logged(command_list, stderr_to_temp=True)
    except:
        logger.critical("encrypt_with_private_key: OPENSSL could not perform RSA sign operation")

    return encrypted_message
def generate_hash(hashing_algorithm, file_to_hash):
    """ Function to generate hashes of input file using the standard hashing algoritm specified

        input:  hashing_algorithm: ["SHA1"|"SHA256"]
                file_to_hash: The file to calculate the hash of.

        output: string representing hash of file_to_hash

    """
    if hashing_algorithm.lower() not in ["sha1", "sha256"]:
        logger.warning("The algorithm specified is invalid! Using SHA256 as default.")
        hashing_algorithm="-sha256"
    else:
        hashing_algorithm = "-" + hashing_algorithm

    try:
        generated_hash = utility_functions.system_command_logged([openssl_binary_path, "dgst", hashing_algorithm, file_to_hash]).rstrip().split("= ")[1]
    except:
        logger.critical("generate_hash: OPENSSL Hash generation failed")
    return generated_hash
def gen_rsa_key_pair(key_size_in_bits, key_exponent, priv_key_output_file, pub_key_output_file):
    """ Generate RSA Key pair

        input:

        key_size_in_bits: Size of the key in bits.
        key_exponent: [3, 65537]
                      Exponent used in key calculation.
        priv_key_output_file: File name for storing private key
        pub_key_output_file: File name for storing public key

        output:

        returned value: {"public_key": [Generated public key],
                         "private_key": [Generated private key] }
                         Dictionary holding the values of public and private keys
    """

    logger.debug("the openssl_binary is:{0}".format(openssl_binary_path))
    if key_exponent==3:
        exponent_str="-3"
    elif key_exponent == 65537:
        exponent_str="-f4"
    else:
        logger.warning("Exponent value supplied is INVALID! going with default exponent of 65537.")
        exponent_str="-f4"

    key_size_str=str(key_size_in_bits)

    if priv_key_output_file is not None:
        pk_file=open(priv_key_output_file,"wb")
    else:
        pk_file=tempfile.NamedTemporaryFile(delete=False)
        logger.debug("No output file specified for private key storage, so creating temp file: " + pk_file.name)

    try:
        private_key = utility_functions.system_command_logged([openssl_binary_path, "genrsa", exponent_str, key_size_str], stderr_to_temp=True)
    except subprocess.CalledProcessError, e:
        logger.critical("gen_rsa_key_pair: OPENSSL Errored out on generation of RSA key.")
        logger.critical("call to OpenSSL binary returned an error!: retval = " + str(e.returncode) + " Command = " + str(e.cmd))
        raise RuntimeError("call to OpenSSL binary returned an error!: retval = " + str(e.returncode) + " Command = " + str(e.cmd))
Example #27
0
    def get_hmac_params_from_cert(cls,
                                  certificate=None,
                                  extracted_attributes=None):
        """ Return a dictionary of the HMAC params from the certificate subject dictionary
        input:
            certificate_subject_dictionary = dictionary of subject params from certificate

        output:
            hmac_params = Dictionary of HMAC parameters from certificate subject
        """

        if certificate:
            certificate_subject_dictionary = crypto.cert.get_subject_params(
                crypto.cert.get_subject(certificate))
            sw_id_re = re.compile(r'01 ([0-9A-F]{16}) SW_ID')
            hw_id_re = re.compile(r'02 ([0-9A-F]{16}) HW_ID')
            if 'OU' in certificate_subject_dictionary.keys() and type(
                    certificate_subject_dictionary['OU']) == list:
                certificate_subject_dictionary['OU'].sort()
            sw_id_element = sw_id_re.match(
                certificate_subject_dictionary['OU'][0])
            hw_id_element = hw_id_re.match(
                certificate_subject_dictionary['OU'][1])
            logger.debug("Valid certificate: Found SW_ID and HW_ID")
            sw_id = sw_id_element.group(
                1) if sw_id_element is not None else None
            hw_id = hw_id_element.group(
                1) if hw_id_element is not None else None
        elif extracted_attributes:
            if extracted_attributes.from_hash_segment:
                hmac_params = cls.get_hmac_params_from_extracted_attributes(
                    extracted_attributes)
                sw_id = hmac_params.sw_id_str
                hw_id = hmac_params.msm_id_str
            else:
                sw_id = extracted_attributes.sw_id
                hw_id = extracted_attributes.hw_id
        else:
            logger.critical(
                "certificate and extracted_attributes cannot both be none")
            raise RuntimeError(
                "certificate and attribute_extractor cannot both be none")

        if sw_id is None:
            logger.critical("Error in image. SW_ID field not found. Exiting")
            raise RuntimeError(
                "Error in image. SW_ID field not found. Exiting")
        elif hw_id is None:
            logger.critical("Error in image. HW_ID field not found. Exiting")
            raise RuntimeError(
                "Error in image. HW_ID field not found. Exiting")

        logger.debug('SW_ID = ' + sw_id)
        logger.debug('HW_ID = ' + hw_id)
        hmac_params = HmacParams(int(hw_id, 16), int(sw_id, 16))
        return hmac_params
    try:
        private_key = utility_functions.system_command_logged([openssl_binary_path, "genrsa", exponent_str, key_size_str], stderr_to_temp=True)
    except subprocess.CalledProcessError, e:
        logger.critical("gen_rsa_key_pair: OPENSSL Errored out on generation of RSA key.")
        logger.critical("call to OpenSSL binary returned an error!: retval = " + str(e.returncode) + " Command = " + str(e.cmd))
        raise RuntimeError("call to OpenSSL binary returned an error!: retval = " + str(e.returncode) + " Command = " + str(e.cmd))

    logger.debug("Writing generated private key to PEM file:" + pk_file.name)
    pk_file.write(private_key)
    pk_file.close()

    try:
        public_key = utility_functions.system_command_logged([openssl_binary_path, "rsa", "-in", pk_file.name, "-pubout"], stderr_to_temp=True)
    except subprocess.CalledProcessError, e:
        logger.critical("gen_rsa_key_pair: OPENSSL could not get public key")
        logger.critical("call to OpenSSL binary returned an error!: retval = " + str(e.returncode) + " Command = " + str(e.cmd))
        raise RuntimeError("call to OpenSSL binary returned an error!: retval = " + str(e.returncode) + " Command = " + str(e.cmd))

    if pub_key_output_file is not None:
        logger.debug("Writing public key to file: " + pub_key_output_file)
        pubk_file=open(pub_key_output_file,"wb")
        pubk_file.write(public_key)
        pubk_file.close()

    if priv_key_output_file is None:
        logger.debug("Since private key file is temporary, deleting: " + pk_file.name)
        os.unlink(pk_file.name)

    return {'private_key': private_key, 'public_key': public_key}
            "call to OpenSSL binary returned an error!: retval = " +
            str(e.returncode) + " Command = " + str(e.cmd))
        raise RuntimeError(
            "call to OpenSSL binary returned an error!: retval = " +
            str(e.returncode) + " Command = " + str(e.cmd))

    logger.debug("Writing generated private key to PEM file:" + pk_file.name)
    pk_file.write(private_key)
    pk_file.close()

    try:
        public_key = utility_functions.system_command_logged(
            [openssl_binary_path, "rsa", "-in", pk_file.name, "-pubout"],
            stderr_to_temp=True)
    except subprocess.CalledProcessError, e:
        logger.critical("gen_rsa_key_pair: OPENSSL could not get public key")
        logger.critical(
            "call to OpenSSL binary returned an error!: retval = " +
            str(e.returncode) + " Command = " + str(e.cmd))
        raise RuntimeError(
            "call to OpenSSL binary returned an error!: retval = " +
            str(e.returncode) + " Command = " + str(e.cmd))

    if pub_key_output_file is not None:
        logger.debug("Writing public key to file: " + pub_key_output_file)
        pubk_file = open(pub_key_output_file, "wb")
        pubk_file.write(public_key)
        pubk_file.close()

    if priv_key_output_file is None:
        logger.debug("Since private key file is temporary, deleting: " +