示例#1
0
    def _validate_certificate_params_dict(self, certificate_params_dict):
        certificate_params_is_valid = False
        generate_new_certificate = False
        for key in certificate_params_dict:
            if key not in ['C', 'CN', 'L', 'O', 'ST', 'OU', 'emailAddress']:
                if key not in ['private_key_path', 'certificate_path']:
                    logger.error(
                        "Invalid Key is being passed in configuration!" +
                        repr(key))
                    raise RuntimeError(
                        "Invalid Key is being passed in configuration!")
                else:
                    # pre-generated cert/key, check if exist
                    if os.path.exists(
                            certificate_params_dict['private_key_path']
                    ) is False:
                        err_str = "private_key_path does not exist: {0}!".format(
                            certificate_params_dict['private_key_path'])
                        logger.error(err_str)
                        certificate_params_is_valid = False
                        raise RuntimeError(err_str)

                    if os.path.exists(
                            certificate_params_dict['certificate_path']
                    ) is False:
                        err_str = "certificate_path does not exist: {0}!".format(
                            certificate_params_dict['certificate_path'])
                        logger.error(err_str)
                        certificate_params_is_valid = False
                        raise RuntimeError(err_str)

                    cert_version = crypto.cert.get_version(
                        crypto.cert.get_text(
                            c_path.load_data_from_file(
                                certificate_params_dict['certificate_path'])))
                    if cert_version == crypto.cert.CERT_V3:
                        generate_new_certificate = False
                        certificate_params_is_valid = True
                    else:
                        logger.critical('Certificate version is incorrect: ' +
                                        str(cert_version))
                        raise RuntimeError(
                            'Invalid certificate: ' +
                            certificate_params_dict['certificate_path'])

            else:  # generate new cert/key
                certificate_params_is_valid = True
                generate_new_certificate = True

        return certificate_params_is_valid, generate_new_certificate
    def decrypt(self, message, key, iv, ciphername=AesCbcBase.CIPHERNAME_128):
        message_path, decrypted_message_path = None, None
        try:
            message_path = c_path.create_tmp_file(message)
            decrypted_message_path = c_path.create_tmp_file()

            cmd = [
                self.openssl, 'enc', ciphername, '-d', '-in', message_path,
                '-K', key, '-iv', iv, '-out', decrypted_message_path, '-nopad'
            ]
            run_command(cmd)
            return c_path.load_data_from_file(decrypted_message_path)
        finally:
            c_path.remove_tmp_file(message_path)
            c_path.remove_tmp_file(decrypted_message_path)
示例#3
0
    def _populate_database(cls, data_prov_object, level, path):
        """ Recursively creates and fills in the DataProvObject including all of it's children

        :param data_prov_object: the highest level of the DataProvObject hierarchy
        :type data_prov_object: DataProvObject
        :param level: the level depth of the current data prov hierarchy. Should be set to 1 when initially calling _populate_database
        :type level: int
        :param path: the path in the file system corresponding to the current data prov level through which to scan and populate the DataProvObject
        :type path: str
        :rtype: None
        :raises: RuntimeError
        """

        for item in os.listdir(path):
            if item.endswith(".xml") and level == BINARY_FILE_LEVEL:
                data_prov_object.config = cls._get_config(
                    c_path.join(path, item))
            # allow for unix style hidden folders to exist
            elif item.startswith("."):
                continue
            elif c_path.validate_dir(c_path.join(
                    path, item)) and level == BINARY_FILE_LEVEL:
                raise RuntimeError(
                    "DataProvisioner:  found directory {0} in binary_file level of DataProvisioner. \
                Directories are not allowed in the binary_file level".format(
                        item))
            elif not c_path.validate_dir(c_path.join(
                    path, item)) and level != BINARY_FILE_LEVEL:
                raise RuntimeError(
                    "DataProvisioner:  found binary file {0} in level {1} of DataProvisioner. \
                Binary files are only allowed at the binary_file level".format(
                        item, cls._level_num_to_name(level)))
            elif level == 4:
                try:
                    data_prov_object.files[item] = c_path.load_data_from_file(
                        c_path.join(path, item))
                except:
                    raise RuntimeError(
                        "DataProvisioner:  Can't open {0}".format(
                            c_path.join(path, item)))

            # recursively populate database children
            if level < BINARY_FILE_LEVEL:
                child_data_prov_object = DataProvObject(
                    item, c_path.join(path, item))
                data_prov_object.children[item] = child_data_prov_object
                cls._populate_database(child_data_prov_object, level + 1,
                                       c_path.join(path, item))
    def encrypt(self, message, key, iv, aad):
        message_path, encrypted_message_path = None, None
        try:
            message_path = c_path.create_tmp_file(message)
            encrypted_message_path = c_path.create_tmp_file()

            cmd = [
                self.crypto_ccm, '--input-file', message_path, '--key', key,
                '--iv', iv, '--output', encrypted_message_path,
                '--operation=encrypt', '--aad', aad
            ]
            run_command(cmd, log=False)
            return c_path.load_data_from_file(encrypted_message_path)
        finally:
            c_path.remove_tmp_file(message_path)
            c_path.remove_tmp_file(encrypted_message_path)
    def decrypt(self, message, key, iv):
        message_path, decrypted_message_path = None, None
        try:
            message_path = c_path.create_tmp_file(message)
            decrypted_message_path = c_path.create_tmp_file()

            cmd = [
                self.crypto_cbc, '--input-file', message_path, '--key', key,
                '--iv', iv, '--output', decrypted_message_path,
                '--operation=decrypt'
            ]
            run_command(cmd, log=False)
            return c_path.load_data_from_file(decrypted_message_path)
        finally:
            c_path.remove_tmp_file(message_path)
            c_path.remove_tmp_file(decrypted_message_path)
