def _set_install_locations_for_sec_image_policies(install_policies,
                                                   sec_image_policies,
                                                   install_base_dir):
     logger.debug(
         "Getting the install policy install locations for the enabled secimage policies..."
     )
     # loop though sec image policies for selected build policy
     for sec_image_policy in sec_image_policies:
         # initialize the sec_image_policy's install location list if the list doesn't exist yet
         if not hasattr(sec_image_policy, 'install_locations'):
             sec_image_policy.install_locations = []
         # loop through install policies for selected build policy
         for install_policy in install_policies:
             # loop through directories of each install policy
             for directory in install_policy.directory:
                 # if the directory's sec_image_policy matches the current sec_image_policy
                 # then add the directory's path value to the sec_image_policy's list of install locations
                 if directory.sec_image_policy == sec_image_policy.id:
                     # add the new install location to the sec_image_policy's list of locations substituting in the value for install_base_dir
                     if directory.value not in sec_image_policy.install_locations:
                         directory_path = c_path.normalize(
                             directory.value[:].replace(
                                 "${sectools_install_base_dir}",
                                 install_base_dir))
                         sec_image_policy.install_locations.append(
                             directory_path)
                         logger.debug(
                             "Added {0} to the install locations for secimage policy {1}"
                             .format(
                                 c_path.normalize(
                                     directory.value[:].replace(
                                         "${sectools_install_base_dir}",
                                         install_base_dir)),
                                 sec_image_policy.id))
Exemplo n.º 2
0
    def read(self, xml_path, config_xml_path=None):

        import auto_gen_fm_config
        import auto_gen_fmconf_config

        try:
            self.path = c_path.normalize(xml_path)
            self.config_path = c_path.normalize(config_xml_path)

            # load the FM config data
            if (self.config_path is not None):
                c_config.CoreConfig.__init__(self.core_fmconfig,
                                             auto_gen_fmconf_config,
                                             self.config_path)
                self.filtermethod = self.core_fmconfig.root.filterType.method
            else:
                # TODO: change default to None or error out, check with Maria
                self.filtermethod = 'all'

            # populate the FM data model
            self._populate(self.path, auto_gen_fm_config, self.core_config)

        except Exception:
            logger.debug('fuseMasterData: Exception raised')
            raise
Exemplo n.º 3
0
def validate_args(arguments, err_strings, init_logging):

    # configure logger to log to filesystem
    if init_logging:
        if arguments.target_base_dir:
            folder = c_path.normalize(arguments.target_base_dir)
            try:
                c_path.create_dir(folder)
            except Exception as e:
                raise RuntimeError('Unable to create directory for logging: ' +
                                   folder + '\n' + 'Error: ' + str(e))
            if arguments.sign_id:
                logging_file_name = SECTOOLS_BUILDER_TOOL_NAME.replace(
                    " ", "_") + "_" + arguments.sign_id
            else:
                logging_file_name = SECTOOLS_BUILDER_TOOL_NAME.replace(
                    " ", "_")
            logger.enable_file_logging(logging_file_name,
                                       num_logs=1,
                                       log_dir=folder)
        else:
            raise RuntimeError(err_strings[0])

    err = []
    # validate that the required fields were provided
    if not arguments.target_base_dir:
        err.append(err_strings[0])
    if not arguments.source:
        err.append(err_strings[1])
    if not arguments.sign_id:
        err.append(err_strings[2])
    if arguments.jtag_id and arguments.soc_hw_version:
        err.append(err_strings[3])
    if hasattr(arguments, "config_type") and arguments.config_type is not None:
        logger.info("Sectools Builder config was provided using new api")
        config = c_path.normalize(arguments.config_type)
        if config not in CONFIGS:
            err.append(err_strings[8])
    else:
        logger.info(
            "Sectools Builder config was provided using deprecated api")
        config = c_path.normalize(arguments.config)
        if config not in CONFIGS:
            logger.warning(
                "Sectools Builder received custom Secimage config file")
    sectools_builder_core.validate_file(config, err_strings[4], err)
    validate_bool(arguments.qti_sign, err_strings[5], err)
    validate_bool(arguments.relocatable, err_strings[6], err)
    if hasattr(
            arguments, "target_image_type_filter"
    ) and arguments.target_image_type_filter is not None and arguments.target_image_type_filter not in [
            sectools_builder_core.INTEGRITY, sectools_builder_core.SIGN,
            sectools_builder_core.ENCRYPT,
            sectools_builder_core.SIGN_AND_ENCRYPT
    ]:
        err.append(err_strings[7])
    return error_list_to_str(err)
