コード例 #1
0
    def c_epilog_from_params(self):
        """(str) Based on the arguments provided, return the extended epilog 
        message.
        """
        args = self.parsed_args
        help_obj = SecImageCore()
        epilog = ''

        if args.chipset == self._LIST_TAG:
            # Compile a list of available chipsets
            epilog += '\n' + 'Chipsets available: ' + '\n'
            for idx, chipset in enumerate(help_obj.available_chipsets):
                epilog += str(idx + 1) + '. ' + chipset + '\n'

        if (args.sign_id == self._LIST_TAG and args.chipset != self._LIST_TAG
                and args.config_path != self._LIST_TAG):
            if args.chipset:
                # Compile a list of available sign ids for a chipset
                help_obj.chipset = args.chipset
                epilog += '\n' + 'Sign-ids available for chipset "' + args.chipset + '": ' + '\n'
                for idx, sign_id in enumerate(help_obj.available_sign_ids):
                    epilog += str(idx + 1) + '. ' + sign_id + '\n'
            elif args.config_path:
                # Compile a list of available sign ids for a config file
                help_obj.config_path = args.config_path
                epilog += '\n' + 'Sign-ids available for config_path "' + args.config_path + '": ' + '\n'
                for idx, sign_id in enumerate(help_obj.available_sign_ids):
                    epilog += str(idx + 1) + '. ' + sign_id + '\n'

        return epilog
コード例 #2
0
    def _validate_sign(self, dp_file):
        """Validate the given debugpolicy elf file.
        """
        # Set the debug params
        if self.debug:
            debug = True
        else:
            debug = False

        # Initialize SecImageCore
        isc = SecImageCore(debug=debug)
        isc.config_path = self.secimage_config

        for sign in range(len(dp_file)):
            logger.info('\nValidating debugpolicy signed file against ' +
                        SECIMAGE_SIGN_ID[sign] + ' signature..')
            isc.set_image_path(dp_file[sign], SECIMAGE_SIGN_ID[sign])
            isc.output_dir = os.path.dirname(dp_file[sign])
            isc.image_info_list[0].dest_image.image_dir_ext = ''

            # Process the signed elf
            isc.process(val_sign=True)

            if os.path.isfile(c_path.join(self.output_dir,
                                          'SecImage_log.txt')):
                shutil.move(
                    c_path.join(self.output_dir, 'SecImage_log.txt'),
                    c_path.join(self.output_dir,
                                ('val_' + SECIMAGE_SIGN_ID[sign] +
                                 '_secimage_log.txt')))
コード例 #3
0
    def sign(self, dp_file):
        """Sign the given debugpolicy elf file.
        """

        try:
            self.input_file_list.pop()
        except:
            pass

        self.input_file_list.append(
            c_path.join(self.output_dir, 'dp_AP_signed.mbn'))
        self.input_file_list.append(
            c_path.join(self.output_dir, 'dp_MSA_signed.mbn'))

        # Set the debug params
        if self.debug:
            debug = True
        else:
            debug = False

        # Initialize SecImageCore
        isc = SecImageCore(debug=debug)
        isc.config_path = self.secimage_config

        for sign in range(len(SECIMAGE_SIGN_ID)):
            isc.set_image_path(dp_file, SECIMAGE_SIGN_ID[sign])
            isc.output_dir = os.path.dirname(dp_file)
            isc.image_info_list[0].dest_image.image_dir_ext = ''

            # Process the debug policy
            isc.process(sign=True)

            # Check if the signing is done or not
            if not isc.image_info_list[
                    0].status.sign.state == isc.image_info_list[
                        0].status.sign.SUCCESS:
                raise RuntimeError(
                    'Failed to sign the debugpolicy elf file: ' +
                    self.input_file_list[sign])
            logger.info('Signed debugpolicy elf file at: ' +
                        self.input_file_list[sign])

            if os.path.isfile(c_path.join(self.output_dir,
                                          'SecImage_log.txt')):
                shutil.move(
                    c_path.join(self.output_dir, 'SecImage_log.txt'),
                    c_path.join(
                        self.output_dir,
                        (SECIMAGE_SIGN_ID[sign] + '_secimage_log.txt')))
