def generate_fec(data_model, region_id, row):
    '''
    helper function to generate fec from fuse region ID
    '''
    try:
        for region in data_model.module[0].fuse_region:
            if region.id == region_id:
                for fuse in region.fuse:
                    if fuse.n == row:
                        fec = compute_fec(
                            int(fuse.value, 16) & defines.FEC_DATA_56BIT_MASK)
                        # now that we got fec, find the fec field in this row and set it
                        for field in fuse.field:
                            if field.id == 'FEC_VALUE':
                                field.value = hex(fec)
                                logger.debug2(
                                    'generate_fec for ' + region_id +
                                    ', row ' + str(row) + ' : ' + hex(fec) +
                                    ' - ' + hex(
                                        int(fuse.value, 16)
                                        & defines.FEC_DATA_56BIT_MASK))
                                return fuse.value

        # got to this point, not found
        raise RuntimeError("USER config FEC_VALUE field not found: " +
                           region_id + ' : row ' + row)
        raise

    except:
        raise RuntimeError("Error from generate_fec(): " + region_id)
Ejemplo n.º 2
0
    def _get_config_path(self, chipset_dir):
        """Returns the config found in the chipset dir matching
        the naming conventions. If the config file is not found
        in the dir, None is returned.

        :param str chipset_dir: The directory in which to look for config path.
        :returns: config_file
        :rtype: (str)
        """
        config = None
        chipset_from_dir_name = os.path.basename(chipset_dir)

        for entry in os.listdir(chipset_dir):
            path = c_path.join(chipset_dir, entry)
            if c_path.validate_file(path) and re.match(defines.XML_NAME_REGEX, entry):
                # Extract the chipset from the file
                try:
                    chipset_from_file = ConfigParser.get_chipset_from_file(path)
                except Exception as e:
                    logger.warning('Skipping file: ' + entry + '\n'
                                   '    ' + 'Failed to load the file: ' + str(e))
                    continue

                # Check the naming conventions
                if chipset_from_file == chipset_from_dir_name:
                    config = path
                else:
                    logger.warning('Skipping file: ' + entry + '\n'
                                   '    ' + 'Chipset from file: "' + chipset_from_file + '" does not match chipset from dir name: "' + chipset_from_dir_name + '"')
            else:
                logger.debug2('Skipping file: ' + entry + '\n'
                              '    ' + 'Name does not match any of the naming convention patters')
        logger.debug2('Config path found for chipset_dir: ' + chipset_dir + '\n'
                      '    ' + 'config: ' + str(config))
        return config
Ejemplo n.º 3
0
    def _get_config_path(self, chipset_dir):
        """Returns the config found in the chipset dir matching
        the naming conventions. If the config file is not found
        in the dir, None is returned.

        :param str chipset_dir: The directory in which to look for config path.
        :returns: config_file
        :rtype: (str)
        """
        config = None
        chipset_from_dir_name = os.path.basename(chipset_dir)

        for entry in os.listdir(chipset_dir):
            path = c_path.join(chipset_dir, entry)
            if c_path.validate_file(path) and entry.endswith(defines.XML_NAME_ENDING):
                # Extract the chipset from the file
                try:
                    chipset_from_file = ConfigParser.get_chipset_from_file(path)
                except Exception as e:
                    logger.warning('Skipping file: ' + entry + '\n'
                                   '    ' + 'Failed to load the file: ' + str(e))
                    continue

                # Check the naming conventions
                if chipset_from_file == chipset_from_dir_name:
                    config = path
                else:
                    logger.warning('Skipping file: ' + entry + '\n'
                                   '    ' + 'Chipset from file: "' + chipset_from_file + '" does not match chipset from dir name: "' + chipset_from_dir_name + '"')
            else:
                logger.debug2('Skipping file: ' + entry + '\n'
                              '    ' + 'Name does not match any of the naming convention patters')
        logger.debug2('Config path found for chipset_dir: ' + chipset_dir + '\n'
                      '    ' + 'config: ' + str(config))
        return config