Exemplo n.º 4
0
    def __init__(self,
                 image_path,
                 img_config_parser,
                 parsegen_config,
                 authority,
                 sign_id=None,
                 gen_multi_image=False,
                 multi_image_path=None):
        from sectools.features.isc.parsegen.config.parser import ParsegenCfgParser
        assert isinstance(image_path, str)
        assert isinstance(img_config_parser, ConfigParser)
        assert isinstance(parsegen_config, ParsegenCfgParser)
        if sign_id is not None: assert isinstance(sign_id, str)

        # Initialize the BaseStager
        BaseStager.__init__(self, authority)

        # Validate that the image path exists
        image_path = c_path.normalize(image_path)
        if not c_path.validate_file(image_path):
            raise RuntimeError('No read access to the image path: ' +
                               image_path)
        # Put the image info object into the list
        imageinfo = self._create_imageinfo(img_config_parser, parsegen_config,
                                           sign_id, image_path, False)
        self._image_info_list.append(imageinfo)

        # Validate that the Multi-Image Sign & Integrity image path exists
        if multi_image_path is not None:
            multi_image_path = c_path.normalize(multi_image_path)
            if not c_path.validate_file(multi_image_path):
                raise RuntimeError('No read access to the ' +
                                   multi_image_string() + ' image path: ' +
                                   multi_image_path)
            # Set sign id to Multi-Image image's sign id
            sign_id = MULTI_IMAGE_SIGN_ID[authority]
            # Set the Multi-Image Signing & Integrity image's imageinfo
            multi_image_imageinfo = self._create_imageinfo(
                img_config_parser, parsegen_config, sign_id, multi_image_path,
                False)
            self._multi_image_imageinfo_dict[
                multi_image_imageinfo.chipset] = multi_image_imageinfo
        # Create image info object for to-be-created Multi-Image Signing and Integrity image
        elif gen_multi_image:
            # Set sign id to Multi-Image Sign & Integrity image's sign id
            sign_id = MULTI_IMAGE_SIGN_ID[authority]
            # Set the Multi-Image Signing & Integrity image's imageinfo
            multi_image_imageinfo = self._create_imageinfo(
                img_config_parser, parsegen_config, sign_id, None,
                gen_multi_image)
            self._multi_image_imageinfo_dict[
                multi_image_imageinfo.chipset] = multi_image_imageinfo
Exemplo n.º 5
0
    def generateMetaBuild(self, timer=1200, interval=5):
        """ generate new meta build with given image build
        :param str meta_build_path: meta build directory, require write access
        :param str image_build_path: image build directory, require read access
        """
        if self.run:
            self.retcode = ''
            # meta build path validation
            meta_path_val = c_path.normalize(self.meta_build_path)
            if not c_path.validate_dir_write(meta_path_val):
                raise RuntimeError('Cannot write at: ' + meta_path_val)

            # image build path validation
            image_path_val = c_path.normalize(self.image_build_path)
            if not c_path.validate_dir(image_path_val):
                raise RuntimeError('Cannot access: ' + image_path_val)

            """TODO: Don't know how to check if TZ build has changed
                     and if re-generate NON-HLOS.bin is needed.
                     For now, always re-generate meta build.
            """
            # check if meta build has been generated with the required image build already
            meta_info = self.getMetainfo(self.meta_build_path)
            path = meta_info.get_build_path(BUILD)
            tz_path_in_meta_build_val = c_path.normalize(path)
            generation_complete_flag = c_path.join(meta_path_val, GENERATION_COMPLETE_STR)
            """
            if tz_path_in_meta_build_val == image_path_val and c_path.validate_file(generation_complete_flag):
                self.logging_state_info('meta build with required image build is available at: ' + meta_path_val)
                self.logging_state_info('meta build generation is skipped')
                logger.debug('meta build path: ' + meta_path_val)
                logger.debug('image build path: ' + image_path_val)
            else:
            """
            cmd = ['python', REGENERATE_CMD_TZ + image_path_val]
            cwd = c_path.join(meta_path_val, BUILD_SCRIPTS_DIR)
            self.logging_state_info(getCurrentTime() + ' start meta build generation, please wait and do not interrupt ...')
            self.logging_state_info('Set current working directory: ' + cwd)
            self.logging_state_info('Generate Meta build command: ' + " ".join(cmd))
            self.log = c_path.join(meta_path_val, REGENERATE_BUID_LOG)
            self.run = False
            self.retcode = self.execute(cmd, self.log, cwd, timer, interval)
            self.logging_state_info(getCurrentTime() +' meta build generation return code: ' + str(self.retcode))
            self.logging_state_info('meta build generation log can be found at: ' + self.log)
            if self.retcode == 0:
                open(generation_complete_flag,'a').close()
                self.run = True
            self.logging_state_info(SECTION_BREAK)
        else:
            self.logging_state_info('skip meta build regeneration')