コード例 #4
0
    def _execute_pilsplit(self, file_to_pilsplit, pilsplit_prefix,
                          subdirectory):
        logger.debug("\nPilsplitting Sectools's output file...")
        if self.input.pilsplitter_target_base_dir:
            # Attempt pilsplit 3 times before failing
            pilsplit_successful = False
            for i in range(3):
                try:
                    if subdirectory:
                        subdir = c_path.join(
                            self.input.pilsplitter_target_base_dir,
                            subdirectory)
                        c_path.create_dir(subdir)
                        prefix = c_path.join(subdir, pilsplit_prefix)
                    else:
                        subdir = self.input.pilsplitter_target_base_dir
                        prefix = c_path.join(
                            self.input.pilsplitter_target_base_dir,
                            pilsplit_prefix)

                    SecImageCore.pil_split(file_to_pilsplit, prefix)
                except:
                    # Pilsplitting failed so retry pilsplit
                    continue
                pilsplit_successful = True
                logger.info(
                    "Pilsplitted \"{0}\" into directory \"{1}\"".format(
                        file_to_pilsplit, subdir))
                break
            if not pilsplit_successful:
                error_message = "Failed to pilsplit \"{0}\"".format(
                    file_to_pilsplit)
                logger.error(error_message)
                raise RuntimeError(error_message)
        else:
            logger.info(
                "Pilsplit was skipped because a value for pilsplitter_target_base_dir was not provided"
            )
コード例 #5
0
def main(args):
    """Parses the command line arguments, performs any basic operations based on
    the parsed arguments and starts processing using the isc module.
    """
    # Log to file
    log_to_file(args.output_dir)

    # Print the tool's launch command
    logger.debug('\n\n    SecImage launched as: "' + ' '.join(sys.argv) +
                 '"\n')

    # Initialize SecImageCore
    isc = SecImageCore(debug=args.debug)

    # Configure image signer
    if args.image_file or (
            args.meta_build
            and not SecImageCore.meta_supports_sign_id(args.meta_build)):
        if args.chipset:
            isc.set_chipset(args.chipset, args._c_overrides)
        elif args.config_path:
            isc.set_config_path(args.config_path, args._c_overrides)

    # Set the input
    if args.image_file:
        isc.set_image_path(args.image_file, args.sign_id)
    elif args.meta_build:
        isc.set_meta_build_path(args.meta_build,
                                [] if args.sign_id is None else [args.sign_id])

    # Set the output
    if args.mini_build:
        isc.mini_build_path = args.mini_build
    elif args.output_dir:
        isc.output_dir = args.output_dir

    # Process the images
    isc.process(verify_setup=args.verify_inputs,
                integrity_check=args.integrity_check,
                sign=args.sign,
                encrypt=args.encrypt,
                decrypt=args.decrypt,
                val_image=args.validate,
                val_integrity_check=args.validate,
                val_sign=args.validate,
                val_encrypt=args.validate)

    # Print the summary
    print_summary(args, isc.image_info_list)

    return isc.image_info_list