Ejemplo n.º 4
0
    def dump_signer_debug_data(self, image, sign_assets):
        if image.dest_image.debug_dir_signer is None:
            return
        c_path.create_debug_dir(image.dest_image.debug_dir_signer)

        sa = sign_assets
        fp = image.dest_image
        from imageinfo import DestImagePath
        assert isinstance(fp, DestImagePath)

        debug_logs = [
            (sa.root_cert, fp.debug_file_signer_root_cert),
            (sa.attestation_ca_cert, fp.debug_file_signer_attestation_ca_cert),
            (sa.attestation_cert, fp.debug_file_signer_attestation_cert),
            (sa.signature, fp.debug_file_signer_signature),
            (sa.cert_chain, fp.debug_file_signer_cert_chain)
        ]

        # Save the private attributes too
        debug_logs += [
            (sa.root_key, fp.debug_file_signer_root_key),
            (sa.attestation_ca_key, fp.debug_file_signer_attestation_ca_key),
            (sa.attestation_key, fp.debug_file_signer_attestation_key)
        ]

        for data, debug_file in debug_logs:
            try:
                store_data_to_file(debug_file, data)
            except Exception:
                logger.debug2('Failed to save debug file ' + debug_file + '\n'
                              '    ' + str(sys.exc_info()[1]))
Ejemplo n.º 5
0
    def dump_parsegen_debug_data(self, image, parsegen):
        if image.dest_image.debug_dir_parsegen is None:
            return

        so = parsegen
        fp = image.dest_image
        from imageinfo import DestImagePath
        assert isinstance(fp, DestImagePath)

        debug_logs = []
        try: debug_logs.append((so.get_data(False, False, False), fp.debug_file_parsegen_unsigned))
        except Exception: pass
        try: debug_logs.append((so.data_to_sign, fp.debug_file_parsegen_tosign))
        except Exception: pass
        try: debug_logs.append((so.cert_chain, fp.debug_file_parsegen_cert_chain))
        except Exception: pass
        try: debug_logs.append((so.data_signature, fp.debug_file_parsegen_signature))
        except Exception: pass
        try: debug_logs.append((so.get_data(True, False, False), fp.debug_file_parsegen_integrity_check))
        except Exception: pass
        try: debug_logs.append((so.get_data(True, True, False), fp.debug_file_parsegen_signed))
        except Exception: pass
        try: debug_logs.append((so.get_data(True, True, True), fp.debug_file_parsegen_encrypted))
        except Exception: pass

        for data, debug_file in debug_logs:
            try: store_data_to_file(debug_file, data)
            except Exception: logger.debug2('Failed to save debug file ' + debug_file + '\n'
                                            '    ' + str(sys.exc_info()[1]))
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_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 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 decrypt_with_private_der_key(encrypted_message, private_key):
    """ Decrypt an encrypted message with a private key
    input:
        encrypted_message = String representation of encrypted message
        private_key = String representation of private key

    output:
        message = String representing decrypted message
    """
    private_key_tempfile_name = utility_functions.store_data_to_temp_file(
        private_key)
    encrypted_message_tempfile_name = utility_functions.store_data_to_temp_file(
        encrypted_message)
    pt_tempfile_name = utility_functions.store_data_to_temp_file('')
    command_list = [
        openssl_binary_path, 'rsautl', '-decrypt', '-inkey',
        private_key_tempfile_name, '-in', encrypted_message_tempfile_name,
        '-keyform', 'DER'
    ]
    try:
        message = utility_functions.system_command_logged(command_list,
                                                          stderr_to_temp=True)
        return message
    except:
        logger.debug2(
            "decrypt_with_private_der_key: OPENSSL could not decrypt with private key"
        )
Ejemplo n.º 11
0
    def discover(self):
        """Searches for the ecies binary in the predefined packaged path.

        :returns str: Path to the ecies binary.
        """
        module_name = BINARY_NAME.title()
        filenames = bin_names(BINARY_NAME)
        filenames += alternate_bin_names(BINARY_NAME)
        module = ModuleNotFound

        for filename in filenames:
            file_path = c_path.join(packaged_bin_folder, filename)
            if c_path.validate_file(file_path):
                module = file_path
                logger.debug2(module_name + ': Found at - ' + module)
                break
        else:
            logger.debug2(module_name + ': Not Found')

        # Log if permissions are not correct
        if module != ModuleNotFound and not os.access(module, os.X_OK):
            logger.error(module_name +
                         ': Cannot execute. Missing execution permission.')

        return module