Exemplo n.º 6
0
 def dbgp_config(self, config_path):
     config_path = c_path.normalize(config_path)
     if not c_path.validate_file(config_path):
         raise RuntimeError(
             'debugpolicy config is inaccessible at given path: ' +
             str(config_path))
     self._config_parser = ConfigParser(config_path)
    def __init__(self, image_path, img_config_parser, sign_id=None):
        assert isinstance(image_path, str)
        assert isinstance(img_config_parser, ConfigParser)
        if sign_id is not None: assert isinstance(sign_id, str)

        # Initialize the BaseStager
        BaseStager.__init__(self)

        # Validate that the image path exists
        image_path = c_path.normalize(image_path)
        if not c_path.validate_file(image_path):
            raise RuntimeError('No read access to the image path: ' + image_path)

        # Validate the sign_id
        sign_id = self._get_sign_id(img_config_parser,
                                    os.path.basename(image_path),
                                    sign_id)

        # Get the config block for the sign id
        img_config_block = img_config_parser.get_config_for_sign_id(sign_id)

        # Create the one image info object
        image_info = ImageInfo(image_path, sign_id, img_config_block,
                               img_config_parser)
        image_info.dest_image.image_name = image_info.src_image.image_name

        # Check if the dest image name should be overriden
        if img_config_block.output_file_name is not None:
            image_info.dest_image.image_name = img_config_block.output_file_name

        # Put the image info object into the list
        self._image_info_list.append(image_info)
def validate_dir(path, var_name, error_list):
    if path:
        path = c_path.normalize(path)
        try:
            c_path.create_dir(path)
        except RuntimeError:
            error_list.append("Provided {0} \"{1}\" is not a valid path or does not have read/write access.".format(var_name, path))
def validate_file(path, var_name, error_list):
    if path:
        path = c_path.normalize(path)
        if not c_path.validate_file(path):
            error_list.append(
                "Provided {0} \"{1}\" is not a valid file or does not have read access."
                .format(var_name, path))
    def __init__(self, image_path, img_config_parser, sign_id=None):
        assert isinstance(image_path, str)
        assert isinstance(img_config_parser, ConfigParser)
        if sign_id is not None: assert isinstance(sign_id, str)

        # Initialize the BaseStager
        BaseStager.__init__(self)

        # Validate that the image path exists
        image_path = c_path.normalize(image_path)
        if not c_path.validate_file(image_path):
            raise RuntimeError('No read access to the image path: ' +
                               image_path)

        # Validate the sign_id
        sign_id = self._get_sign_id(img_config_parser,
                                    os.path.basename(image_path), sign_id)

        # Get the config block for the sign id
        img_config_block = img_config_parser.get_config_for_sign_id(sign_id)

        # Create the one image info object
        image_info = ImageInfo(image_path, sign_id, img_config_block,
                               img_config_parser)
        image_info.dest_image.image_name = image_info.src_image.image_name

        # Check if the dest image name should be overriden
        if img_config_block.output_file_name is not None:
            image_info.dest_image.image_name = img_config_block.output_file_name

        # Put the image info object into the list
        self._image_info_list.append(image_info)