コード例 #6
0
    def c_validate(self):
        """Validates the command line args provided by the user.

        :raises: RuntimeError if any error occurs.
        """
        args = self.parsed_args
        err = []

        # Check if the meta build supports sign id
        meta_supports_sign_id = False
        if args.meta_build:
            meta_supports_sign_id = SecImageCore.meta_supports_sign_id(
                args.meta_build)

        # Check the input files
        if ((args.image_file and args.meta_build)
                or (not args.image_file and not args.meta_build)):
            err.append(
                'Provide either image_file or a meta_build for processing.')

        # Check that --override flag is not given without help flag
        if args.overrides and not args.help:
            err.append(
                '-h flag must accompany --overrides flag to view overridable properties'
            )

        # Check the configuration option and output dir
        if args.image_file or (args.meta_build and not meta_supports_sign_id):
            if ((args.chipset and args.config_path)
                    or (not args.chipset and not args.config_path)):
                err.append(
                    'Provide either chipset or a config_path to process images.'
                )
            if not args.output_dir:
                err.append('Provide the output_dir for storing the output.')
        elif args.meta_build and not meta_supports_sign_id:
            if not args.output_dir and not args.mini_build:
                err.append(
                    'Provide either output_dir or mini_build for storing the output.'
                )

        # Check the operations
        if not (args.integrity_check or args.sign or args.encrypt
                or args.decrypt or args.validate or args.verify_inputs):
            err.append('Specify one or more operations to perform.')

        # Check and sanitize any paths for read access
        for path in ['image_file', 'config_path']:
            path_val = getattr(args, path, None)
            if path_val:
                path_val = c_path.normalize(path_val)
                if not c_path.validate_file(path_val):
                    err.append('Cannot access ' + path + ' at: ' + path_val)
                setattr(args, path, path_val)

        # Check and sanitize any paths for read dir access
        for path in ['meta_build']:
            path_val = getattr(args, path, None)
            if path_val:
                path_val = c_path.normalize(path_val)
                if not c_path.validate_dir(path_val):
                    err.append('Cannot access ' + path + ' at: ' + path_val)
                setattr(args, path, path_val)

        # Check and sanitize paths for write access
        for path in ['output_dir', 'mini_build']:
            path_val = getattr(args, path, None)
            if path_val:
                path_val = c_path.normalize(path_val)
                try:
                    c_path.create_dir(path_val)
                except Exception as e:
                    err.append('Cannot write at: ' + path_val + '\n'
                               '    ' + 'Error: ' + str(e))
                setattr(args, path, path_val)

        # Raise error if any
        if err:
            if len(err) > 1:
                err = [('  ' + str(idx + 1) + '. ' + error)
                       for idx, error in enumerate(err)]
                err = 'Please check the command line args:\n\n' + '\n'.join(
                    err)
            else:
                err = err[0]
            raise RuntimeError(err)
コード例 #7
0
    def c_epilog_from_params(self):
        """(str) Based on the arguments provided, return the extended epilog
        message.
        """
        args = self.parsed_args
        help_obj = SecImageCore()
        epilog = ''

        # Extended Feature 1
        if args.chipset == self._LIST_TAG:
            # Compile a list of available chipsets
            epilog += '\n' + 'Chipsets available: ' + '\n'
            for idx, chipset in enumerate(help_obj.available_chipsets):
                epilog += str(idx + 1) + '. ' + chipset + '\n'

        # Extended Features 2 & 3
        elif (args.sign_id == self._LIST_TAG and args.chipset != self._LIST_TAG
              and args.config_path != self._LIST_TAG):

            # Extended Feature 2
            if args.chipset:
                # Compile a list of available sign ids for a chipset
                help_obj.chipset = args.chipset
                epilog += '\n' + 'Sign-ids available for chipset "' + args.chipset + '": ' + '\n'
                for idx, sign_id in enumerate(help_obj.available_sign_ids):
                    epilog += str(idx + 1) + '. ' + sign_id + '\n'

            # Extended Feature 3
            elif args.config_path:
                # Compile a list of available sign ids for a config file
                help_obj.config_path = args.config_path
                epilog += '\n' + 'Sign-ids available for config_path "' + args.config_path + '": ' + '\n'
                for idx, sign_id in enumerate(help_obj.available_sign_ids):
                    epilog += str(idx + 1) + '. ' + sign_id + '\n'

        # Extended Feature 4
        elif args.overrides:
            cert_configs = '\n    - ' + '\n    - '.join([
                'qc_presigned',
                'default',
                'mrc_sha256cert',
                'sha1_certs',
                'sha1_mrc_certs',
                'mrc_certs_manual',
                'rot_presigned_certs',
            ])

            # This should always contain all the available options
            order = [
                ('selected_signer', ''),
                ('selected_encryptor', ''),
                ('selected_cert_config', cert_configs),
                ('cass_capability', ''),
                ('', ''),
                ('msm_part', ''),
                ('oem_id', ''),
                ('model_id', ''),
                ('debug', ''),
                ('sw_id', ''),
                ('', ''),
                ('key_size', ''),
                ('exponent', ''),
                ('', ''),
                ('app_id', ''),
                ('crash_dump', ''),
                ('rot_en', ''),
                ('', ''),
                ('num_root_certs', '[1-16]'),
                ('mrc_index', '[0-15]'),
                ('', ''),
                ('max_cert_size', ''),
                ('num_certs_in_certchain', ''),
                ('', ''),
                ('soc_hw_version', ''),
                ('in_use_soc_hw_version', ''),
                ('use_serial_number_in_signing', ''),
                ('', ''),
                ('testsig_serialnum', ''),
                ('hash_pageseg_as_segment', ''),
            ]

            properties = self.overrides.get_properties()

            # Remove attributes excluded from order list
            del properties['mask_soc_hw_version']

            # Check all options are correct
            for tag in properties.keys():
                if not tag in [t for t, m in order]:
                    raise RuntimeError(
                        tag + ' is not provided in user interface order.')
            for tag, msg in order:
                if tag and not tag in properties.keys():
                    raise RuntimeError(tag +
                                       ' is extra in user interface order.')

            # Update the epilog
            epilog += ('Supported Parameters: ' + '\n\n')

            # Available options
            idx = 1
            for tag, msg in order:
                if tag:
                    override = properties[tag]
                    # Start of the option string
                    start = (
                        '%2d' % idx
                    ) + '. ' + self.override_prefix + tag + ' (' + override.type_str + ')'

                    # Help message
                    msg = ' : ' + msg if msg else ''

                    # Choices
                    choices = override.choices
                    if () in choices:
                        choices.remove(())
                    choices_string = ' : ' + str(choices) if choices else ''
                    if len(start + choices_string) > 80:
                        choices_string = ' :\n    - ' + '\n    - '.join(
                            choices)

                    # Put all together
                    epilog += start + msg + choices_string + '\n'
                    idx += 1
                else:
                    epilog += '\n'

        return epilog