Ejemplo n.º 12
0
    def dump_parsegen_debug_data(self, image, parsegen):
        if image.dest_image.debug_dir_parsegen is None:
            return

        so = parsegen
        fp = image.dest_image
        from imageinfo import DestImagePath
        assert isinstance(fp, DestImagePath)

        debug_logs = []
        try: debug_logs.append((so.get_data(False, False, False), fp.debug_file_parsegen_unsigned))
        except Exception: pass
        try: debug_logs.append((so.data_to_sign, fp.debug_file_parsegen_tosign))
        except Exception: pass
        try: debug_logs.append((so.cert_chain, fp.debug_file_parsegen_cert_chain))
        except Exception: pass
        try: debug_logs.append((so.data_signature, fp.debug_file_parsegen_signature))
        except Exception: pass
        try: debug_logs.append((so.get_data(True, False, False), fp.debug_file_parsegen_integrity_check))
        except Exception: pass
        try: debug_logs.append((so.get_data(True, True, False), fp.debug_file_parsegen_signed))
        except Exception: pass
        try: debug_logs.append((so.get_data(True, True, True), fp.debug_file_parsegen_encrypted))
        except Exception: pass

        for data, debug_file in debug_logs:
            try: store_data_to_file(debug_file, data)
            except Exception: logger.debug2('Failed to save debug file ' + debug_file + '\n'
                                            '    ' + str(sys.exc_info()[1]))
    def discover(self):
        '''Searches for the openssl binary in:

        #. The environment using the openssl tag
        #. Prepackaged binary folder
        #. Current path
        #. System path

        :returns str: Path to the openssl binary.
        '''
        module_name = BINARY_NAME.title()
        filenames = bin_names(BINARY_NAME)
        module = ModuleNotFound

        for filename in filenames:
            # Using the environment
            if OPENSSL_ENV_DIR_TAG in os.environ:
                env_module = c_path.join(os.environ[OPENSSL_ENV_DIR_TAG],
                                         filename)
                if not c_path.validate_file(env_module):
                    logger.debug2(
                        module_name +
                        ': File from environment does not exist at - ' +
                        env_module)
                elif not self.is_supported_version(env_module):
                    logger.debug2(
                        module_name +
                        ': File from environment is not the correct version - '
                        + env_module)
                else:
                    module = env_module
                    logger.debug2(module_name +
                                  ': Found from environment at - ' +
                                  env_module)
                    break

            # Searching in prepacked dir, current dir and system paths
            else:
                folder = packaged_bin_folder
                modules_found = c_path.which(filename, paths=[folder])
                for module_found in modules_found:
                    if not self.is_supported_version(module_found):
                        continue
                    module = module_found
                    conf_file = c_path.join(folder, OPENSSL_CONF_FILE)
                    if c_path.validate_file(conf_file):
                        os.environ[OPENSSL_ENV_CONF_TAG] = conf_file
                    logger.debug2(module_name + ': Found at - ' + module)
                    break
        else:
            logger.debug2(module_name + ': Not Found')

        # Log if permissions are not correct
        if module != ModuleNotFound and not os.access(module, os.X_OK):
            logger.error(module_name +
                         ': Cannot execute. Missing execution permission.')

        return module
 def resolve_remote_server_info(self):
     host, port = QCOM_SIGNING_SERVER_HOST, QCOM_SIGNING_SERVER_PORT
     if ENV_SIGNING_SERVER_HOST_TAG in os.environ:
         logger.debug2(str(ENV_SIGNING_SERVER_HOST_TAG) + ' tag found in environment')
         host = os.environ[ENV_SIGNING_SERVER_HOST_TAG]
     if ENV_SIGNING_SERVER_PORT_TAG in os.environ:
         logger.debug2(str(ENV_SIGNING_SERVER_PORT_TAG) + ' tag found in environment')
         port = int(os.environ[ENV_SIGNING_SERVER_PORT_TAG])
     return host, port