Exemplo n.º 11
0
 def secimage_config(self, config_path):
     config_path = c_path.normalize(config_path)
     if not c_path.validate_file(config_path):
         raise RuntimeError(
             'Secimage config is inaccessible at given path: ' +
             str(config_path))
     self._secimage_config = config_path
 def secdat(self, secdat_path):
     if secdat_path:
         secdat_path = c_path.normalize(secdat_path)
         if not c_path.validate_file(secdat_path):
             raise RuntimeError('Cannot access the secdat file: ' + secdat_path)
     self._secdat = secdat_path
     logger.info('Secdat path is set to: ' + str(secdat_path))
Exemplo n.º 13
0
    def __init__(self,
                 image_path,
                 img_config_parser,
                 parsegen_config,
                 authority,
                 sign_id=None,
                 crypto_params={},
                 imageinfo_class=None):

        assert isinstance(image_path, str)
        assert isinstance(img_config_parser, ConfigParser)
        assert isinstance(parsegen_config, ParsegenCfgParser)
        if sign_id is not None: assert isinstance(sign_id, str)

        # Initialize the BaseStager
        super(ImagePathsStagerIot, self).__init__(authority)

        # Validate that the image path exists
        image_path = c_path.normalize(image_path)
        if not c_path.validate_file(image_path):
            raise RuntimeError('No read access to the image path: ' +
                               image_path)
        # Put the image info object into the list
        imageinfo = self._create_imageinfo(img_config_parser,
                                           parsegen_config,
                                           sign_id,
                                           image_path,
                                           crypto_params=crypto_params,
                                           imageinfo_class=imageinfo_class)
        self._image_info_list.append(imageinfo)
Exemplo n.º 14
0
    def _execute_install(self, policy):
        logger.debug("\nInstalling Sectools's output file...")
        if self.input.sectools_install_base_dir:
            path, filename = os.path.split(self.input.source)
            chipset = ConfigParser(
                self.input.config).root.metadata.get_chipset()
            src = c_path.normalize(
                c_path.join(self.input.target_base_dir, policy.id, chipset,
                            self.input.sign_id, filename))
            for install_location in policy.install_locations:
                if self.input.install_file_name:
                    dest = c_path.join(install_location,
                                       self.input.install_file_name)
                else:
                    dest = c_path.join(install_location, filename)

                # Attempt installation 3 times before failing
                installation_successful = False
                for i in range(3):
                    try:
                        c_path.create_dir(install_location)
                        copy_successful, error = c_path.copyFile(
                            src, dest, None, True)
                        if not copy_successful:
                            continue
                    except:
                        # Installation failed so retry installation
                        continue
                    installation_successful = True
                    logger.info("Installed \"{0}\" to \"{1}\"".format(
                        src, dest))
                    break
                if not installation_successful:
                    error_message = "Failed to install \"{0}\" to \"{1}\"".format(
                        src, dest)
                    logger.error(error_message)
                    raise RuntimeError(error_message)

                # pilsplit sectools's output file
                pilsplit_subdirectory = ""
                if install_location != self.input.sectools_install_base_dir:
                    pilsplit_subdirectory = install_location.replace(
                        os.path.join(self.input.sectools_install_base_dir, "",
                                     ""), "")
                pilsplit_prefix = self.input.install_file_name.split(
                    "."
                )[0] if self.input.install_file_name else filename.split(
                    ".")[0]
                self._execute_pilsplit(dest, pilsplit_prefix,
                                       pilsplit_subdirectory)
        else:
            logger.info(
                "Installation was skipped because a value for sectools_install_base_dir was not provided"
            )
            if self.input.pilsplitter_target_base_dir:
                logger.info(
                    "Pilsplitting was skipped because a value for sectools_install_base_dir was not provided"
                )