コード例 #8
0
def main(args, return_isc=False):
    """Parses the command line arguments, performs any basic operations based on
    the parsed arguments and starts processing using the isc module.
    """
    # Log to file
    flids = logger.log_to_file(SECIMAGE_TOOL_NAME, args.output_dir)

    try:
        # Print the tool's launch command
        logged_args = CoreOptionParser.mask_private_args(
            sys.argv, args._c_spec_override_prefix)
        logger.info('\n\n    SecImage launched as: "' + ' '.join(logged_args) +
                    '"\n')

        # Initialize SecImageCore
        isc = SecImageCore(debug=args.debug)

        # Configure image signer
        if args.image_file or (
                args.meta_build
                and not SecImageCore.meta_supports_sign_id(args.meta_build)):
            if args.chipset:
                isc.set_chipset(args.chipset, args._c_overrides,
                                args._c_spec_overrides)
            elif args.config_path:
                isc.set_config_path(args.config_path, args._c_overrides,
                                    args._c_spec_overrides)

        # Set the input
        if args.image_file:
            isc.set_image_path(args.image_file, args.sign_id)
        elif args.meta_build:
            isc.set_meta_build_path(
                args.meta_build,
                [] if args.sign_id is None else [args.sign_id])

        # Set the output
        if args.mini_build:
            isc.mini_build_path = args.mini_build
        elif args.output_dir:
            isc.output_dir = args.output_dir

        if args.qc_signing:
            isc.authority = AUTHORITY_QC

        # Process the images
        isc.process(verify_setup=args.verify_inputs,
                    integrity_check=args.integrity_check,
                    sign=args.sign,
                    encrypt=args.encrypt,
                    decrypt=args.decrypt,
                    val_image=args.validate,
                    val_integrity_check=args.validate,
                    val_sign=args.validate,
                    val_encrypt=args.validate,
                    root_cert_hash=args.rch)

        # Print the summary
        print_summary(args, isc.image_info_list)

        if return_isc:
            return isc
        else:
            return isc.image_info_list

    finally:
        # Clear all log handlers
        logger.removeFileLogger(flids)