Ejemplo n.º 15
0
    def sha_hash(self, data, sha_algo=None):
        if not data:
            raise RuntimeError('No data to hash')
        if sha_algo not in utils.hash_algos_map.keys():
            logger.warning('No SHA algo specified. Defaulting to SHA-256')

        msg = utils.hash(data, sha_algo)
        msg_bin = binascii.a2b_hex(msg)
        logger.debug2("H(code image) : " + msg)
        return msg_bin
Ejemplo n.º 16
0
    def hmac_sha(self, data, sha_algo=None):
        hash_lib_func = self.HASH_ALGO_MAP.get(self.hash_algo, None)
        if hash_lib_func is None:
            raise RuntimeError('Unknown HASH algorithm: ' + str(self.hash_algo))

        # Create hash
        msg = hash_lib_func(data).hexdigest()
        logger.debug2("H(code image) : " + msg)

        return binascii.a2b_hex(msg)
Ejemplo n.º 17
0
    def is_supported_version(cls, openssl_bin):
        '''Returns True if the version of the openssl is supported
        '''
        # Get the version info
        try:
            version = cls.get_version(openssl_bin)
        except Exception as e:
            logger.debug2(str(e))
            return False

        # Check if version is less than minimum
        return LooseVersion(version) >= LooseVersion(OPENSSL_VERSION_MIN)
Ejemplo n.º 18
0
    def is_supported_version(cls, openssl_bin, min_version=OPENSSL_VERSION_MIN):
        """Returns True if the version of the openssl is supported
        """
        # Get the version info
        try:
            openssl_version = cls.get_version(openssl_bin)
        except Exception as e:
            logger.debug2(str(e))
            return False

        # Check if version is less than minimum
        return min_version <= openssl_version
Ejemplo n.º 19
0
 def configs(self):
     """(list[obj]) List of objects of :class:`ConfigParser` generated by
     loading the config files in the config_dir.
     """
     configs = []
     for path in self.config_paths:
         logger.debug2('Loading config: ' + path)
         try:
             configs.append(ConfigParser(path))
         except Exception as e:
             logger.warning('Failed to load config: ' + path + '\n'
                            '    ' + 'Error: ' + str(e))
     return configs
Ejemplo n.º 20
0
 def configs(self):
     """(list[obj]) List of objects of :class:`ConfigParser` generated by
     loading the config files in the config_dir.
     """
     configs = []
     for path in self.config_paths:
         logger.debug2('Loading config: ' + path)
         try:
             configs.append(ConfigParser(path))
         except Exception as e:
             logger.warning('Failed to load config: ' + path + '\n'
                            '    ' + 'Error: ' + str(e))
     return configs
Ejemplo n.º 21
0
    def discover(self):
        """Searches for the M2Crypto library in the python package.

        :returns module: M2Crypto python module
        """
        module_name = MODULE_NAME
        module = ModuleNotFound
        try:
            import M2Crypto as module
            logger.debug2(module_name + ': Found at - ' + str(module))
        except ImportError as e:
            logger.debug2(module_name + ': Not Found - ' + str(e))
        return module
Ejemplo n.º 22
0
def get_field_value(data_model, region_id, field_id ):
    '''
    helper function to get the field value from data model
    '''
    for region in data_model.module[0].fuse_region:
        if region.id == region_id:
            for fuse in region.fuse:
                for field in fuse.field:
                    if field.id == field_id:
                        logger.debug2('USER config get region: '+region.id+', field: '+field.id+', value:'+field.value)
                        return field.value

    # got to this point, not found
    raise RuntimeError("USER config entry not found in OEM config: "+region_id+' : '+field_id)
