| 1 |
#!/usr/bin/env python |
| 2 |
|
| 3 |
# Copyright New York University and the in-toto contributors |
| 4 |
# SPDX-License-Identifier: Apache-2.0 |
| 5 |
|
| 6 |
""" |
| 7 |
<Program Name> |
| 8 |
in_toto_sign.py |
| 9 |
|
| 10 |
<Author> |
| 11 |
Sachit Malik <[email protected]> |
| 12 |
Lukas Puehringer <[email protected]> |
| 13 |
|
| 14 |
<Started> |
| 15 |
June 13, 2017 |
| 16 |
|
| 17 |
<Copyright> |
| 18 |
See LICENSE for licensing information. |
| 19 |
|
| 20 |
<Purpose> |
| 21 |
Provides command line interface to sign in-toto link or layout metadata |
| 22 |
or to verify its signatures. |
| 23 |
|
| 24 |
""" |
| 25 |
import argparse |
| 26 |
import logging |
| 27 |
import sys |
| 28 |
|
| 29 |
import securesystemslib.exceptions |
| 30 |
import securesystemslib.formats |
| 31 |
from securesystemslib import interface |
| 32 |
from securesystemslib.gpg import functions as gpg_interface |
| 33 |
from securesystemslib.signer import SSlibSigner |
| 34 |
|
| 35 |
from in_toto import ( |
| 36 |
KEY_TYPE_ECDSA, |
| 37 |
KEY_TYPE_ED25519, |
| 38 |
KEY_TYPE_RSA, |
| 39 |
SUPPORTED_KEY_TYPES, |
| 40 |
__version__, |
| 41 |
exceptions, |
| 42 |
) |
| 43 |
from in_toto.common_args import ( |
| 44 |
GPG_HOME_ARGS, |
| 45 |
GPG_HOME_KWARGS, |
| 46 |
QUIET_ARGS, |
| 47 |
QUIET_KWARGS, |
| 48 |
VERBOSE_ARGS, |
| 49 |
VERBOSE_KWARGS, |
| 50 |
sort_action_groups, |
| 51 |
title_case_action_groups, |
| 52 |
) |
| 53 |
from in_toto.models._signer import GPGSigner |
| 54 |
from in_toto.models.link import FILENAME_FORMAT |
| 55 |
from in_toto.models.metadata import Metadata |
| 56 |
|
| 57 |
# Command line interfaces should use in_toto base logger (c.f. in_toto.log) |
| 58 |
LOG = logging.getLogger("in_toto") |
| 59 |
|
| 60 |
|
| 61 |
def _sign_and_dump_metadata(metadata, args): |
| 62 |
""" |
| 63 |
<Purpose> |
| 64 |
Internal method to sign link or layout metadata and dump it to disk. |
| 65 |
|
| 66 |
<Arguments> |
| 67 |
metadata: |
| 68 |
Metadata object (contains Link or Layout object) |
| 69 |
args: |
| 70 |
see argparser |
| 71 |
|
| 72 |
<Exceptions> |
| 73 |
SystemExit(0) if signing is successful |
| 74 |
SystemExit(2) if any exception occurs |
| 75 |
|
| 76 |
""" |
| 77 |
|
| 78 |
try: |
| 79 |
if not args.append: |
| 80 |
metadata.signatures = [] |
| 81 |
|
| 82 |
signature = None |
| 83 |
# If the cli tool was called with `--gpg [KEYID ...]` `args.gpg` is |
| 84 |
# a list (not None) and we will try to sign with gpg. |
| 85 |
# If `--gpg-home` was not set, args.gpg_home is None and the signer tries |
| 86 |
# to use the default gpg keyring. |
| 87 |
if args.gpg is not None: |
| 88 |
# If `--gpg` was passed without argument we sign with the default key |
| 89 |
# Excluded so that coverage does not vary in different test environments |
| 90 |
if len(args.gpg) == 0: # pragma: no cover |
| 91 |
signature = metadata.create_signature( |
| 92 |
GPGSigner(None, homedir=args.gpg_home) |
| 93 |
) |
| 94 |
|
| 95 |
# Otherwise we sign with each passed keyid |
| 96 |
for keyid in args.gpg: |
| 97 |
securesystemslib.formats.KEYID_SCHEMA.check_match(keyid) |
| 98 |
signature = metadata.create_signature( |
| 99 |
GPGSigner(keyid, homedir=args.gpg_home) |
| 100 |
) |
| 101 |
|
| 102 |
# Alternatively we iterate over passed private key paths `--key KEYPATH |
| 103 |
# ...` load the corresponding key from disk and sign with it |
| 104 |
elif args.key is not None: # pragma: no branch |
| 105 |
if args.key_type is None: |
| 106 |
args.key_type = [KEY_TYPE_RSA] * len(args.key) |
| 107 |
|
| 108 |
if len(args.key_type) != len(args.key): |
| 109 |
raise securesystemslib.exceptions.FormatError( |
| 110 |
"number of key_types should match with the number" |
| 111 |
" of keys specified" |
| 112 |
) |
| 113 |
|
| 114 |
for idx, key_path in enumerate(args.key): |
| 115 |
key = interface.import_privatekey_from_file( |
| 116 |
key_path, key_type=args.key_type[idx], prompt=args.prompt |
| 117 |
) |
| 118 |
signature = metadata.create_signature(SSlibSigner(key)) |
| 119 |
|
| 120 |
payload = metadata.get_payload() |
| 121 |
_type = payload.type_ |
| 122 |
|
| 123 |
# If `--output` was specified we store the signed link or layout metadata |
| 124 |
# to that location no matter what |
| 125 |
if args.output: |
| 126 |
out_path = args.output |
| 127 |
|
| 128 |
# Otherwise, in case of links, we build the filename using the link/step |
| 129 |
# name and the keyid of the created signature (there is only one for links) |
| 130 |
elif _type == "link": |
| 131 |
keyid = signature.keyid |
| 132 |
out_path = FILENAME_FORMAT.format( |
| 133 |
step_name=payload.name, keyid=keyid |
| 134 |
) |
| 135 |
|
| 136 |
# In case of layouts we just override the input file. |
| 137 |
elif _type == "layout": # pragma: no branch |
| 138 |
out_path = args.file |
| 139 |
|
| 140 |
LOG.info("Dumping {0} to '{1}'...".format(_type, out_path)) |
| 141 |
|
| 142 |
metadata.dump(out_path) |
| 143 |
sys.exit(0) |
| 144 |
|
| 145 |
except Exception as e: |
| 146 |
LOG.error("The following error occurred while signing: " "{}".format(e)) |
| 147 |
sys.exit(2) |
| 148 |
|
| 149 |
|
| 150 |
def _verify_metadata(metadata, args): |
| 151 |
""" |
| 152 |
<Purpose> |
| 153 |
Internal method to verify link or layout signatures. |
| 154 |
|
| 155 |
<Arguments> |
| 156 |
metadata: |
| 157 |
Metadata object (contains Link or Layout object) |
| 158 |
args: |
| 159 |
see argparser |
| 160 |
|
| 161 |
<Exceptions> |
| 162 |
SystemExit(0) if verification passes |
| 163 |
SystemExit(1) if verification fails |
| 164 |
SystemExit(2) if any exception occurs |
| 165 |
|
| 166 |
""" |
| 167 |
try: |
| 168 |
# Load pubkeys from disk .... |
| 169 |
if args.key is not None: |
| 170 |
pub_key_dict = interface.import_publickeys_from_file( |
| 171 |
args.key, args.key_type |
| 172 |
) |
| 173 |
|
| 174 |
# ... or from gpg keyring |
| 175 |
elif args.gpg is not None: # pragma: no branch |
| 176 |
pub_key_dict = gpg_interface.export_pubkeys(args.gpg, args.gpg_home) |
| 177 |
|
| 178 |
for keyid, verification_key in pub_key_dict.items(): |
| 179 |
metadata.verify_signature(verification_key) |
| 180 |
LOG.info( |
| 181 |
"Signature verification passed for keyid '{}'".format(keyid) |
| 182 |
) |
| 183 |
|
| 184 |
sys.exit(0) |
| 185 |
|
| 186 |
except exceptions.SignatureVerificationError as e: |
| 187 |
LOG.error("Signature verification failed: {}".format(e)) |
| 188 |
sys.exit(1) |
| 189 |
|
| 190 |
except Exception as e: |
| 191 |
LOG.error( |
| 192 |
"The following error occurred while verifying signatures: " |
| 193 |
"{}".format(e) |
| 194 |
) |
| 195 |
sys.exit(2) |
| 196 |
|
| 197 |
|
| 198 |
def _load_metadata(file_path): |
| 199 |
""" |
| 200 |
<Purpose> |
| 201 |
Loads Metadata (link or layout metadata) file from disk |
| 202 |
|
| 203 |
<Arguments> |
| 204 |
file_path: |
| 205 |
path to link or layout metadata file |
| 206 |
|
| 207 |
<Exceptions> |
| 208 |
SystemExit(2) if any exception occurs |
| 209 |
|
| 210 |
<Returns> |
| 211 |
in-toto Metadata object (contains Link or Layout object) |
| 212 |
|
| 213 |
""" |
| 214 |
try: |
| 215 |
return Metadata.load(file_path) |
| 216 |
|
| 217 |
except Exception as e: |
| 218 |
LOG.error( |
| 219 |
"The following error occurred while loading the file '{}': " |
| 220 |
"{}".format(file_path, e) |
| 221 |
) |
| 222 |
sys.exit(2) |
| 223 |
|
| 224 |
|
| 225 |
def create_parser(): |
| 226 |
"""Create and return configured ArgumentParser instance.""" |
| 227 |
parser = argparse.ArgumentParser( |
| 228 |
formatter_class=argparse.RawDescriptionHelpFormatter, |
| 229 |
description=""" |
| 230 |
in-toto-sign provides a command line interface to sign in-toto link or layout |
| 231 |
metadata or verify their signatures, with options to: |
| 232 |
|
| 233 |
* replace (default) or add signatures: |
| 234 |
|
| 235 |
+ layout metadata can be signed by multiple keys at once, |
| 236 |
+ link metadata can only be signed by one key at a time. |
| 237 |
|
| 238 |
* write signed metadata to a specified path. If no output path is specified, |
| 239 |
|
| 240 |
+ layout metadata is written to the path of the input file, |
| 241 |
+ link metadata is written to '<name>.<keyid prefix>.link'. |
| 242 |
|
| 243 |
* verify signatures |
| 244 |
|
| 245 |
in-toto-sign is useful to re-sign metadata (e.g. when changing keys), or to |
| 246 |
sign unsigned links (e.g. generated with 'in-toto-mock'). For layouts, it is |
| 247 |
useful to append signatures in case threshold signing of layouts is necessary. |
| 248 |
|
| 249 |
It returns a non-zero value on failure and zero otherwise.""", |
| 250 |
) |
| 251 |
|
| 252 |
parser.epilog = """EXAMPLE USAGE |
| 253 |
|
| 254 |
Sign 'unsigned.layout' with two keys and write it to 'root.layout'. |
| 255 |
|
| 256 |
{prog} -f unsigned.layout -k priv_key1 priv_key2 -o root.layout |
| 257 |
|
| 258 |
|
| 259 |
Replace signature in link file and write to default filename, i.e. |
| 260 |
'package.<priv_key keyid prefix>.link'. |
| 261 |
|
| 262 |
{prog} -f package.2f89b927.link -k priv_key |
| 263 |
|
| 264 |
|
| 265 |
Verify layout signed with 3 keys. |
| 266 |
|
| 267 |
{prog} -f root.layout -k pub_key0 pub_key1 pub_key2 --verify |
| 268 |
|
| 269 |
|
| 270 |
Sign layout with default gpg key in default gpg keyring. |
| 271 |
|
| 272 |
{prog} -f root.layout --gpg |
| 273 |
|
| 274 |
|
| 275 |
Verify layout with a gpg key identified by keyid '...439F3C2'. |
| 276 |
|
| 277 |
{prog} -f root.layout --verify \\ |
| 278 |
--gpg 3BF8135765A07E21BD12BF89A5627F6BF439F3C2 |
| 279 |
|
| 280 |
""".format( |
| 281 |
prog=parser.prog |
| 282 |
) |
| 283 |
|
| 284 |
named_args = parser.add_argument_group("required named arguments") |
| 285 |
|
| 286 |
named_args.add_argument( |
| 287 |
"-f", |
| 288 |
"--file", |
| 289 |
type=str, |
| 290 |
required=True, |
| 291 |
metavar="<path>", |
| 292 |
help=("path to link or layout file to be signed or verified."), |
| 293 |
) |
| 294 |
|
| 295 |
parser.add_argument( |
| 296 |
"-k", |
| 297 |
"--key", |
| 298 |
nargs="+", |
| 299 |
metavar="<path>", |
| 300 |
help=( |
| 301 |
"paths to key files, used to sign the passed link or layout metadata" |
| 302 |
" or to verify its signatures. See '--key-type' for available formats." |
| 303 |
), |
| 304 |
) |
| 305 |
|
| 306 |
parser.add_argument( |
| 307 |
"-t", |
| 308 |
"--key-type", |
| 309 |
dest="key_type", |
| 310 |
type=str, |
| 311 |
choices=SUPPORTED_KEY_TYPES, |
| 312 |
nargs="+", |
| 313 |
help=( |
| 314 |
"types of keys specified by the '--key' option. '{rsa}' keys are" |
| 315 |
" expected in a 'PEM' format. '{ed25519}' and '{ecdsa} are expected in a" |
| 316 |
" custom 'securesystemslib/json' format. If multiple keys are passed via" |
| 317 |
" '--key' the same amount of key types must be passed. Key" |
| 318 |
" types are then associated with keys by index. If '--key-type' is" |
| 319 |
" omitted, the default of '{rsa}' is used for all keys.".format( |
| 320 |
rsa=KEY_TYPE_RSA, ed25519=KEY_TYPE_ED25519, ecdsa=KEY_TYPE_ECDSA |
| 321 |
) |
| 322 |
), |
| 323 |
) |
| 324 |
|
| 325 |
parser.add_argument( |
| 326 |
"-p", |
| 327 |
"--prompt", |
| 328 |
action="store_true", |
| 329 |
help="prompt for signing key decryption password", |
| 330 |
) |
| 331 |
|
| 332 |
parser.add_argument( |
| 333 |
"-g", |
| 334 |
"--gpg", |
| 335 |
nargs="*", |
| 336 |
metavar="<id>", |
| 337 |
help=( |
| 338 |
"GPG keyids used to sign the passed link or layout metadata or to verify" |
| 339 |
" its signatures. If passed without keyids, the default GPG key is" |
| 340 |
" used." |
| 341 |
), |
| 342 |
) |
| 343 |
|
| 344 |
parser.add_argument(*GPG_HOME_ARGS, **GPG_HOME_KWARGS) |
| 345 |
|
| 346 |
# Only when signing |
| 347 |
parser.add_argument( |
| 348 |
"-o", |
| 349 |
"--output", |
| 350 |
type=str, |
| 351 |
metavar="<path>", |
| 352 |
help=( |
| 353 |
"path to location where the metadata file is stored after signing. If" |
| 354 |
" not passed, layout metadata is written to the path of the input file" |
| 355 |
" and link metadata is written to '<name>.<keyid prefix>.link'" |
| 356 |
), |
| 357 |
) |
| 358 |
|
| 359 |
# Only when signing |
| 360 |
parser.add_argument( |
| 361 |
"-a", |
| 362 |
"--append", |
| 363 |
action="store_true", |
| 364 |
help=( |
| 365 |
"add signatures rather than replacing existing signatures. This option" |
| 366 |
" is only availabe for layout metdata." |
| 367 |
), |
| 368 |
) |
| 369 |
|
| 370 |
parser.add_argument( |
| 371 |
"--verify", |
| 372 |
action="store_true", |
| 373 |
help="verify signatures of passed link or layout metadata using the" |
| 374 |
" public keys passed via '--key' and/or '--gpg' options.", |
| 375 |
) |
| 376 |
|
| 377 |
verbosity_args = parser.add_mutually_exclusive_group(required=False) |
| 378 |
verbosity_args.add_argument(*VERBOSE_ARGS, **VERBOSE_KWARGS) |
| 379 |
verbosity_args.add_argument(*QUIET_ARGS, **QUIET_KWARGS) |
| 380 |
|
| 381 |
parser.add_argument( |
| 382 |
"--version", |
| 383 |
action="version", |
| 384 |
version="{} {}".format(parser.prog, __version__), |
| 385 |
) |
| 386 |
|
| 387 |
title_case_action_groups(parser) |
| 388 |
sort_action_groups(parser) |
| 389 |
|
| 390 |
return parser |
| 391 |
|
| 392 |
|
| 393 |
def main(): |
| 394 |
"""Parse arguments, load link or layout metadata file and either sign |
| 395 |
metadata file or verify its signatures.""" |
| 396 |
|
| 397 |
parser = create_parser() |
| 398 |
args = parser.parse_args() |
| 399 |
|
| 400 |
LOG.setLevelVerboseOrQuiet(args.verbose, args.quiet) |
| 401 |
|
| 402 |
# Additional argparse sanitization |
| 403 |
# NOTE: This tool is starting to have many inter-dependent argument |
| 404 |
# restrictions. Maybe we should make it less sophisticated at some point. |
| 405 |
if args.verify and (args.append or args.output): |
| 406 |
parser.print_help() |
| 407 |
parser.error( |
| 408 |
"conflicting arguments: don't specify any of" |
| 409 |
" 'append' or 'output' when verifying signatures" |
| 410 |
) |
| 411 |
|
| 412 |
# Regular signing and GPG signing are mutually exclusive |
| 413 |
if (args.key is None) == (args.gpg is None): |
| 414 |
parser.print_help() |
| 415 |
parser.error( |
| 416 |
"wrong arguments: specify either '--key PATH [PATH ...]'" |
| 417 |
" or '--gpg [KEYID [KEYID ...]]'" |
| 418 |
) |
| 419 |
|
| 420 |
# For gpg verification we must specify a keyid (no default key is loaded) |
| 421 |
if args.verify and args.gpg is not None and len(args.gpg) < 1: |
| 422 |
parser.print_help() |
| 423 |
parser.error( |
| 424 |
"missing arguments: specify at least one keyid for GPG" |
| 425 |
" signature verification ('--gpg KEYID ...')" |
| 426 |
) |
| 427 |
|
| 428 |
metadata = _load_metadata(args.file) |
| 429 |
|
| 430 |
# Specific command line argument restrictions if we deal with links |
| 431 |
payload = metadata.get_payload() |
| 432 |
if payload.type_ == "link": |
| 433 |
# Above we check that it's either `--key ...` or `--gpg ...` |
| 434 |
# Here we check that it is not more than one in each case when dealing |
| 435 |
# with links |
| 436 |
link_error_message = ( |
| 437 |
"link metadata is associated with a" |
| 438 |
" single functionary and is usually namespaced accordingly:" |
| 439 |
" '<name>.<keyid prefix>.link'." |
| 440 |
) |
| 441 |
|
| 442 |
if (args.key is not None and len(args.key) > 1) or ( |
| 443 |
args.gpg is not None and len(args.gpg) > 1 |
| 444 |
): |
| 445 |
parser.print_help() |
| 446 |
parser.error( |
| 447 |
"too many arguments: {} Hence signing Link metadata" |
| 448 |
" with multiple keys is not allowed.".format(link_error_message) |
| 449 |
) |
| 450 |
|
| 451 |
if args.append: |
| 452 |
parser.print_help() |
| 453 |
parser.error( |
| 454 |
"wrong arguments: {}. Hence adding signatures to" |
| 455 |
" existing signatures on link metadata is not allowed.".format( |
| 456 |
link_error_message |
| 457 |
) |
| 458 |
) |
| 459 |
|
| 460 |
if args.verify: |
| 461 |
_verify_metadata(metadata, args) |
| 462 |
|
| 463 |
else: |
| 464 |
_sign_and_dump_metadata(metadata, args) |
| 465 |
|
| 466 |
|
| 467 |
if __name__ == "__main__": |
| 468 |
main() |