コード例 #9
0
ファイル: dpc.py プロジェクト: basehub/sectools
    def _validate_sign(self, dp_file, rootcerthash=None, sign_id=None):
        """Validate the given debugpolicy elf file.
        """
        # Initialize SecImageCore
        isc = SecImageCore(debug=self.debug)
        isc.config_path = self.secimage_config
        if self.authority is not None:
            isc.authority = self.authority

        # Get the supported sign_id list
        sign_id_list = isc._img_config_parser.sign_id_list

        # Validating signed images & signed image(in case of one image) for sign_ids available in sign_id list
        if sign_id is None:
            if len(dp_file) > 1:
                for sign in range(len(dp_file)):
                    logger.info(
                        '\nValidating debugpolicy signed file against ' +
                        sign_id_list[sign] + ' signature..')
                    isc.set_image_path(dp_file[sign], sign_id_list[sign])
                    isc.output_dir = os.path.dirname(dp_file[sign])
                    isc.image_info_list[0].dest_image.image_dir_ext = ''

                    # Process the signed elf
                    isc.process(val_sign=True, root_cert_hash=rootcerthash)

                    if os.path.isfile(
                            c_path.join(self.output_dir, 'SecImage_log.txt')):
                        shutil.move(
                            c_path.join(self.output_dir, 'SecImage_log.txt'),
                            c_path.join(self.output_dir,
                                        ('val_' + sign_id_list[sign] +
                                         '_secimage_log.txt')))
            else:
                for sign in range(len(sign_id_list)):
                    logger.info(
                        '\nValidating debugpolicy signed file against ' +
                        sign_id_list[sign] + ' signature..')
                    isc.set_image_path(dp_file[0], sign_id_list[sign])
                    isc.output_dir = os.path.dirname(dp_file[0])
                    isc.image_info_list[0].dest_image.image_dir_ext = ''

                    # Process the signed elf
                    isc.process(val_sign=True, root_cert_hash=rootcerthash)

                    if os.path.isfile(
                            c_path.join(self.output_dir, 'SecImage_log.txt')):
                        shutil.move(
                            c_path.join(self.output_dir, 'SecImage_log.txt'),
                            c_path.join(self.output_dir,
                                        ('val_' + sign_id_list[sign] +
                                         '_secimage_log.txt')))

        # Validating signed image for given sign_id
        else:
            if sign_id not in sign_id_list:
                raise RuntimeError('Received sign_id "' + sign_id +
                                   '" as input.' + '\n'
                                   "       Supported sign_id's are: " +
                                   str(sign_id_list))

            logger.info('\nValidating debugpolicy signed file against ' +
                        sign_id + ' signature..')
            isc.set_image_path(dp_file[0], sign_id)
            isc.output_dir = os.path.dirname(dp_file[0])
            isc.image_info_list[0].dest_image.image_dir_ext = ''

            # Process the signed elf
            isc.process(val_sign=True, root_cert_hash=rootcerthash)

            if os.path.isfile(c_path.join(self.output_dir,
                                          'SecImage_log.txt')):
                shutil.move(
                    c_path.join(self.output_dir, 'SecImage_log.txt'),
                    c_path.join(self.output_dir,
                                ('val_' + sign_id + '_secimage_log.txt')))
コード例 #10
0
ファイル: dpc.py プロジェクト: basehub/sectools
    def sign(self, dp_file, sign_id=None):
        """Sign the given debugpolicy elf file.
        """

        try:
            self.input_file_list.pop()
        except:
            pass

        # Initialize SecImageCore
        isc = SecImageCore(debug=self.debug)
        isc.config_path = self.secimage_config
        if self.authority is not None:
            isc.authority = self.authority

        # Get the supported sign_id list
        sign_id_list = isc._img_config_parser.sign_id_list

        # Generating signed images for sign_ids available in sign_id list
        if sign_id is None:
            for sign in range(len(sign_id_list)):
                isc.set_image_path(dp_file, sign_id_list[sign])
                isc.output_dir = os.path.dirname(dp_file)
                isc.image_info_list[0].dest_image.image_dir_ext = ''

                # Process the debug policy
                isc.process(sign=True)

                # Check if the signing is done or not
                if not isc.image_info_list[
                        0].status.sign.state == isc.image_info_list[
                            0].status.sign.SUCCESS:
                    raise RuntimeError(
                        'Failed to sign the debugpolicy elf file: ' +
                        isc.image_info_list[0].image_under_operation)
                logger.info('Signed debugpolicy elf file at: ' +
                            isc.image_info_list[0].image_under_operation)
                self.input_file_list.append(
                    isc.image_info_list[0].image_under_operation)

                if os.path.isfile(
                        c_path.join(self.output_dir, 'SecImage_log.txt')):
                    shutil.move(
                        c_path.join(self.output_dir, 'SecImage_log.txt'),
                        c_path.join(
                            self.output_dir,
                            (sign_id_list[sign] + '_secimage_log.txt')))

        # Generating signed image for given sign_id
        else:
            if sign_id not in sign_id_list:
                raise RuntimeError('Received sign_id "' + sign_id +
                                   '" as input.' + '\n'
                                   "       Supported sign_id's are: " +
                                   str(sign_id_list))

            isc.set_image_path(dp_file, sign_id)
            isc.output_dir = os.path.dirname(dp_file)
            isc.image_info_list[0].dest_image.image_dir_ext = ''

            # Process the debug policy
            isc.process(sign=True)

            # Check if the signing is done or not
            if not isc.image_info_list[
                    0].status.sign.state == isc.image_info_list[
                        0].status.sign.SUCCESS:
                raise RuntimeError(
                    'Failed to sign the debugpolicy elf file: ' +
                    isc.image_info_list[0].image_under_operation)
            logger.info('Signed debugpolicy elf file at: ' +
                        isc.image_info_list[0].image_under_operation)
            self.input_file_list.append(
                isc.image_info_list[0].image_under_operation)

            if os.path.isfile(c_path.join(self.output_dir,
                                          'SecImage_log.txt')):
                shutil.move(
                    c_path.join(self.output_dir, 'SecImage_log.txt'),
                    c_path.join(self.output_dir,
                                (sign_id + '_secimage_log.txt')))