Exemplo n.º 15
0
class HardwareIdentityKeystore(BaseKeystore):
    KEYSTORE_TYPE = "PKCS11"
    PKCS11_CFG_TEMPLATE = c_path.normalize(
        os.path.join(defines.CASS_CLIENT_REFAPP_INPUT_DIR,
                     'pkcs11.cfg.template'))
    MESG_PROMPT_PASSWORD = '******'
    MESG_TOKEN_DRIVER_INVALID = "Token driver path {0} is invalid! Please install Safenet driver."

    def __init__(self, user_identity_config):
        self.file = None
        self._user_identity = user_identity_config
        BaseKeystore.__init__(self, user_identity_config.token_password)
        self.token_driver_home = user_identity_config.token_driver_home
        self.file = self._generate_pkcs11_cfg(self.token_driver_home)

    @property
    def file(self):
        return self._file

    @file.setter
    def file(self, value):
        self._file = value

    @property
    def type(self):
        return self.KEYSTORE_TYPE

    @property
    def token_driver_home(self):
        return self._token_driver_home

    @token_driver_home.setter
    def token_driver_home(self, token_driver_home_config):
        if sys.platform.startswith('linux'):
            self._token_driver_home = token_driver_home_config.linux
        else:
            self._token_driver_home = token_driver_home_config.windows

        if c_path.validate_file(self._token_driver_home) is False:
            raise ConfigError(
                self.MESG_TOKEN_DRIVER_INVALID.format(self._token_driver_home))

    def _generate_pkcs11_cfg(self, token_driver_home):
        pkcs11_cfg_template_data = c_misc.load_data_from_file(
            self.PKCS11_CFG_TEMPLATE)
        pkcs11_cfg_data = signerutils.macro_replace(pkcs11_cfg_template_data,
                                                    "token_driver_home",
                                                    token_driver_home,
                                                    isMandatory=True)
        return utility_functions.store_data_to_temp_file(pkcs11_cfg_data)

    def release(self):
        if self.file and os.path.isfile(self.file):
            logger.debug("Deleting temporary file: " + self.file)
            os.unlink(self.file)

    def __del__(self):
        self.release()
Exemplo n.º 16
0
    def __init__(self, meta_build_path, config_dir_obj, sign_id_list=[]):
        assert isinstance(meta_build_path, str)
        assert isinstance(config_dir_obj, ConfigDir)

        # Initialize the BaseStager
        BaseStager.__init__(self)

        self.config_dir_obj = config_dir_obj

        # Create internal attributes
        self._meta_build_path = meta_build_path

        # Validate that the meta_build path exists
        meta_build_path = c_path.normalize(meta_build_path)
        if not c_path.validate_dir(meta_build_path):
            raise RuntimeError('No read access to the meta build path: ' + meta_build_path)

        # Get the meta lib module from the metabuild
        meta_info = self.get_meta_info(meta_build_path)

        # Create the image info list based on the meta data
        for sign_id, chipset, image_src_path, image_dest_path in self.get_image_info_from_meta(meta_info):
            # Filer on the sign id
            if sign_id_list:
                if sign_id not in sign_id_list:
                    continue

            try:
                img_config_parser = self.get_image_config_parser(chipset)

                # Validate the sign_id
                sign_id = self._get_sign_id(img_config_parser,
                                            os.path.basename(image_src_path.image_path),
                                            sign_id)

                # Get the config block for the sign id
                img_config_block = img_config_parser.get_config_for_sign_id(sign_id)

                # Create the one image info object
                image_info = ImageInfo('', sign_id, img_config_block,
                                       img_config_parser)

                # Set the src path
                image_info.src_image = image_src_path
                image_info.image_under_operation = image_info.src_image.image_path

                # Set the dest path
                image_info.dest_image = image_dest_path

                # Put the image info object into the list
                self._image_info_list.append(image_info)

            except Exception as e:
                logger.error(str(e))

        if not self._image_info_list:
            raise RuntimeError('No images found from the meta build.')
Exemplo n.º 17
0
 def set_input_file(self, i_file):
     """(str) Path to the input debugpolicy elf file.
     """
     i_file = c_path.normalize(i_file)
     if not c_path.validate_file(i_file):
         raise RuntimeError(
             'debugpolicy elf file is inaccessible at given path: ' +
             str(i_file))
     self._input_files_base = os.path.dirname(i_file)
     self._input_files_list = [i_file]
    def mini_build_path(self, mini_build_path):
        assert isinstance(mini_build_path, str)
        mini_build_path = c_path.normalize(mini_build_path)
        if not c_path.validate_dir_write(mini_build_path):
            raise RuntimeError('No write access to minimized build directory: ' + mini_build_path)

        # Update the output dir of each image in image_info_list
        for image_info in self.image_info_list:
            image_info.dest_image.image_dir_base = mini_build_path
        self._mini_build_path = mini_build_path
    def set_config_paths(self, oem_config_path=None, qc_config_path=None,
                         ui_config_path=None, user_config_path=None):
        """Sets the config paths to the paths provided.

        :param str oem_config_path: Path to the OEM config file
        :param str qc_config_path: Path to the QC config file
        :param str ui_config_path: Path to the UI config file
        """
        # Normalize all paths
        oem_config_path = c_path.normalize(oem_config_path) if oem_config_path is not None else None
        qc_config_path = c_path.normalize(qc_config_path) if qc_config_path is not None else None
        ui_config_path = c_path.normalize(ui_config_path) if ui_config_path is not None else None
        user_config_path = c_path.normalize(user_config_path) if user_config_path is not None else None

        # Set the paths on the config_parser
        self._config_parser.read(oem_config_path,
                                 qc_config_path,
                                 ui_config_path,
                                 user_config_path)