Ejemplo n.º 23
0
    def dump_signer_debug_data(self, image, sign_assets, parsegen):
        if image.dest_image.debug_dir_signer is None:
            return
        c_path.create_debug_dir(image.dest_image.debug_dir_signer)

        sa = sign_assets
        fp = image.dest_image
        from imageinfo import DestImagePath
        assert isinstance(fp, DestImagePath)

        # Backup parsegen authority
        authority = parsegen.authority

        # QTI Signature and Cert Chain
        parsegen.authority = defines.AUTHORITY_QTI
        data_signature_qti = parsegen.data_signature
        cert_chain_qti = parsegen.cert_chain

        # OEM Signature and Cert Chain
        parsegen.authority = defines.AUTHORITY_OEM
        data_signature = parsegen.data_signature
        cert_chain = parsegen.cert_chain

        # Restore authority
        parsegen.authority = authority

        debug_logs = [
            (sa.root_cert, fp.debug_file_signer_root_cert),
            (sa.attestation_ca_cert, fp.debug_file_signer_attestation_ca_cert),
            (sa.attestation_cert, fp.debug_file_signer_attestation_cert),
            (data_signature, fp.debug_file_signer_signature),
            (cert_chain, fp.debug_file_signer_cert_chain),
            (data_signature_qti, fp.debug_file_signer_qti_signature),
            (cert_chain_qti, fp.debug_file_signer_qti_cert_chain)
        ]

        # Save the private attributes too
        debug_logs += [
            (sa.root_key, fp.debug_file_signer_root_key),
            (sa.attestation_ca_key, fp.debug_file_signer_attestation_ca_key),
            (sa.attestation_key, fp.debug_file_signer_attestation_key)
        ]

        for data, debug_file in debug_logs:
            try:
                store_data_to_file(debug_file, data)
            except Exception:
                logger.debug2('Failed to save debug file ' + debug_file + '\n'
                              '    ' + str(sys.exc_info()[1]))
def main(args):
    """Parses the command line arguments, performs any basic operations based on
    the parsed arguments and starts processing using the isc module.
    """
    # Print the tool's launch command
    logger.debug2('\n\n    Sectools launched as: "' + ' '.join(sys.argv) + '"\n')

    if len(args) > 1:
        feature = args[1]
        for supported_feature in FEATURES_LIST:
            if feature == supported_feature.CMD_ARG_TOOL_NAME:
                supported_feature.main(supported_feature.parse_args(sys.argv[1:]))
                break
        else:
            raise RuntimeError('Feature provided from command line: "' + feature + '" is invalid.' + '\n'
                               '       ' + 'Please choose from : ' + str([f.CMD_ARG_TOOL_NAME for f in FEATURES_LIST]))
def get_public_key_from_certificate(certificate):
    if 'BEGIN CERTIFICATE' not in certificate:
        certificate = cert_der_to_pem(certificate)



    pubkey=_extract_public_key_from_certificate(certificate)
    pubkey_file_name=utility_functions.store_data_to_temp_file(pubkey)
    command_list=[openssl_binary_path,'rsa','-pubin','-inform','PEM','-text','-noout','<',pubkey_file_name]
    logger.debug("Command_list = " + repr(command_list))

    pubkey_text = utility_functions.system_command_logged(command_list, stderr_to_temp=True)
    logger.debug2("Pubkey text: " + pubkey_text)


    os.unlink(pubkey_file_name)
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 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
Ejemplo n.º 28
0
    def is_supported_version(cls, openssl_bin):
        '''Returns True if the version of the openssl is supported
        '''
        # Get the version info
        try:
            version = cls.get_version(openssl_bin)
        except Exception as e:
            logger.debug2(str(e))
            return False

        # Check if version is less than minimum
        openssl_version_min = OPENSSL_VERSION_MIN.split('.')
        if (int(openssl_version_min[0]) > int(version[0]) or  # Major
                int(openssl_version_min[1]) > int(version[1]) or  # Minor
                int(openssl_version_min[2]) > int(version[2])):  # Patch
            return False
        return True
    def _get_config_paths(self, chipset_dir):
        """Returns a tuple of the configs found in the chipset dir matching
        the naming conventions. If any of the config files is not found
        in the dir, its value is returned as None.

        :param str chipset_dir: The directory in which to look for config paths.
        :returns: (oem_config_path, qc_config_path, ui_config_path, user_config_path)
        :rtype: (tuple(str))
        """
        oem, qc, ui, user = None, None, None, None
        chipset_from_dir_name = os.path.basename(chipset_dir)

        for entry in os.listdir(chipset_dir):
            path = c_path.join(chipset_dir, entry)
            if c_path.validate_file(path):
                # Extract the chipset from the file
                try:
                    chipset_from_file = ConfigParser.get_chipset_from_file(
                        path)
                except Exception as e:
                    logger.debug2('Skipping file: ' + entry + '\n'
                                  '    ' + 'Failed to load the file: ' +
                                  str(e))
                    continue

                # Check the naming conventions
                if chipset_from_file == chipset_from_dir_name:
                    if entry.endswith(defines.XML_NAME_ENDING_OEM):
                        oem = path
                    elif entry.endswith(defines.XML_NAME_ENDING_QC):
                        qc = path
                    elif entry.endswith(defines.XML_NAME_ENDING_UI):
                        ui = path
                    elif entry.endswith(defines.XML_NAME_ENDING_USER):
                        user = path
                    else:
                        logger.debug2(
                            'Skipping file: ' + entry + '\n'
                            '    ' +
                            'Name does not match any of the naming convention patters'
                        )
                else:
                    logger.debug2('Skipping file: ' + entry + '\n'
                                  '    ' + 'Chipset from file: "' +
                                  chipset_from_file +
                                  '" does not match chipset from dir name: "' +
                                  chipset_from_dir_name + '"')

        logger.debug2('Config paths found for chipset_dir: ' + chipset_dir +
                      '\n'
                      '    ' + 'oem: ' + str(oem) + '\n'
                      '    ' + 'qc: ' + str(qc) + '\n'
                      '    ' + 'ui: ' + str(ui) + '\n'
                      '    ' + 'user: ' + str(user))
        return oem, qc, ui, user