コード例 #11
0
ファイル: secimage.py プロジェクト: mxpro2003/qcs605_root
    def c_validate(self):
        """Validates the command line args provided by the user.

        :raises: RuntimeError if any error occurs.
        """
        args = self.parsed_args
        err = []

        # Check the input files
        if ((args.image_file and args.meta_build)
                or (not args.image_file and not args.meta_build)):
            err.append(
                'Provide either image_file or a meta_build for processing.')

        # Check that m_image_file and meta_build are not both provided
        if args.meta_build and args.m_image_file:
            err.append('--m_image_file cannot be provided with meta_build.')
            err.append('Provide --m_gen flag if ' + multi_image_string() +
                       ' file generation is desired.')

        # Check that m_gen and m_image_file are not both provided
        if args.m_gen and args.m_image_file:
            err.append('Provide either --m_image_file or --m_gen.')

        # Check that --override flag is not given without help flag
        if args.overrides and not args.help:
            err.append(
                '-h flag must accompany --overrides flag to view overridable properties'
            )

        # Check if the meta build supports sign id
        meta_supports_sign_id = False
        if args.meta_build:
            meta_supports_sign_id = SecImageCore.meta_supports_sign_id(
                args.meta_build)

        # Check the configuration option and output dir
        if args.image_file or (args.meta_build and not meta_supports_sign_id):
            if ((args.chipset and args.config_path)
                    or (not args.chipset and not args.config_path)):
                err.append(
                    'Provide either chipset or a config_path to process images.'
                )
            if not args.output_dir:
                err.append('Provide the output_dir for storing the output.')
        elif args.meta_build and not meta_supports_sign_id:
            if not args.output_dir and not args.mini_build:
                err.append(
                    'Provide either output_dir or mini_build for storing the output.'
                )

        if not (args.integrity_check or args.sign or args.encrypt
                or args.decrypt or args.validate or args.verify_inputs
                or args.no_op):
            err.append('Specify one or more operations to perform.')

        # Check that multi-image operations are enabled when m_gen or m_image_file are provided
        if args.m_image_file and not (args.m_integrity_check or args.m_sign
                                      or args.m_encrypt or args.m_decrypt
                                      or args.m_validate):
            err.append('Specify one or more ' + multi_image_string() +
                       ' image operations to perform.')
        if args.m_gen and not (args.m_integrity_check or args.m_sign
                               or args.m_encrypt):
            err.append('Specify one or more ' + multi_image_string() +
                       ' image operations to perform.')

        # Check that multi-image operations are not enabled when m_gen and m_image_file are missing
        if not (args.m_gen or args.m_image_file) and (
                args.m_integrity_check or args.m_sign or args.m_encrypt
                or args.m_decrypt or args.m_validate):
            err.append(
                'Provide either --m_image_file or --m_gen when performing ' +
                multi_image_string() + ' image operations.')

        # Check that no_op operation is only enabled when m_gen or m_image_file are provided
        if args.no_op and not (args.m_gen or args.m_image_file):
            err.append(
                'Provide either --m_image_file or --m_gen when adding image entry to '
                + multi_image_string() + ' image.')

        # Check that no_op operation is not provided with any other individual image operations
        if args.no_op and (args.integrity_check or args.sign or args.encrypt
                           or args.decrypt or args.validate):
            err.append(
                'no_op operation cannot be performed alongside other image operations'
            )

        # Check sign_attr is only set when adding hash table
        if args.sign_attr and not (args.integrity_check or args.sign):
            err.append(
                'sign_attr operation can only be performed when integrity_check or sign are being performed.'
            )

        # Check m_sign_attr is only set when adding hash table
        if args.m_sign_attr and not (args.m_integrity_check or args.m_sign):
            err.append(
                'm_sign_attr operation can only be performed when m_integrity_check or m_sign are being performed.'
            )

        # Check other options:
        if args.rch and not args.validate:
            err.append(
                'Root Cert Hash can only be given when "--validate" operation is provided.'
            )

        # Check and sanitize any paths for read access
        for path in ['image_file', 'config_path']:
            path_val = getattr(args, path, None)
            if path_val:
                path_val = c_path.normalize(path_val)
                if not c_path.validate_file(path_val):
                    err.append('Cannot access ' + path + ' at: ' + path_val)
                setattr(args, path, path_val)

        # Check and sanitize any paths for read dir access
        for path in ['meta_build']:
            path_val = getattr(args, path, None)
            if path_val:
                path_val = c_path.normalize(path_val)
                if not c_path.validate_dir(path_val):
                    err.append('Cannot access ' + path + ' at: ' + path_val)
                setattr(args, path, path_val)

        # Check and sanitize paths for write access
        for path in ['output_dir', 'mini_build']:
            path_val = getattr(args, path, None)
            if path_val:
                path_val = c_path.normalize(path_val)
                try:
                    c_path.create_dir(path_val)
                except Exception as e:
                    err.append('Cannot write at: ' + path_val + '\n'
                               '    ' + 'Error: ' + str(e))
                setattr(args, path, path_val)

        # Raise error if any
        if err:
            if len(err) > 1:
                err = [('  ' + str(idx + 1) + '. ' + error)
                       for idx, error in enumerate(err)]
                err = 'Please check the command line args:\n\n' + '\n'.join(
                    err)
            else:
                err = err[0]
            raise RuntimeError(err)