Exemplo n.º 20
0
 def directory_to_string(complex_directory_object,
                         install_base_dir):
     directory_list = []
     for directory in complex_directory_object:
         directory_list.append(
             "[" + directory.sec_image_policy + ": " +
             c_path.normalize(directory.value[:].replace(
                 "${sectools_install_base_dir}",
                 install_base_dir)) + "]")
     return ", ".join(directory_list)
Exemplo n.º 21
0
 def output_dir(self, output_dir):
     output_dir = c_path.normalize(output_dir)
     try:
         c_path.create_dir(output_dir)
     except Exception as e:
         raise RuntimeError('Cannot write in the given output_dir: ' +
                            output_dir + '\n'
                            '    ' + 'Error: ' + str(e))
     self._output_dir = output_dir
     logger.info('Output dir is set to: ' + output_dir)
def get_keydata_from_file(filepath):
    import os
    import binascii

    filepath = c_path.normalize(os.path.join(DIR_PATH, filepath))

    with open(filepath, 'rb') as f:
        f.seek(0)
        file_data = binascii.hexlify(f.read())
        f.close()
        return file_data
    def output_dir(self, output_dir):
        assert isinstance(output_dir, str)
        output_dir = c_path.normalize(output_dir)
        if not c_path.validate_dir_write(output_dir):
            raise RuntimeError('No write access to output directory: ' + output_dir)

        # Update the output dir of each image in image_info_list
        for image_info in self.image_info_list:
            image_info.dest_image.image_dir_base = output_dir
            image_info.dest_image.image_dir_ext = (image_info.chipset + '/' +
                                                   image_info.sign_id)
        self._output_dir = output_dir
Exemplo n.º 24
0
def log_to_file(folder):
    """Configures the logger to log to filesystem

    :param str folder: Directory to generate the logs in.
    """
    folder = c_path.normalize(folder)
    try:
        c_path.create_dir(folder)
    except Exception as e:
        raise RuntimeError('Unable to create directory for logging: ' + folder + '\n'
                           '    ' + 'Error: ' + str(e))
    logger.enable_file_logging(FUSEBLOWER_TOOL_NAME, num_logs=1, log_dir=folder)
Exemplo n.º 25
0
    def output_dir(self, output_dir):
        assert isinstance(output_dir, str)
        output_dir = c_path.normalize(output_dir)
        if not c_path.validate_dir_write(output_dir):
            raise RuntimeError('No write access to output directory: ' +
                               output_dir)

        # Update the output dir of each image in image_info_list
        for image_info in self.image_info_list:
            self.update_dest_image(image_info, output_dir)

        self._output_dir = output_dir
    def _get_cmds(self):
        if os.path.exists(self.output_dir) is None:
            os.makedirs(self.output_dir)

        signing_package_file = c_path.normalize(self.signing_package_file_name)
        cmds = ["java"]
        if self.cass_signer_attributes.server:
            cmds.append("-Dcass_server.host={0}".format(
                self.cass_signer_attributes.server.host))
            cmds.append("-Dcass_server.sslport={0}".format(
                self.cass_signer_attributes.server.port))
            cmds.append("-Dtrust_anchor.file={0}".format(
                self.trust_keystore.file))
            cmds.append("-Dtrust_anchor.password={0}".format(
                self.trust_keystore.password))
            cmds.append("-Dtrust_anchor.keystoretype={0}".format(
                self.trust_keystore.type))
            cmds.append("-Dcn_verify.mode={0}".format(
                self.host_validation_mode))
        cmds.append("-Dsig_authority.file={0}".format(
            self.identity_keystore.file))
        cmds.append("-Dsig_authority.password={0}".format(
            self.identity_keystore.password))
        cmds.append("-Dsig_authority.keystoretype={0}".format(
            self.identity_keystore.type))
        if self.identity_keystore.token_driver_home:
            cmds.append("-Detoken_driver_home={0}".format(
                self.identity_keystore.token_driver_home))
        cmds.append("-Doutput.location={0}".format(self.output_dir))
        cmds.append("-Dschema.location={0}".format(
            c_path.normalize(self.SCHEMA_XSD_FILE_PATH)))

        cmds.extend(['-jar', self.CLIENT_REFAPP_JAR, signing_package_file])

        # only enable -v if debug is enabled
        if logger.verbosity < logger.DEBUG:
            cmds.append('-v')

        self.cmds = cmds