Ejemplo n.º 30
0
def set_field_value(data_model, region_id, field_id, value ):
    '''
    helper function to find the field and set its value
    '''
    if not isinstance(value, str):
        value = hex(value).rstrip('L')

    for region in data_model.module[0].fuse_region:
        if region.id == region_id:
            for fuse in region.fuse:
                for field in fuse.field:
                    if field.id == field_id:
                        field.value = value
                        logger.debug2('USER config set region: '+region.id+', field: '+field.id+', value:'+field.value)
                        return True, field.value

    # got to this point, not found
    raise RuntimeError("USER config entry not found in OEM config: "+region_id+' : '+field_id)
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_private_der_key(encrypted_message, private_key):
    """ Decrypt an encrypted message with a private key
    input:
        encrypted_message = String representation of encrypted message
        private_key = String representation of private key

    output:
        message = String representing decrypted message
    """
    private_key_tempfile_name =utility_functions.store_data_to_temp_file(private_key)
    encrypted_message_tempfile_name = utility_functions.store_data_to_temp_file(encrypted_message)
    pt_tempfile_name=utility_functions.store_data_to_temp_file('')
    command_list=[openssl_binary_path, 'rsautl', '-decrypt', '-inkey', private_key_tempfile_name, '-in', encrypted_message_tempfile_name, '-keyform','DER']
    try:
        message = utility_functions.system_command_logged(command_list, stderr_to_temp=True)
        return message
    except:
        logger.debug2("decrypt_with_private_der_key: OPENSSL could not decrypt with private 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
Ejemplo n.º 34
0
    def sha_hash(self, data, sha_algo=None):
        if not data:
            raise RuntimeError('No data to hash')

        if sha_algo == 'sha1':
            hashlib_calc = hashlib.sha1
        elif sha_algo == 'sha256':
            hashlib_calc = hashlib.sha256
        elif sha_algo == 'sha384':
            hashlib_calc = hashlib.sha384
        else:
            logger.warning('No SHA algo specified. Defaulting to SHA-256')
            hashlib_calc = hashlib.sha256

        msg = hashlib_calc(data).hexdigest()
        msg_bin = binascii.a2b_hex(msg)
        logger.debug2("H(code image) : " + msg)

        return msg_bin
Ejemplo n.º 35
0
    def discover(self):
        """Searches for the crypto cbc binary in the predefined packaged path.

        :returns str: Path to the crypto cbc binary.
        """
        module_name = BINARY_NAME.title()
        filenames = bin_names(BINARY_NAME)
        module = ModuleNotFound

        for filename in filenames:
            file_path = c_path.join(packaged_bin_folder, filename)
            if c_path.validate_file(file_path):
                module = file_path
                logger.debug2(module_name + ': Found at - ' + module)
                break
        else:
            logger.debug2(module_name + ': Not Found')

        return module
def create_certificate(certificate_params, certificate_key_pair, CACertificate,
                       CA_key_pair, days, configfile, serial_num,
                       extfile_name):
    """ Generate a certificate.
    input:

        certificate_params ={
                              'C'              : "US",
                              'ST'             : "California",
                              'L'              : "San Diego",
                              'O'              : "ASIC",
                              'CN'             : "Qualcomm",
                              'OU'             : [r"General Use Test Key (for testing only)", r"CDMA Technologies"]
                          }
        Dictionary of parameters to put in the certificate. The parameters above are an example
        If the same parameter has multiple values as 'OU' above, create a list of values

        CACertificate: String representation of CA certificate used to sign the cert

        certificate_key_pair = None | key_pair = {"public_key": [Generated public key],
                                                  "private_key": [Generated private key] }

        Dictionary holding the values of public and private keys. If this is None, a key
        is generated.

        days = validity period of certificate in days

        configfile = configfile used by openssl

    output:
        certificate: String representation of PEM certificate.
        certificate_key_pair : {"public_key": certificate public key],
                                "private_key": certificate private key] }
    """

    csr, csr_key_pair = _create_sigining_request(certificate_params,
                                                 certificate_key_pair, days,
                                                 configfile)
    logger.debug2(csr + repr(csr_key_pair))
    certificate, ca_key_pair = _sign_csr_with_CA_certificate(
        csr, CACertificate, CA_key_pair, days, serial_num, extfile_name)

    return (certificate, csr_key_pair)
Ejemplo n.º 37
0
    def dump_signer_debug_data(self, image, sign_assets):
        if image.dest_image.debug_dir_signer is None:
            return

        sa = sign_assets
        fp = image.dest_image
        from imageinfo import DestImagePath
        assert isinstance(fp, DestImagePath)

        debug_logs = [(sa.root_cert, fp.debug_file_signer_root_cert),
                      (sa.attestation_ca_cert, fp.debug_file_signer_attestation_ca_cert),
                      (sa.attestation_cert, fp.debug_file_signer_attestation_cert),
                      (sa.attestation_key, fp.debug_file_signer_attestation_key),
                      (sa.signature, fp.debug_file_signer_signature),
                      (sa.cert_chain, fp.debug_file_signer_cert_chain)]

        for data, debug_file in debug_logs:
            try: store_data_to_file(debug_file, data)
            except Exception: logger.debug2('Failed to save debug file ' + debug_file + '\n'
                                            '    ' + str(sys.exc_info()[1]))
Ejemplo n.º 38
0
    def config_paths(self):
        """(list[tuple(str)]) List of the config paths found in the workspace
        conforming to the naming structure.
        """
        config_dir = self.config_dir
        config_paths = []

        logger.debug('Searching config path sets in dir: ' + config_dir)
        for entry in os.listdir(config_dir):
            path = c_path.join(config_dir, entry)
            if c_path.validate_dir(path):
                config = self._get_config_path(path)
                if config:
                    config_paths.append(config)
                else:
                    logger.debug2('Skipping dir: ' + entry + '\n'
                                  '    ' + 'Does not contain any configs')
            else:
                logger.debug2('Skipping file in first level: ' + entry)
        logger.debug('Config paths found from the config dir: ' + str(config_paths))
        return config_paths
Ejemplo n.º 39
0
    def configs(self):
        """(list[obj]) List of objects of :class:`ConfigParser` generated by
        loading the config files in the config_dir.
        """
        configs = []
        for oem, qc, ui, user in self.config_paths:
            logger.debug2('Loading configs: ' + '\n'
                          '    ' + 'oem: ' + str(oem) + '\n'
                          '    ' + 'qc: ' + str(qc) + '\n'
                          '    ' + 'ui: ' + str(ui) + '\n'
                          '    ' + 'user: '******'Failed to load configs.'
                               '    ' + 'Error: ' + str(e))
        return configs
Ejemplo n.º 40
0
    def config_paths(self):
        """(list[tuple(str)]) List of the config paths found in the workspace
        conforming to the naming structure.
        """
        config_dir = self.config_dir
        config_paths = []

        logger.debug('Searching config path sets in dir: ' + config_dir)
        for entry in os.listdir(config_dir):
            path = c_path.join(config_dir, entry)
            if c_path.validate_dir(path):
                oem, qc, ui, user = self._get_config_paths(path)
                if oem or qc or ui or user:
                    config_paths.append((oem, qc, ui, user))
                else:
                    logger.debug2('Skipping dir: ' + entry + '\n'
                                  '    ' + 'Does not contain any configs')
            else:
                logger.debug2('Skipping file in first level: ' + entry)
        logger.debug('Config paths found from the config dir: ' + str(config_paths))
        return config_paths
Ejemplo n.º 41
0
    def qcom_hmac(self, data, hmac_params):
        if data == None or hmac_params == None:
            raise RuntimeError('Input parameters to the HMAC function are incorrect')
        else:
            msm_id = hmac_params.MSM_ID
            sw_id = hmac_params.SW_ID
            ipad = 0x3636363636363636
            opad = 0x5C5C5C5C5C5C5C5C
            logger.debug("MSM_ID key : " + repr(msm_id))
            logger.debug("SW_ID key : " + repr(sw_id))
            logger.debug("ipad : " + repr(ipad))
            logger.debug("opad : " + repr(opad))
            Si = sw_id ^ ipad
            Si = binascii.unhexlify(format(Si,'x'))
            So = msm_id ^ opad
            So = binascii.unhexlify(format(So,'x'))
            msg_step1 = hashlib.sha256(data).hexdigest()
            msg_step1_bin = binascii.a2b_hex(msg_step1)
            logger.debug2("H(code image) : " + msg_step1)
            msg_step2 = hashlib.sha256(Si + msg_step1_bin).hexdigest()
            msg_step2_bin = binascii.a2b_hex(msg_step2)
            logger.debug2("H[(SWID^ipad) || H(code image)] : " + msg_step2)
            msg_step3 = hashlib.sha256(So + msg_step2_bin).hexdigest()
            msg_step3_bin = binascii.a2b_hex(msg_step3)
            logger.debug2("H[(MSMID^opad) || H[(SWID^ipad) || H(code image)]] : " + msg_step3)

            hmac = msg_step3_bin
            return hmac
def create_certificate(certificate_params, certificate_key_pair, CACertificate, CA_key_pair, days, configfile, serial_num, extfile_name):
    """ Generate a certificate.
    input:

        certificate_params ={
                              'C'              : "US",
                              'ST'             : "California",
                              'L'              : "San Diego",
                              'O'              : "ASIC",
                              'CN'             : "Qualcomm",
                              'OU'             : [r"General Use Test Key (for testing only)", r"CDMA Technologies"]
                          }
        Dictionary of parameters to put in the certificate. The parameters above are an example
        If the same parameter has multiple values as 'OU' above, create a list of values

        CACertificate: String representation of CA certificate used to sign the cert

        certificate_key_pair = None | key_pair = {"public_key": [Generated public key],
                                                  "private_key": [Generated private key] }

        Dictionary holding the values of public and private keys. If this is None, a key
        is generated.

        days = validity period of certificate in days

        configfile = configfile used by openssl

    output:
        certificate: String representation of PEM certificate.
        certificate_key_pair : {"public_key": certificate public key],
                                "private_key": certificate private key] }
    """

    csr,csr_key_pair = _create_sigining_request(certificate_params, certificate_key_pair, days, configfile)
    logger.debug2(csr + repr(csr_key_pair))
    certificate,ca_key_pair = _sign_csr_with_CA_certificate(csr, CACertificate, CA_key_pair, days, serial_num, extfile_name)

    return (certificate, csr_key_pair)