1#!/usr/bin/env python3 2# Copyright 2024 The ChromiumOS Authors 3# Use of this source code is governed by a BSD-style license that can be 4# found in the LICENSE file. 5 6"""Generates cloud config files to be used by apksigner for signing. 7 81. Generates base pkcs#11 config file. 9 10Usage: generate_android_cloud_config.py [ 11 --output_dir <output directory for config file> 12 ] 13""" 14 15from argparse import ArgumentParser 16from argparse import Namespace 17import logging 18import os 19from pathlib import Path 20import sys 21from typing import Sequence 22 23 24CONFIG_FILE_NAME = "pkcs11_java.cfg" 25PKCS11_MODULE_PATH = "PKCS11_MODULE_PATH" 26 27 28def _parse_flags(argv: Sequence[str]) -> Namespace: 29 """The function passed to absl.app.run to parse flags. 30 31 :param argv: A list of input arguments. 32 33 :return parsed input namespace. 34 """ 35 parser = ArgumentParser( 36 description="Generate config files to be used for pkcs#11 signing using gcloud." 37 ) 38 39 parser.add_argument( 40 "--output_dir", 41 "-o", 42 type=str, 43 help="Output directory location where files will be " 44 "generated. This would default to input directory " 45 "if nothing is provided.", 46 default=os.getcwd(), 47 ) 48 return parser.parse_args(argv[1:]) 49 50 51def generate_config_file(output_dir: str) -> None: 52 """ 53 Generates a static config file with name, description, library path and 54 slotListIndex. 55 """ 56 config_file_name = os.path.join(output_dir, CONFIG_FILE_NAME) 57 58 try: 59 lib_path = os.getenv(PKCS11_MODULE_PATH) 60 with open(config_file_name, "w") as file: 61 file.write("name = libkmsp11\n") 62 file.write("description = Google Cloud KMS PKCS11 Library\n") 63 file.write(f"library = {lib_path}\n") 64 file.write("slotListIndex = 0\n") 65 except OSError as ex: 66 logging.error("Unable to open create file due to exception: ", ex) 67 sys.exit(1) 68 69 70def _validate(args: Namespace) -> str: 71 lib_path = os.getenv(PKCS11_MODULE_PATH) 72 if not lib_path: 73 logging.error("Please set PKCS11_MODULE_PATH before continuing.") 74 sys.exit(1) 75 76 return args.output_dir 77 78 79def main(argv) -> None: 80 args = _parse_flags(argv) 81 output_dir = _validate(args) 82 83 # Generate the pkcs11 config file. 84 generate_config_file(output_dir=output_dir) 85 86 87if __name__ == "__main__": 88 sys.exit(main(sys.argv)) 89