From 9c2150d1eba85bc27c83b6330e8d59ba2e56c7ad Mon Sep 17 00:00:00 2001 From: Ross Younger Date: Thu, 23 Feb 2023 20:16:03 +1300 Subject: [PATCH] imgtool: option to read key passphrase from environment In a CI chain it is sometimes useful to automatically sign an image (e.g. once qualification tests have passed). Naturally, it is important to protect the private key in such cases. This patch provides that capability. The private key should be stored in a passphrase-protected PEM file in the usual way. The CI provider should be configured, through its secrets mechanism, to inject the passphrase as an environment variable of your choice. A new imgtool option is then used to specify that variable name, e.g.: imgtool --password-env=DEV_KEY_PASSPHRASE sign infile.hex outfile.hex This option also works for the other verbs that load keys (getpub, getpriv, imgfile). Note that argument ordering is critical. --password-env must appear before the verb! --- scripts/imgtool/main.py | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/scripts/imgtool/main.py b/scripts/imgtool/main.py index a246beac72..f526ef79c1 100755 --- a/scripts/imgtool/main.py +++ b/scripts/imgtool/main.py @@ -21,6 +21,7 @@ import click import getpass import imgtool.keys as keys +import os import sys import base64 from imgtool import image, imgtool_version @@ -89,6 +90,10 @@ def load_key(keyfile): key = keys.load(keyfile) if key is not None: return key + pwenv = click.get_current_context().obj.get('password_env') + if pwenv: + click.echo('Using key passphrase from environment') + return keys.load(keyfile, os.environ.get(pwenv, '').encode('utf-8')) passwd = getpass.getpass("Enter key passphrase: ").encode('utf-8') return keys.load(keyfile, passwd) @@ -457,8 +462,11 @@ def version(): @click.command(cls=AliasesGroup, context_settings=dict(help_option_names=['-h', '--help'])) -def imgtool(): - pass +@click.option('--password-env', type=str, default=None, help='Specifies an environment variable to read key passwords from') +@click.pass_context +def imgtool(ctx, password_env): + ctx.ensure_object(dict) + ctx.obj['password_env'] = password_env imgtool.add_command(keygen)