Exemplo n.º 27
0
def get_scons_targets(input):
    # initialize target lists
    integrity_targets = list()
    sign_targets = list()
    encrypt_targets = list()
    sign_and_encrypt_targets = list()
    scons_targets = [integrity_targets, sign_targets, encrypt_targets, sign_and_encrypt_targets]
    pilsplit_files_to_clean = list()
    # get chipset and filename of input file
    chipset = SecImageConfigParser(input.config).root.metadata.get_chipset()
    path, filename = os.path.split(input.source)
    if input.build_policy:
        for policy in input.build_policy.sec_image_policies:
            target_list_to_append_to = scons_targets[target_map[policy.cmd_options]]
            # get path to installed image
            if input.sectools_install_base_dir:
                for install_location in policy.install_locations:
                    if input.install_file_name:
                        target = c_path.join(install_location, input.install_file_name)
                    else:
                        target = c_path.join(install_location, filename)
                    logger.debug("Added to-be-installed file \"{0}\" to SCons target list".format(target))
                    target_list_to_append_to.append(target)
                    # determine pilsplit images to cleanup
                    if input.pilsplitter_target_base_dir:
                        if install_location != input.sectools_install_base_dir:
                            pilsplit_directory = c_path.join(input.pilsplitter_target_base_dir, install_location.replace(os.path.join(input.sectools_install_base_dir, "", ""), ""))
                        else:
                            pilsplit_directory = input.pilsplitter_target_base_dir
                        if c_path.validate_dir_write(pilsplit_directory):
                            pilsplit_filename = input.install_file_name.split(".")[0] if input.install_file_name else filename.split(".")[0]
                            # get all pil files in pilsplit target directory
                            regex = r"^" + re.escape(pilsplit_filename) + r"\.((mdt)|(b[0-9][0-9]))$"
                            pil_files = [c_path.join(pilsplit_directory, f) for f in os.listdir(pilsplit_directory) if re.match(regex, f)]
                            for pil_file in pil_files:
                                logger.debug("Added pilsplit file \"{0}\" to SCons clean list".format(pil_file))
                                pilsplit_files_to_clean.append(pil_file)
            # get path to uninstalled image if no installation is requested
            else:
                uninstalled_target = c_path.normalize(c_path.join(input.target_base_dir, policy.id, chipset, input.sign_id, filename))
                target_list_to_append_to.append(uninstalled_target)
                logger.debug("Added file \"{0}\" to SCons target list".format(uninstalled_target))
    # remove duplicates from lists
    for i, targets in enumerate(scons_targets):
        scons_targets[i] = remove_duplicates(targets)
    pilsplit_files_to_clean = remove_duplicates(pilsplit_files_to_clean)
    # clean pilsplit files
    input.environment.Clean(scons_targets, pilsplit_files_to_clean)
    # return target list
    return scons_targets
Exemplo n.º 28
0
def getBuildIDfrompath(meta_build_path):
    """ Returns build ID from meta build path
    :param str meta_build_path: meta build path
    :returns: meta build ID
    :rtype: str
    """
    # meta build path validation
    path_val = c_path.normalize(meta_build_path)
    if not c_path.validate_dir(path_val):
        raise RuntimeError('Cannot access: ' + path_val)

    # get build id from build_path as it is the directory name in dest
    build_id = os.path.basename(path_val)

    return build_id
