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"
                )
def generatesigned(chipset, output_dir, sig_package, sign_id=None,
                   imagefile=None, metabuild=None, verbose=False, debug=False,
                   quiet=False):
    """Returns the signed image file.
    """
    retcode = 0
    errstr = ''
    signed_image = ''
    expected_path = ''

    # Launch secimage once to get the image info list
    il = launch_secimage(chipset=chipset, output_dir=output_dir,
                         sign_id=sign_id, imagefile=imagefile,
                         metabuild=metabuild, signer=SIGNER_REMOTE,
                         sign=True, verbose=verbose, debug=debug,
                         quiet=(False if verbose else True))

    # Copy the zip to where its expected in the output directory
    sig_package_exp = SecimageRemoteClientSigner.get_signature_package_path(il[0])
    if (sig_package != sig_package_exp):
        c_path.create_dir(os.path.dirname(sig_package_exp))
        ret, err = copyFile(sig_package, sig_package_exp)
        if not ret:
            raise RuntimeError(err)

    try:
        # Launch secimage
        il = launch_secimage(chipset=chipset, output_dir=output_dir,
                             sign_id=sign_id, imagefile=imagefile,
                             metabuild=metabuild, signer=SIGNER_REMOTE,
                             sign=True, verbose=verbose, debug=debug, quiet=quiet)

        # Verify the signed image was generated
        signed_image = il[0].dest_image.image_path
        if not c_path.validate_file(signed_image):
            retcode = 1
            errstr = 'Failed to generate the signed image. ' + str(il[0].status.sign.error)
        else:
            expected_path = il[0].src_image.image_path

    except Exception as e:
        retcode = 1
        errstr = 'Exception occurred while running secimage. Exception - ' + str(e)

    return retcode, errstr, signed_image, expected_path
def generatesigpack(output_dir,
                    hash_package,
                    accept_signattrs=False,
                    verbose=False,
                    debug=False,
                    quiet=False):
    """Returns the signature/certs package for the hash provided.
    """
    retcode = 0
    errstr = ''
    sig_package = ''

    # Objects to be cleaned at the end
    to_sign_file = None
    temp_config_file = None
    copied_sig_file = None

    try:
        # Unzip the hash package
        def get_hash_package_data(package):
            to_sign_package = Package(
                None,
                SecimageRemoteClientSigner.get_class_ToSignPackageFiles(),
                package=package)
            to_sign_package.update_data()
            return SecimageRemoteClientSigner.use_tosign_data(
                to_sign_package.pf)

        to_sign, signing_config = get_hash_package_data(hash_package)

        # Extract the signing info
        signing_config = json.loads(signing_config)
        chipset = str(signing_config['chipset'])
        sign_id = str(signing_config['sign_id'])

        # Save to_sign to a temp file
        to_sign_file_path = c_path.join(output_dir, 'hash_to_sign.bin')
        store_data_to_file(to_sign_file_path, to_sign)
        to_sign_file = to_sign_file_path

        if retcode == 0:

            # Create new config file to update the allow signing attribute &
            # the file type
            def update_cfg_cb(config):
                remote_config = auto_gen_xml_config.complex_remote_signer_attributes(
                )
                remote_config.allow_signing_overrides = accept_signattrs
                config.root.signing.signer_attributes.remote_signer_attributes = remote_config
                sign_id_config = config.get_config_for_sign_id(sign_id)
                sign_id_config.pil_split = False
                sign_id_config.image_type = 'hash_to_sign'

            temp_config_file = c_path.join(output_dir,
                                           'signature_package_config.xml')
            update_config(chipset, update_cfg_cb, temp_config_file)

            # Launch secimage once to get the image info list
            il = launch_secimage(config=temp_config_file,
                                 output_dir=output_dir,
                                 sign_id=sign_id,
                                 imagefile=to_sign_file,
                                 signer=SIGNER_LOCAL,
                                 verify_input=True,
                                 verbose=verbose,
                                 debug=debug,
                                 quiet=(False if verbose else True))

            # Copy the zip to where its expected in the output directory
            hash_package_exp = SecimageRemoteClientSigner.get_to_sign_package_path(
                il[0])
            if (hash_package != hash_package_exp):
                c_path.create_dir(os.path.dirname(hash_package_exp))
                ret, err = copyFile(hash_package, hash_package_exp)
                copied_sig_file = hash_package_exp
                if not ret:
                    raise RuntimeError(err)

            # Launch secimage
            il = launch_secimage(config=temp_config_file,
                                 output_dir=output_dir,
                                 sign_id=sign_id,
                                 imagefile=to_sign_file,
                                 signer=SIGNER_LOCAL,
                                 sign=True,
                                 verbose=verbose,
                                 debug=debug,
                                 quiet=quiet)

            # Verify the signature package was generated
            sig_package = SecimageRemoteClientSigner.get_signature_package_path(
                il[0])
            if not c_path.validate_file(sig_package):
                retcode = 1
                errstr = 'Failed to generate the signature package. ' + str(
                    il[0].status.sign.error)

    except Exception as e:
        retcode = 1
        errstr = 'Exception occurred while running secimage. Exception - ' + str(
            e)

    finally:
        if not debug:
            if to_sign_file is not None:
                try:
                    os.remove(to_sign_file)
                except Exception:
                    pass
            if temp_config_file is not None:
                try:
                    os.remove(temp_config_file)
                except Exception:
                    pass
            if copied_sig_file is not None:
                try:
                    os.remove(copied_sig_file)
                except Exception:
                    pass

    return retcode, errstr, sig_package