blob: d4027e625d037ac2ac107f7bb6983203146893d0 [file] [log] [blame]
David Brown23f91ad2017-05-16 11:38:17 -06001#! /usr/bin/env python3
David Brown1314bf32017-12-20 11:10:55 -07002#
3# Copyright 2017 Linaro Limited
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
David Brown23f91ad2017-05-16 11:38:17 -060016
17import argparse
David Brown1d5bea12017-11-16 15:11:10 -070018import getpass
David Brown23f91ad2017-05-16 11:38:17 -060019from imgtool import keys
20from imgtool import image
21from imgtool import version
22import sys
23
David Brownf88d9f92017-12-06 10:53:35 -070024def get_password(args):
David Brown1d5bea12017-11-16 15:11:10 -070025 if args.password:
26 while True:
27 passwd = getpass.getpass("Enter key passphrase: ")
28 passwd2 = getpass.getpass("Reenter passphrase: ")
29 if passwd == passwd2:
30 break
31 print("Passwords do not match, try again")
32
33 # Password must be bytes, always use UTF-8 for consistent
34 # encoding.
35 return passwd.encode('utf-8')
36 else:
David Brownf88d9f92017-12-06 10:53:35 -070037 return None
38
39def gen_rsa2048(args):
40 passwd = get_password(args)
David Brown1d5bea12017-11-16 15:11:10 -070041 keys.RSA2048.generate().export_private(path=args.key, passwd=passwd)
42
David Brown23f91ad2017-05-16 11:38:17 -060043def gen_ecdsa_p256(args):
David Brownf88d9f92017-12-06 10:53:35 -070044 passwd = get_password(args)
45 keys.ECDSA256P1.generate().export_private(args.key, passwd=passwd)
46
David Brown23f91ad2017-05-16 11:38:17 -060047def gen_ecdsa_p224(args):
48 print("TODO: p-224 not yet implemented")
49
50keygens = {
51 'rsa-2048': gen_rsa2048,
52 'ecdsa-p256': gen_ecdsa_p256,
53 'ecdsa-p224': gen_ecdsa_p224, }
54
55def do_keygen(args):
56 if args.type not in keygens:
57 msg = "Unexpected key type: {}".format(args.type)
58 raise argparse.ArgumentTypeError(msg)
59 keygens[args.type](args)
60
David Brown1d5bea12017-11-16 15:11:10 -070061def load_key(args):
David Brown23f91ad2017-05-16 11:38:17 -060062 key = keys.load(args.key)
David Brown1d5bea12017-11-16 15:11:10 -070063 if key is not None:
64 return key
65 passwd = getpass.getpass("Enter key passphrase: ")
66 passwd = passwd.encode('utf-8')
67 return keys.load(args.key, passwd)
68
69def do_getpub(args):
70 key = load_key(args)
David Brownd36e91a2017-09-01 09:33:00 -060071 if args.lang == 'c':
72 key.emit_c()
73 elif args.lang == 'rust':
74 key.emit_rust()
75 else:
76 msg = "Unsupported language, valid are: c, or rust"
77 raise argparse.ArgumentTypeError(msg)
David Brown23f91ad2017-05-16 11:38:17 -060078
79def do_sign(args):
David Brown23f91ad2017-05-16 11:38:17 -060080 img = image.Image.load(args.infile, version=args.version,
81 header_size=args.header_size,
David Brown2c21f712017-06-08 10:03:42 -060082 included_header=args.included_header,
David Brown23f91ad2017-05-16 11:38:17 -060083 pad=args.pad)
David Brown1d5bea12017-11-16 15:11:10 -070084 key = load_key(args) if args.key else None
David Brown23f91ad2017-05-16 11:38:17 -060085 img.sign(key)
86
87 if args.pad:
88 img.pad_to(args.pad, args.align)
89
90 img.save(args.outfile)
91
92subcmds = {
93 'keygen': do_keygen,
94 'getpub': do_getpub,
95 'sign': do_sign, }
96
97def alignment_value(text):
98 value = int(text)
99 if value not in [1, 2, 4, 8]:
100 msg = "{} must be one of 1, 2, 4 or 8".format(value)
101 raise argparse.ArgumentTypeError(msg)
102 return value
103
104def intparse(text):
105 """Parse a command line argument as an integer.
106
107 Accepts 0x and other prefixes to allow other bases to be used."""
108 return int(text, 0)
109
110def args():
111 parser = argparse.ArgumentParser()
112 subs = parser.add_subparsers(help='subcommand help', dest='subcmd')
113
114 keygenp = subs.add_parser('keygen', help='Generate pub/private keypair')
115 keygenp.add_argument('-k', '--key', metavar='filename', required=True)
116 keygenp.add_argument('-t', '--type', metavar='type',
Fabio Utziga8f06aa2017-10-16 07:14:26 -0200117 choices=keygens.keys(), required=True)
David Brown1d5bea12017-11-16 15:11:10 -0700118 keygenp.add_argument('-p', '--password', default=False, action='store_true',
119 help='Prompt for password to protect key')
David Brown23f91ad2017-05-16 11:38:17 -0600120
121 getpub = subs.add_parser('getpub', help='Get public key from keypair')
122 getpub.add_argument('-k', '--key', metavar='filename', required=True)
David Brownd36e91a2017-09-01 09:33:00 -0600123 getpub.add_argument('-l', '--lang', metavar='lang', default='c')
David Brown23f91ad2017-05-16 11:38:17 -0600124
David Brown5a181022018-03-15 16:56:49 -0600125 sign = subs.add_parser('sign',
126 help='Sign an image with a private key (or create an unsigned image)',
127 aliases=['create'])
128 sign.add_argument('-k', '--key', metavar='filename',
129 help='private key to sign, or no key for an unsigned image')
David Brown23f91ad2017-05-16 11:38:17 -0600130 sign.add_argument("--align", type=alignment_value, required=True)
131 sign.add_argument("-v", "--version", type=version.decode_version, required=True)
132 sign.add_argument("-H", "--header-size", type=intparse, required=True)
David Brown2c21f712017-06-08 10:03:42 -0600133 sign.add_argument("--included-header", default=False, action='store_true',
134 help='Image has gap for header')
David Brown23f91ad2017-05-16 11:38:17 -0600135 sign.add_argument("--pad", type=intparse,
136 help='Pad image to this many bytes, adding trailer magic')
David Brown23f91ad2017-05-16 11:38:17 -0600137 sign.add_argument("infile")
138 sign.add_argument("outfile")
139
140 args = parser.parse_args()
141 if args.subcmd is None:
142 print('Must specify a subcommand', file=sys.stderr)
143 sys.exit(1)
144
145 subcmds[args.subcmd](args)
146
147if __name__ == '__main__':
148 args()