コード例 #12
0
ファイル: secimage.py プロジェクト: mxpro2003/qcs605_root
    def c_epilog_from_params(self):
        """(str) Based on the arguments provided, return the extended epilog
        message.
        """
        args = self.parsed_args
        help_obj = SecImageCore()
        epilog = ''

        # Extended Feature 1
        if args.chipset == self._LIST_TAG:
            # Compile a list of available chipsets
            epilog += '\n' + 'Chipsets available: ' + '\n'
            for idx, chipset in enumerate(help_obj.available_chipsets):
                epilog += str(idx + 1) + '. ' + chipset + '\n'

        # Extended Features 2 & 3
        elif (args.sign_id == self._LIST_TAG and args.chipset != self._LIST_TAG
              and args.config_path != self._LIST_TAG):

            # Extended Feature 2
            if args.chipset:
                # Compile a list of available sign ids for a chipset
                help_obj.chipset = args.chipset
                epilog += '\n' + 'Sign-ids available for chipset "' + args.chipset + '": ' + '\n'
                for idx, sign_id in enumerate(help_obj.available_sign_ids):
                    epilog += str(idx + 1) + '. ' + sign_id + '\n'

            # Extended Feature 3
            elif args.config_path:
                # Compile a list of available sign ids for a config file
                help_obj.config_path = args.config_path
                epilog += '\n' + 'Sign-ids available for config_path "' + args.config_path + '": ' + '\n'
                for idx, sign_id in enumerate(help_obj.available_sign_ids):
                    epilog += str(idx + 1) + '. ' + sign_id + '\n'

        # Extended Feature 4
        elif args.overrides:
            cert_configs = '\n    - ' + '\n    - '.join([
                'qti_presigned_certs',
                'default',
                'mrc_presigned_certs',
                'sha1_certs',
                'sha1_mrc_certs',
                'mrc_certs_manual',
                'rot_presigned_certs',
            ])

            # This should always contain all the available options
            order = [
                ('selected_signer', ''),
                ('selected_encryptor', ''),
                ('selected_cert_config', cert_configs),
                ('cass_capability', ''),
                ('hash_algorithm', ''),
                ('segment_hash_algorithm', ''),
                ('cass_attest_cert', ''),
                ('', ''),
                ('msm_part', ''),
                ('oem_id', ''),
                ('model_id', ''),
                ('debug', ''),
                ('sw_id', ''),
                ('anti_rollback_version', ''),
                ('', ''),
                ('key_size', ''),
                ('exponent', ''),
                ('', ''),
                ('dsa_type', ''),
                ('ecdsa_curve', ''),
                ('', ''),
                ('app_id', ''),
                ('crash_dump', ''),
                ('rot_en', ''),
                ('', ''),
                ('num_root_certs', ''),
                ('max_num_root_certs', ''),
                ('mrc_index', ''),
                ('', ''),
                ('max_cert_size', ''),
                ('num_certs_in_certchain', ''),
                ('', ''),
                ('soc_hw_version', ''),
                ('soc_vers', "ex \"0x0001 0x0002 0x0003\""),
                ('in_use_soc_hw_version', ''),
                ('use_serial_number_in_signing', ''),
                ('serial_number', ''),
                ('multi_serial_numbers',
                 "ex \"0x01234567 0x12345678 0x23456789\""),
                ('oem_id_independent', ''),
                ('', ''),
                ('testsig_serialnum', ''),
                ('hash_pageseg_as_segment', ''),
                ('hmac', ''),
                ('rsa_padding', ''),
                ('', ''),
                ('secboot_version', ''),
                ('qti_sign', ''),
                ('oem_sign', ''),
                ('', ''),
                ('UIE_key', ''),
                ('UIE_capability', ''),
                ('UIE_root_key_type', ''),
                ('uie_key_switch_enable', ''),
                ('', ''),
                ('revocation_enablement', ''),
                ('activation_enablement', ''),
                ('root_revoke_activate_enable', ''),
                ('', ''),
                ('multi_image_segment_addr', ''),
                ('', ''),
                ('client_id', ''),
                ('lib_id', ''),
                ('', ''),
                ('image_entry', ''),
            ]

            properties = self.overrides.get_properties()

            # Remove attributes excluded from order list
            del properties['mask_soc_hw_version']

            # Check all options are correct
            for tag in properties.keys():
                if not tag in [t for t, m in order]:
                    raise RuntimeError(
                        tag + ' is not provided in user interface order.')
            for tag, msg in order:
                if tag and not tag in properties.keys():
                    raise RuntimeError(tag +
                                       ' is extra in user interface order.')

            # Update the epilog
            epilog += ('Supported Parameters: ' + '\n\n')

            # Available options
            idx = 1
            for tag, msg in order:
                if tag:
                    override = properties[tag]
                    # Start of the option string
                    from sectools.common.utils.datautils import data_detail
                    start = (
                        '%2d' %
                        idx) + '. ' + self.override_prefix + tag + ' (' + (
                            override.type_str if
                            tag != MULTI_SERIAL_NUMBERS_TAG else data_detail.
                            _data_type_str[data_detail.DataType.String]) + ')'

                    # Help message
                    msg = ' : ' + msg if msg else ''

                    # Choices
                    choices = override.choices
                    if () in choices:
                        choices.remove(())
                    choices_string = ' : ' + str(choices) if choices else ''
                    if len(start + choices_string) > 80:
                        choices_string = ' :\n    - ' + '\n    - '.join(
                            choices)

                    # Put all together
                    epilog += start + msg + choices_string + '\n'
                    idx += 1
                else:
                    epilog += '\n'

            epilog += ('\n\nSpecial Parameters: ' + '\n\n')

            for tag, override in self.spec_overrides.get_properties().items():
                #Start of the option string
                epilog += (
                    '%2d' % idx
                ) + '. ' + self.spec_override_prefix + tag + ' (' + override.type_str + ')\n'
                idx += 1

        return epilog