示例#6
0
    def encrypt_segment(self, binary_segment, segment_num):
        '''
        Encrypt elf segments using cbc encryption
        input:
        binary_segment: A string representing the binary segment that needs to be encrypted.
        segment_num: The segment number, used to calculate the segment IV

        output:
        encrypted_binary_segment: CBC encrypted segment
        '''
        if len(binary_segment) < 16 and len(binary_segment) != 0:
            raise RuntimeError("The input plaintext is less than the minimum.")
        else:
            pt_fn = c_path.create_tmp_file(data=binary_segment)
            op_fn = c_path.create_tmp_file()
            self.encryption_parameters.ssd_p.enc_segment(
                segment_num, pt_fn, op_fn)
            encrypted_binary_segment = c_path.load_data_from_file(op_fn)
            os.unlink(pt_fn)
            os.unlink(op_fn)
            return encrypted_binary_segment
    def decrypt(self, message, key, iv, aad):
        message_path, decrypted_message_path = None, None
        try:
            message_path = c_path.create_tmp_file(message)
            decrypted_message_path = c_path.create_tmp_file()

            cmd = [
                self.crypto_ccm, '--input-file', message_path, '--key', key,
                '--iv', iv, '--output', decrypted_message_path,
                '--operation=decrypt', '--aad', aad
            ]
            output = run_command(cmd, log=False)

            # Check there is no issue with the output
            if "Caught HashVerificationFailed..." in output:
                raise RuntimeError(output)

            return c_path.load_data_from_file(decrypted_message_path)
        finally:
            c_path.remove_tmp_file(message_path)
            c_path.remove_tmp_file(decrypted_message_path)
    def encrypt(self, message, key, iv):
        """ Function to encrypt binary with a CBC 128 bit cipher.
        input:
        binary_blob: Binary blob to encrypt
        hex_preexisting_128_bit_key: hex representarion of 128bit key | None,
        if None, the key is generated

        hex_preexisting_iv: hex representarion of image IV | None,
        if None, the IV is generated

        output:
        (encrypted_binary, encryption_key, image_iv): Tuple with the encrypted binary, the key, and the IV
        """
        message_path, encrypted_message_path = None, None
        try:
            message_path = c_path.create_tmp_file(message)
            encrypted_message_path = c_path.create_tmp_file()

            cmd = [
                self.crypto_cbc,
                '--operation=encrypt',
                '--input-file',
                message_path,
                '--output',
                encrypted_message_path,
                '--key',
                key,
                '--iv',
                iv,
            ]
            run_command(cmd)
            return c_path.load_data_from_file(encrypted_message_path)
        finally:
            if message_path is not None:
                c_path.remove_tmp_file(message_path)
            if encrypted_message_path is not None:
                c_path.remove_tmp_file(encrypted_message_path)
示例#9
0
 def _generate_new_encryption_params_blob(self):
     enc_xml_fname = c_path.store_data_to_temp_file('')
     self.ssd_p.gen_signed_ssd_xml(enc_xml_fname)
     enc_xml = c_path.load_data_from_file(enc_xml_fname)
     os.unlink(enc_xml_fname)
     return enc_xml