def generate_sha256_hash_from_file(filepath):
    import hashlib
    import os

    filepath = c_path.normalize(os.path.join(DIR_PATH, filepath))

    try:
        cert_file = open(filepath, 'rb')
        file_data = cert_file.read()
        cert_file.close()

    except Exception, e:
        error_str = 'file operation failed. {0}'.format(e)
        raise RuntimeError(error_str)
        raise e
Exemplo n.º 30
0
    def output_dir(self, output_dir):
        assert isinstance(output_dir, str)
        output_dir = c_path.normalize(output_dir)
        if not c_path.validate_dir_write(output_dir):
            raise RuntimeError('No write access to output directory: ' +
                               output_dir)

        # Update the output dir of each image in image_info_list
        for image_info in self.image_info_list:
            self.update_dest_image(image_info, output_dir)
        # Update the output dir of Multi-Image Signing and Integrity image
        if self._multi_image_imageinfo_dict:
            for target, imageinfo in self._multi_image_imageinfo_dict.items():
                self.update_dest_image(imageinfo, output_dir)

        self._output_dir = output_dir
    def sign(self, signingpackage_fname, outputdir):
        signaturepackage_binary = None
        cmds = self._getCmds(signingpackage_fname, outputdir)
        cass_server = self.cass_signer_attributes.server.host if self.cass_signer_attributes.server else "default CASS server"
        logger.info("Connecting to {0}".format(cass_server))
        logger.debug("Executing commands: \n'" + "\n".join(cmds) + "'\n")
        output = self._executeCmds(cmds)
        logger.debug(output)
        signaturepackage_filepath = os.path.join(outputdir, self.SIGNATUREPACKPAGE_RELPATH)
        if os.path.isfile(signaturepackage_filepath):
            logger.info("Signature package retrieved from server: " + c_path.normalize(signaturepackage_filepath))
            signaturepackage_binary = c_misc.load_data_from_file(signaturepackage_filepath)

            # clean up
            path, filename = os.path.split(signaturepackage_filepath)
            shutil.rmtree(path)
        return signaturepackage_binary
 def __init__(self, filepath=None, password="", keystoreType="JKS"):
     BaseKeystore.__init__(self, password)
     self._file = c_path.normalize(filepath)
     self._type = keystoreType
    def __init__(self, meta_build_path, config_dir_obj, sign_id_list=[]):
        assert isinstance(meta_build_path, str)
        assert isinstance(config_dir_obj, ConfigDir)

        # Initialize the BaseStager
        BaseStager.__init__(self)

        self.config_dir_obj = config_dir_obj

        # Create internal attributes
        self._meta_build_path = meta_build_path

        # Validate that the meta_build path exists
        meta_build_path = c_path.normalize(meta_build_path)
        if not c_path.validate_dir(meta_build_path):
            raise RuntimeError('No read access to the meta build path: ' + meta_build_path)

        # Get the meta lib module from the metabuild
        meta_info = self.get_meta_info(meta_build_path)

        # Create the image info list based on the meta data
        for sign_id, chipset, image_src_path, image_dest_path in self.get_image_info_from_meta(meta_info):
            # Filer on the sign id
            if sign_id_list:
                if sign_id not in sign_id_list:
                    continue

            try:
                img_config_parser = self.get_image_config_parser(chipset)

                # Validate the sign_id
                sign_id = self._get_sign_id(img_config_parser,
                                            os.path.basename(image_src_path.image_path),
                                            sign_id)

                # Get the config block for the sign id
                img_config_block = img_config_parser.get_config_for_sign_id(sign_id)

                # Create the one image info object
                image_info = ImageInfo('', sign_id, img_config_block,
                                       img_config_parser)

                # Set the src path
                image_info.src_image = image_src_path
                image_info.image_under_operation = image_info.src_image.image_path

                # Set the dest path
                image_info.dest_image = image_dest_path

                # Check if the dest image name should be overriden
                if img_config_block.output_file_name is not None:
                    image_info.dest_image.image_name = img_config_block.output_file_name

                # Put the image info object into the list
                self._image_info_list.append(image_info)

            except Exception as e:
                logger.error(str(e))

        if not self._image_info_list:
            raise RuntimeError('No images found from the meta build.')
Exemplo n.º 34
0
 def image_dir_base(self, image_dir_base):
     image_dir_base = c_path.normalize(image_dir_base)
     self._image_dir_base = image_dir_base
 def _formatpath(self, path):
     return c_path.normalize(path)