예제 #1
0
    def gen_keys(self, curve, priv_key_path=None, pub_key_path=None):
        # Generate the key pair using openssl
        priv_key = self._gen_ecdsa_key_pair(curve)

        # Save the private key to file
        priv_path = priv_key_path if priv_key_path is not None else c_path.create_tmp_file(
        )

        # Generate the public key file
        try:
            logger.debug('Writing generated private key to PEM file: ' +
                         priv_path)
            c_path.store_data_to_file(priv_path, priv_key)

            # Extract the public key from the private key
            pub_key = self.get_public_key_from_private(priv_key)
        finally:
            # Cleanup temp file
            c_path.remove_tmp_file(priv_path)

        # Save the public key to file
        if pub_key_path is not None:
            logger.debug('Writing generated public key to PEM file: ' +
                         pub_key_path)
            c_path.store_data_to_file(pub_key_path, pub_key)

        return priv_key, pub_key
예제 #2
0
    def save_package(self):
        # Set local variables
        package = self.package
        pf = self.pf

        # Check that the package can be written to
        if package is None:
            raise RuntimeError('Package is not set')
        elif not c_path.validate_file_write(package):
            raise RuntimeError('Package could not be written to at ' + package)

        # Set internal functions
        write_func = lambda x, y: store_data_to_file(c_path.join(package, x), y
                                                     )
        if pf.zip:
            fp = zipfile.ZipFile(package, 'w')
            write_func = fp.writestr

        # Store the relevant files in the package
        try:
            for file_tag, file_info in pf.file_data.items():
                # Decide optional and list tags
                file_type = file_info['type']
                is_optional = False
                is_list = False
                if isinstance(file_type, tuple):
                    is_optional = True
                    file_type = file_type[0]
                if isinstance(file_type, list):
                    is_list = True
                    file_type = file_type[0]

                # Check optional data
                if file_info['data'] is None:
                    if is_optional:
                        continue
                    else:
                        raise RuntimeError(file_tag + ' doesnt have any data')

                # Write the data
                if is_list:
                    if (len(file_info['data']) == 1):
                        write_func(file_info['name'].format(''),
                                   file_info['data'][0])
                    else:
                        for idx, d in enumerate(file_info['data']):
                            write_func(
                                file_info['name'].format('_' + str(idx + 1)),
                                d)
                else:
                    write_func(file_info['name'], file_info['data'])
        finally:
            if pf.zip:
                fp.close()
예제 #3
0
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 = copy_file(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