Debian Codegraph @

in_toto/runlib.py

raw
1 # Copyright New York University and the in-toto contributors
2 # SPDX-License-Identifier: Apache-2.0
3
4 """
5 <Program Name>
6 runlib.py
7
8 <Author>
9 Lukas Puehringer <[email protected]>
10
11 <Started>
12 June 27, 2016
13
14 <Copyright>
15 See LICENSE for licensing information.
16
17 <Purpose>
18 Provides a wrapper for any command of the software supply chain.
19
20 The wrapper performs the following tasks which are implemented in this
21 library.
22
23 - Record state of material (files the command is executed on)
24 - Execute command
25 - Capture stdout/stderr/return value of the executed command
26 - Record state of product (files after the command was executed)
27 - Return Metadata containing a Link object which can be can be signed
28 and stored to disk
29 """
30 import glob
31 import io
32 import logging
33 import os
34 import subprocess # nosec
35 import sys
36 import tempfile
37 import time
38 from collections import defaultdict
39
40 import securesystemslib.exceptions
41 import securesystemslib.formats
42 import securesystemslib.gpg
43 import securesystemslib.hash
44 from securesystemslib.signer import Signature, SSlibSigner
45
46 import in_toto.exceptions
47 import in_toto.settings
48 from in_toto.models._signer import GPGSigner
49 from in_toto.models.link import (
50 FILENAME_FORMAT,
51 FILENAME_FORMAT_SHORT,
52 UNFINISHED_FILENAME_FORMAT,
53 UNFINISHED_FILENAME_FORMAT_GLOB,
54 )
55 from in_toto.models.metadata import Envelope, Metablock, Metadata
56 from in_toto.resolver import (
57 RESOLVER_FOR_URI_SCHEME,
58 FileResolver,
59 OSTreeResolver,
60 Resolver,
61 )
62
63 # Inherits from in_toto base logger (c.f. in_toto.log)
64 LOG = logging.getLogger(__name__)
65
66
67 def record_artifacts_as_dict(
68 artifacts,
69 exclude_patterns=None,
70 base_path=None,
71 follow_symlink_dirs=False,
72 normalize_line_endings=False,
73 lstrip_paths=None,
74 ):
75 """
76 <Purpose>
77 Hashes each file in the passed path list. If the path list contains
78 paths to directories the directory tree(s) are traversed.
79
80 The files a link command is executed on are called materials.
81 The files that result form a link command execution are called
82 products.
83
84 Paths are normalized for matching and storing by left stripping "./"
85
86 NOTE on exclude patterns:
87 - Uses PathSpec to compile gitignore-style patterns, making use of the
88 GitWildMatchPattern class (registered as 'gitwildmatch')
89
90 - Patterns are checked for match against the full path relative to each
91 path passed in the artifacts list
92
93 - If a directory is excluded, all its files and subdirectories are also
94 excluded
95
96 - How it differs from .gitignore
97 - No need to escape #
98 - No ignoring of trailing spaces
99 - No general negation with exclamation mark !
100 - No special treatment of slash /
101 - No special treatment of consecutive asterisks **
102
103 - Exclude patterns are likely to become command line arguments or part of
104 a config file.
105
106 <Arguments>
107 artifacts:
108 A list of file or directory paths used as materials or products for
109 the link command.
110
111 exclude_patterns: (optional)
112 Artifacts matched by the pattern are excluded from the result.
113 Exclude patterns can be passed as argument or specified via
114 ARTIFACT_EXCLUDE_PATTERNS setting (see `in_toto.settings`).
115 If passed, patterns specified via settings are overriden.
116
117 base_path: (optional)
118 Change to base_path and record artifacts relative from there.
119 If not passed, current working directory is used as base_path.
120 NOTE: The base_path part of the recorded artifact is not included
121 in the returned paths.
122
123 follow_symlink_dirs: (optional)
124 Follow symlinked dirs if the linked dir exists (default is False).
125 The recorded path contains the symlink name, not the resolved name.
126 NOTE: This parameter toggles following linked directories only,
127 linked files are always recorded, independently of this parameter.
128 NOTE: Beware of infinite recursions that can occur if a symlink
129 points to a parent directory or itself.
130
131 normalize_line_endings: (optional)
132 If True, replaces windows and mac line endings with unix line
133 endings before hashing the content of the passed files, for
134 cross-platform support.
135
136 lstrip_paths: (optional)
137 If a prefix path is passed, the prefix is left stripped from
138 the path of every artifact that contains the prefix.
139
140 <Exceptions>
141 OSError: cannot change to base path directory.
142 ValueError: arguments are malformed.
143
144 <Side Effects>
145 Calls functions to generate cryptographic hashes.
146
147 <Returns>
148 A dictionary with file paths as keys and the files' hashes as values.
149
150 """
151 artifact_hashes = {}
152
153 if not artifacts:
154 return artifact_hashes
155
156 if not base_path:
157 base_path = in_toto.settings.ARTIFACT_BASE_PATH
158
159 if not exclude_patterns:
160 exclude_patterns = in_toto.settings.ARTIFACT_EXCLUDE_PATTERNS
161
162 # Configure resolver with resolver specific arguments
163 # FIXME: This should happen closer to the user boundary, where
164 # resolver-specific config arguments are passed and global state is managed.
165 RESOLVER_FOR_URI_SCHEME[FileResolver.SCHEME] = FileResolver(
166 exclude_patterns,
167 base_path,
168 follow_symlink_dirs,
169 normalize_line_endings,
170 lstrip_paths,
171 )
172
173 # Configure resolver for OSTree
174 RESOLVER_FOR_URI_SCHEME[OSTreeResolver.SCHEME] = OSTreeResolver(base_path)
175
176 # Aggregate artifacts per resolver
177 resolver_for_uris = defaultdict(list)
178 for artifact in artifacts:
179 resolver = Resolver.for_uri(artifact)
180 resolver_for_uris[resolver].append(artifact)
181
182 # Hash artifacts in a batch per resolver
183 # FIXME: The behavior may change if we hash each artifact individually,
184 # because the left-prefix duplicate check in FileResolver only works for the
185 # artifacts hashed in one batch.
186 for resolver, uris in resolver_for_uris.items():
187 artifact_hashes.update(resolver.hash_artifacts(uris))
188
189 # Clear resolvers to not preserve global state change beyond this function.
190 # FIXME: This also clears resolver registered elsewhere. For now we
191 # assume that we only modify RESOLVER_FOR_URI_SCHEME in this function.
192 RESOLVER_FOR_URI_SCHEME.clear()
193
194 return artifact_hashes
195
196
197 def _subprocess_run_duplicate_streams(cmd, timeout):
198 """Helper to run subprocess and both print and capture standards streams.
199
200 Caveat:
201 * Might behave unexpectedly with interactive commands.
202 * Might not duplicate output in real time, if the command buffers it (see
203 e.g. `print("foo")` vs. `print("foo", flush=True)`).
204 * Possible race condition on Windows when removing temporary files.
205
206 """
207 # Use temporary files as targets for child process standard stream redirects
208 # They seem to work better (i.e. do not hang) than pipes, when using
209 # interactive commands like `vi`.
210 stdout_fd, stdout_name = tempfile.mkstemp()
211 stderr_fd, stderr_name = tempfile.mkstemp()
212 try:
213 with io.open( # pylint: disable=unspecified-encoding
214 stdout_name, "r"
215 ) as stdout_reader, os.fdopen( # pylint: disable=unspecified-encoding
216 stdout_fd, "w"
217 ) as stdout_writer, io.open( # pylint: disable=unspecified-encoding
218 stderr_name, "r"
219 ) as stderr_reader, os.fdopen(
220 stderr_fd, "w"
221 ) as stderr_writer:
222 # Store stream results in mutable dict to update it inside nested helper
223 _std = {"out": "", "err": ""}
224
225 def _duplicate_streams():
226 """Helper to read from child process standard streams, write their
227 contents to parent process standard streams, and build up return values
228 for outer function.
229 """
230 # Read until EOF but at most `io.DEFAULT_BUFFER_SIZE` bytes per call.
231 # Reading and writing in reasonably sized chunks prevents us from
232 # subverting a timeout, due to being busy for too long or indefinitely.
233 stdout_part = stdout_reader.read(io.DEFAULT_BUFFER_SIZE)
234 stderr_part = stderr_reader.read(io.DEFAULT_BUFFER_SIZE)
235 sys.stdout.write(stdout_part)
236 sys.stderr.write(stderr_part)
237 sys.stdout.flush()
238 sys.stderr.flush()
239 _std["out"] += stdout_part
240 _std["err"] += stderr_part
241
242 # Start child process, writing its standard streams to temporary files
243 proc = subprocess.Popen( # pylint: disable=consider-using-with # nosec
244 cmd,
245 stdout=stdout_writer,
246 stderr=stderr_writer,
247 universal_newlines=True,
248 )
249 proc_start_time = time.time()
250
251 # Duplicate streams until the process exits (or times out)
252 while proc.poll() is None:
253 # Time out as Python's `subprocess.run` would do it
254 if (
255 timeout is not None
256 and time.time() > proc_start_time + timeout
257 ):
258 proc.kill()
259 proc.wait()
260 raise subprocess.TimeoutExpired(cmd, timeout)
261
262 _duplicate_streams()
263
264 # Read/write once more to grab everything that the process wrote between
265 # our last read in the loop and exiting, i.e. breaking the loop.
266 _duplicate_streams()
267
268 finally:
269 # The work is done or was interrupted, the temp files can be removed
270 os.remove(stdout_name)
271 os.remove(stderr_name)
272
273 # Return process exit code and captured streams
274 return proc.poll(), _std["out"], _std["err"]
275
276
277 def execute_link(link_cmd_args, record_streams):
278 """
279 <Purpose>
280 Executes the passed command plus arguments in a subprocess and returns
281 the return value of the executed command. If the specified standard output
282 and standard error of the command are recorded and also returned to the
283 caller.
284
285 <Arguments>
286 link_cmd_args:
287 A list where the first element is a command and the remaining
288 elements are arguments passed to that command.
289 record_streams:
290 A bool that specifies whether to redirect standard output and
291 and standard error to a temporary file which is returned to the
292 caller (True) or not (False).
293
294 <Exceptions>
295 OSError:
296 The given command is not present or non-executable
297
298 subprocess.TimeoutExpired:
299 The execution of the given command times (see
300 in_toto.settings.LINK_CMD_EXEC_TIMEOUT).
301
302 <Side Effects>
303 Executes passed command in a subprocess and redirects stdout and stderr
304 if specified.
305
306 <Returns>
307 - A dictionary containing standard output and standard error of the
308 executed command, called by-products.
309 Note: If record_streams is False, the dict values are empty strings.
310 - The return value of the executed command.
311 """
312 if record_streams:
313 return_code, stdout_str, stderr_str = _subprocess_run_duplicate_streams(
314 link_cmd_args, timeout=float(in_toto.settings.LINK_CMD_EXEC_TIMEOUT)
315 )
316
317 else:
318 process = subprocess.run(
319 link_cmd_args,
320 check=False, # nosec
321 timeout=float(in_toto.settings.LINK_CMD_EXEC_TIMEOUT),
322 stdout=subprocess.DEVNULL,
323 stderr=subprocess.DEVNULL,
324 )
325 stdout_str = stderr_str = ""
326 return_code = process.returncode
327
328 return {
329 "stdout": stdout_str,
330 "stderr": stderr_str,
331 "return-value": return_code,
332 }
333
334
335 def in_toto_mock(name, link_cmd_args, use_dsse=False):
336 """
337 <Purpose>
338 in_toto_run with defaults
339 - Records materials and products in current directory
340 - Does not sign resulting link file
341 - Stores resulting link file under "<name>.link"
342
343 <Arguments>
344 name:
345 A unique name to relate mock link metadata with a step or
346 inspection defined in the layout.
347 link_cmd_args:
348 A list where the first element is a command and the remaining
349 elements are arguments passed to that command.
350 use_dsse (optional):
351 A boolean indicating if DSSE should be used to generate metadata.
352
353 <Exceptions>
354 None.
355
356 <Side Effects>
357 Writes newly created link metadata file to disk using the filename scheme
358 from link.FILENAME_FORMAT_SHORT
359
360 <Returns>
361 Newly created Metadata object containing a Link object
362
363 """
364 link_metadata = in_toto_run(
365 name,
366 ["."],
367 ["."],
368 link_cmd_args,
369 record_streams=True,
370 use_dsse=use_dsse,
371 )
372
373 filename = FILENAME_FORMAT_SHORT.format(step_name=name)
374 LOG.info("Storing unsigned link metadata to '{}'...".format(filename))
375 link_metadata.dump(filename)
376 return link_metadata
377
378
379 def _check_match_signing_key(signing_key):
380 """Helper method to check if the signing_key has securesystemslib's
381 KEY_SCHEMA and the private part is not empty.
382 # FIXME: Add private key format check to formats
383 """
384 securesystemslib.formats.KEY_SCHEMA.check_match(signing_key)
385 if not signing_key["keyval"].get("private"):
386 raise securesystemslib.exceptions.FormatError(
387 "Signing key needs to be a private key."
388 )
389
390
391 def in_toto_run(
392 name,
393 material_list,
394 product_list,
395 link_cmd_args,
396 record_streams=False,
397 signing_key=None,
398 gpg_keyid=None,
399 gpg_use_default=False,
400 gpg_home=None,
401 exclude_patterns=None,
402 base_path=None,
403 compact_json=False,
404 record_environment=False,
405 normalize_line_endings=False,
406 lstrip_paths=None,
407 metadata_directory=None,
408 use_dsse=False,
409 ):
410 """Performs a supply chain step or inspection generating link metadata.
411
412 Executes link_cmd_args, recording paths and hashes of files before and after
413 command execution (aka. artifacts) in a link metadata file. The metadata is
414 signed with the passed signing_key, a gpg key identified by its ID, or the
415 default gpg key. If multiple key arguments are passed, only one key is used
416 in above order of precedence. The resulting link file is written to
417 ``STEP-NAME.KEYID-PREFIX.link``. If no key argument is passed the link
418 metadata is neither signed nor written to disk.
419
420 Arguments:
421 name: A unique name to associate link metadata with a step or inspection.
422
423 material_list: A list of artifact paths to be recorded before command
424 execution. Directories are traversed recursively.
425
426 product_list: A list of artifact paths to be recorded after command
427 execution. Directories are traversed recursively.
428
429 link_cmd_args: A list where the first element is a command and the
430 remaining elements are arguments passed to that command.
431
432 record_streams (optional): A boolean indicating if standard output and
433 standard error of the link command should be recorded in the link
434 metadata in addition to being displayed while the command is executed.
435
436 signing_key (optional): A key used to sign the resulting link metadata. The
437 format is securesystemslib.formats.KEY_SCHEMA.
438
439 gpg_keyid (optional): A keyid used to identify a local gpg key used to sign
440 the resulting link metadata.
441
442 gpg_use_default (optional): A boolean indicating if the default gpg key
443 should be used to sign the resulting link metadata.
444
445 gpg_home (optional): A path to the gpg home directory. If not set the
446 default gpg home directory is used.
447
448 exclude_patterns (optional): A list of filename patterns to exclude certain
449 files from being recorded as artifacts. See Config docs for details.
450
451 base_path (optional): A path relative to which artifacts are recorded.
452 Default is the current working directory.
453
454 compact_json (optional): A boolean indicating if the resulting link
455 metadata should be written in the most compact JSON representation.
456
457 record_environment (optional): A boolean indicating if information about
458 the environment should be added in the resulting link metadata.
459
460 normalize_line_endings (optional): A boolean indicating if line endings of
461 artifacts should be normalized before hashing for cross-platform
462 support.
463
464 lstrip_paths (optional): A list of path prefixes used to left-strip
465 artifact paths before storing them in the resulting link metadata.
466
467 metadata_directory (optional): A directory path to write the resulting link
468 metadata file to. Default destination is the current working directory.
469
470 use_dsse (optional): A boolean indicating if DSSE should be used to
471 generate metadata.
472
473 Raises:
474 securesystemslib.exceptions.FormatError: Passed arguments are malformed.
475
476 OSError: Cannot change to base path directory.
477
478 securesystemslib.exceptions.StorageError: Cannot hash artifacts.
479
480 PrefixError: Left-stripping artifact paths results in non-unique dict keys.
481
482 subprocess.TimeoutExpired: Link command times out.
483
484 IOError, FileNotFoundError, NotADirectoryError, PermissionError:
485 Cannot write link metadata.
486
487 securesystemslib.exceptions.CryptoError, \
488 securesystemslib.exceptions.UnsupportedAlgorithmError:
489 Signing errors.
490
491 ValueError, OSError, securesystemslib.gpg.exceptions.CommandError, \
492 securesystemslib.gpg.exceptions.KeyNotFoundError:
493 gpg signing errors.
494
495 Side Effects:
496 Reads artifact files from disk.
497 Runs link command in subprocess.
498 Calls system gpg in a subprocess, if a gpg key argument is passed.
499 Writes link metadata file to disk, if any key argument is passed.
500
501 Returns:
502 A Metadata object that contains the resulting link object.
503
504 """
505 LOG.info("Running '{}'...".format(name))
506
507 # Check key formats to fail early
508 if signing_key:
509 _check_match_signing_key(signing_key)
510 if gpg_keyid:
511 securesystemslib.formats.KEYID_SCHEMA.check_match(gpg_keyid)
512
513 if exclude_patterns:
514 securesystemslib.formats.NAMES_SCHEMA.check_match(exclude_patterns)
515
516 if base_path:
517 securesystemslib.formats.PATH_SCHEMA.check_match(base_path)
518
519 if metadata_directory:
520 securesystemslib.formats.PATH_SCHEMA.check_match(metadata_directory)
521
522 if material_list:
523 LOG.info("Recording materials '{}'...".format(", ".join(material_list)))
524
525 materials_dict = record_artifacts_as_dict(
526 material_list,
527 exclude_patterns=exclude_patterns,
528 base_path=base_path,
529 follow_symlink_dirs=True,
530 normalize_line_endings=normalize_line_endings,
531 lstrip_paths=lstrip_paths,
532 )
533
534 if link_cmd_args:
535 securesystemslib.formats.LIST_OF_ANY_STRING_SCHEMA.check_match(
536 link_cmd_args
537 )
538 LOG.info("Running command '{}'...".format(" ".join(link_cmd_args)))
539 byproducts = execute_link(link_cmd_args, record_streams)
540 else:
541 byproducts = {}
542
543 if product_list:
544 securesystemslib.formats.PATHS_SCHEMA.check_match(product_list)
545 LOG.info("Recording products '{}'...".format(", ".join(product_list)))
546
547 products_dict = record_artifacts_as_dict(
548 product_list,
549 exclude_patterns=exclude_patterns,
550 base_path=base_path,
551 follow_symlink_dirs=True,
552 normalize_line_endings=normalize_line_endings,
553 lstrip_paths=lstrip_paths,
554 )
555
556 LOG.info("Creating link metadata...")
557 environment = {}
558 if record_environment:
559 environment["workdir"] = os.getcwd().replace("\\", "/")
560
561 link = in_toto.models.link.Link(
562 name=name,
563 materials=materials_dict,
564 products=products_dict,
565 command=link_cmd_args,
566 byproducts=byproducts,
567 environment=environment,
568 )
569
570 if use_dsse:
571 LOG.info("Generating link metadata using DSSE...")
572 link_metadata = Envelope.from_signable(link)
573 else:
574 LOG.info("Generating link metadata using Metablock...")
575 link_metadata = Metablock(signed=link, compact_json=compact_json)
576
577 signer = None
578 if signing_key:
579 LOG.info("Signing link metadata using passed key...")
580 signer = SSlibSigner(signing_key)
581
582 elif gpg_keyid:
583 LOG.info("Signing link metadata using passed GPG keyid...")
584 signer = GPGSigner(keyid=gpg_keyid, homedir=gpg_home)
585
586 elif gpg_use_default:
587 LOG.info("Signing link metadata using default GPG key ...")
588 signer = GPGSigner(keyid=None, homedir=gpg_home)
589
590 # We need the signature's keyid to write the link to keyid infix'ed filename
591 if signer:
592 signature = link_metadata.create_signature(signer)
593 signing_keyid = signature.keyid
594
595 filename = FILENAME_FORMAT.format(step_name=name, keyid=signing_keyid)
596
597 if metadata_directory is not None:
598 filename = os.path.join(metadata_directory, filename)
599
600 LOG.info("Storing link metadata to '{}'...".format(filename))
601 link_metadata.dump(filename)
602
603 return link_metadata
604
605
606 def in_toto_record_start(
607 step_name,
608 material_list,
609 signing_key=None,
610 gpg_keyid=None,
611 gpg_use_default=False,
612 gpg_home=None,
613 exclude_patterns=None,
614 base_path=None,
615 record_environment=False,
616 normalize_line_endings=False,
617 lstrip_paths=None,
618 use_dsse=False,
619 ):
620 """Generates preliminary link metadata.
621
622 Records paths and hashes of materials in a preliminary link metadata file.
623 The metadata is signed with the passed signing_key, a gpg key identified by
624 its ID, or the default gpg key. If multiple key arguments are passed, only
625 one key is used in above order of precedence. At least one key argument must
626 be passed. The resulting link file is written to
627 ``.STEP-NAME.KEYID-PREFIX.link-unfinished``.
628
629 Use this function together with in_toto_record_stop as an alternative to
630 in_toto_run, in order to provide evidence for supply chain steps that cannot
631 be carried out by a single command.
632
633 Arguments:
634 step_name: A unique name to associate link metadata with a step.
635
636 material_list: A list of artifact paths to be recorded as materials.
637 Directories are traversed recursively.
638
639 signing_key (optional): A key used to sign the resulting link metadata. The
640 format is securesystemslib.formats.KEY_SCHEMA.
641
642 gpg_keyid (optional): A keyid used to identify a local gpg key used to sign
643 the resulting link metadata.
644
645 gpg_use_default (optional): A boolean indicating if the default gpg key
646 should be used to sign the resulting link metadata.
647
648 gpg_home (optional): A path to the gpg home directory. If not set the
649 default gpg home directory is used.
650
651 exclude_patterns (optional): A list of filename patterns to exclude certain
652 files from being recorded as artifacts. See Config docs for details.
653
654 base_path (optional): A path relative to which artifacts are recorded.
655 Default is the current working directory.
656
657 record_environment (optional): A boolean indicating if information about
658 the environment should be added in the resulting link metadata.
659
660 normalize_line_endings (optional): A boolean indicating if line endings of
661 artifacts should be normalized before hashing for cross-platform
662 support.
663
664 lstrip_paths (optional): A list of path prefixes used to left-strip
665 artifact paths before storing them in the resulting link metadata.
666
667 use_dsse (optional): A boolean indicating if DSSE should be used to
668 generate metadata.
669
670 Raises:
671 securesystemslib.exceptions.FormatError: Passed arguments are malformed.
672
673 ValueError: None of signing_key, gpg_keyid or gpg_use_default=True is
674 passed.
675
676 securesystemslib.exceptions.StorageError: Cannot hash artifacts.
677
678 PrefixError: Left-stripping artifact paths results in non-unique dict keys.
679
680 subprocess.TimeoutExpired: Link command times out.
681
682 IOError, PermissionError:
683 Cannot write link metadata.
684
685 securesystemslib.exceptions.CryptoError, \
686 securesystemslib.exceptions.UnsupportedAlgorithmError:
687 Signing errors.
688
689 ValueError, OSError, securesystemslib.gpg.exceptions.CommandError, \
690 securesystemslib.gpg.exceptions.KeyNotFoundError:
691 gpg signing errors.
692
693 Side Effects:
694 Reads artifact files from disk.
695 Calls system gpg in a subprocess, if a gpg key argument is passed.
696 Writes preliminary link metadata file to disk.
697
698 """
699 LOG.info("Start recording '{}'...".format(step_name))
700
701 # Fail if there is no signing key arg at all
702 if not signing_key and not gpg_keyid and not gpg_use_default:
703 raise ValueError(
704 "Pass either a signing key, a gpg keyid or set"
705 " gpg_use_default to True!"
706 )
707
708 # Check key formats to fail early
709 if signing_key:
710 _check_match_signing_key(signing_key)
711 if gpg_keyid:
712 securesystemslib.formats.KEYID_SCHEMA.check_match(gpg_keyid)
713
714 if exclude_patterns:
715 securesystemslib.formats.NAMES_SCHEMA.check_match(exclude_patterns)
716
717 if base_path:
718 securesystemslib.formats.PATH_SCHEMA.check_match(base_path)
719
720 if material_list:
721 LOG.info("Recording materials '{}'...".format(", ".join(material_list)))
722
723 materials_dict = record_artifacts_as_dict(
724 material_list,
725 exclude_patterns=exclude_patterns,
726 base_path=base_path,
727 follow_symlink_dirs=True,
728 normalize_line_endings=normalize_line_endings,
729 lstrip_paths=lstrip_paths,
730 )
731
732 LOG.info("Creating preliminary link metadata...")
733 environment = {}
734 if record_environment:
735 environment["workdir"] = os.getcwd().replace("\\", "/")
736
737 link = in_toto.models.link.Link(
738 name=step_name,
739 materials=materials_dict,
740 products={},
741 command=[],
742 byproducts={},
743 environment=environment,
744 )
745
746 if use_dsse:
747 LOG.info("Generating link metadata using DSSE...")
748 link_metadata = Envelope.from_signable(link)
749 else:
750 LOG.info("Generating link metadata using Metablock...")
751 link_metadata = Metablock(signed=link)
752
753 if signing_key:
754 LOG.info("Signing link metadata using passed key...")
755 signer = SSlibSigner(signing_key)
756
757 elif gpg_keyid:
758 LOG.info("Signing link metadata using passed GPG keyid...")
759 signer = GPGSigner(keyid=gpg_keyid, homedir=gpg_home)
760
761 else: # (gpg_use_default)
762 LOG.info("Signing link metadata using default GPG key ...")
763 signer = GPGSigner(keyid=None, homedir=gpg_home)
764
765 signature = link_metadata.create_signature(signer)
766 # We need the signature's keyid to write the link to keyid infix'ed filename
767 signing_keyid = signature.keyid
768
769 unfinished_fn = UNFINISHED_FILENAME_FORMAT.format(
770 step_name=step_name, keyid=signing_keyid
771 )
772
773 LOG.info(
774 "Storing preliminary link metadata to '{}'...".format(unfinished_fn)
775 )
776 link_metadata.dump(unfinished_fn)
777
778
779 def in_toto_record_stop(
780 step_name,
781 product_list,
782 signing_key=None,
783 gpg_keyid=None,
784 gpg_use_default=False,
785 gpg_home=None,
786 exclude_patterns=None,
787 base_path=None,
788 normalize_line_endings=False,
789 lstrip_paths=None,
790 metadata_directory=None,
791 command=None,
792 byproducts=None,
793 environment=None,
794 ):
795 """Finalizes preliminary link metadata generated with in_toto_record_start.
796
797 Loads preliminary link metadata file, verifies its signature, and records
798 paths and hashes as products, thus finalizing the link metadata. The metadata
799 is signed with the passed signing_key, a gpg key identified by its ID, or the
800 default gpg key. If multiple key arguments are passed, only one key is used
801 in above order of precedence. At least one key argument must be passed and it
802 must be the same as the one used to sign the preliminary link metadata file.
803 The resulting link file is written to ``STEP-NAME.KEYID-PREFIX.link``.
804
805 Use this function together with in_toto_record_start as an alternative to
806 in_toto_run, in order to provide evidence for supply chain steps that cannot
807 be carried out by a single command.
808
809 Arguments:
810 step_name: A unique name to associate link metadata with a step.
811
812 product_list: A list of artifact paths to be recorded as products.
813 Directories are traversed recursively.
814
815 signing_key (optional): A key used to sign the resulting link metadata. The
816 format is securesystemslib.formats.KEY_SCHEMA.
817
818 gpg_keyid (optional): A keyid used to identify a local gpg key used to sign
819 the resulting link metadata.
820
821 gpg_use_default (optional): A boolean indicating if the default gpg key
822 should be used to sign the resulting link metadata.
823
824 gpg_home (optional): A path to the gpg home directory. If not set the
825 default gpg home directory is used.
826
827 exclude_patterns (optional): A list of filename patterns to exclude certain
828 files from being recorded as artifacts.
829
830 base_path (optional): A path relative to which artifacts are recorded.
831 Default is the current working directory.
832
833 normalize_line_endings (optional): A boolean indicating if line endings of
834 artifacts should be normalized before hashing for cross-platform
835 support.
836
837 lstrip_paths (optional): A list of path prefixes used to left-strip
838 artifact paths before storing them in the resulting link metadata.
839
840 metadata_directory (optional): A directory path to write the resulting link
841 metadata file to. Default destination is the current working directory.
842
843 command (optional): A list consisting of a command and arguments executed
844 between in_toto_record_start() and in_toto_record_stop() to capture
845 the command ran in the resulting link metadata.
846
847 byproducts (optional): A dictionary that lists byproducts of the link
848 command execution. It should have at least the following entries
849 "stdout" (str), "stderr" (str) and "return-value" (int).
850
851 environment (optional): A dictionary to capture information about
852 the environment to be added in the resulting link metadata eg.::
853
854 {
855 "variables": "<list of env var KEY=value pairs>",
856 "filesystem": "<filesystem info>",
857 "workdir": "<CWD when executing link command>"
858 }
859
860 Raises:
861 securesystemslib.exceptions.FormatError: Passed arguments are malformed.
862
863 ValueError: None of signing_key, gpg_keyid or gpg_use_default=True is
864 passed.
865
866 LinkNotFoundError: No preliminary link metadata file found.
867
868 securesystemslib.exceptions.StorageError: Cannot hash artifacts.
869
870 PrefixError: Left-stripping artifact paths results in non-unique dict keys.
871
872 subprocess.TimeoutExpired: Link command times out.
873
874 IOError, FileNotFoundError, NotADirectoryError, PermissionError:
875 Cannot write link metadata.
876
877 securesystemslib.exceptions.CryptoError, \
878 securesystemslib.exceptions.UnsupportedAlgorithmError:
879 Signing errors.
880
881 ValueError, OSError, securesystemslib.gpg.exceptions.CommandError, \
882 securesystemslib.gpg.exceptions.KeyNotFoundError:
883 gpg signing errors.
884
885 Side Effects:
886 Reads preliminary link metadata file from disk.
887 Reads artifact files from disk.
888 Calls system gpg in a subprocess, if a gpg key argument is passed.
889 Writes resulting link metadata file to disk.
890 Removes preliminary link metadata file from disk.
891
892 """
893 LOG.info("Stop recording '{}'...".format(step_name))
894
895 # Check that we have something to sign and if the formats are right
896 if not signing_key and not gpg_keyid and not gpg_use_default:
897 raise ValueError(
898 "Pass either a signing key, a gpg keyid or set"
899 " gpg_use_default to True"
900 )
901
902 if signing_key:
903 _check_match_signing_key(signing_key)
904 if gpg_keyid:
905 securesystemslib.formats.KEYID_SCHEMA.check_match(gpg_keyid)
906
907 if exclude_patterns:
908 securesystemslib.formats.NAMES_SCHEMA.check_match(exclude_patterns)
909
910 if base_path:
911 securesystemslib.formats.PATH_SCHEMA.check_match(base_path)
912
913 if metadata_directory:
914 securesystemslib.formats.PATH_SCHEMA.check_match(metadata_directory)
915
916 # Load preliminary link file
917 # If we have a signing key we can use the keyid to construct the name
918 if signing_key:
919 unfinished_fn = UNFINISHED_FILENAME_FORMAT.format(
920 step_name=step_name, keyid=signing_key["keyid"]
921 )
922
923 # FIXME: Currently there is no way to know the default GPG key's keyid and
924 # so we glob for preliminary link files
925 else:
926 unfinished_fn_glob = UNFINISHED_FILENAME_FORMAT_GLOB.format(
927 step_name=step_name, pattern="*"
928 )
929 unfinished_fn_list = glob.glob(unfinished_fn_glob)
930
931 if not len(unfinished_fn_list):
932 raise in_toto.exceptions.LinkNotFoundError(
933 "Could not find a preliminary"
934 " link for step '{}' in the current working directory.".format(
935 step_name
936 )
937 )
938
939 if len(unfinished_fn_list) > 1:
940 raise in_toto.exceptions.LinkNotFoundError(
941 "Found more than one"
942 " preliminary links for step '{}' in the current working directory:"
943 " {}. We need exactly one to stop recording.".format(
944 step_name, ", ".join(unfinished_fn_list)
945 )
946 )
947
948 unfinished_fn = unfinished_fn_list[0]
949
950 LOG.info("Loading preliminary link metadata '{}'...".format(unfinished_fn))
951 link_metadata = Metadata.load(unfinished_fn)
952
953 # The file must have been signed by the same key
954 # If we have a signing_key we use it for verification as well
955 if signing_key:
956 LOG.info(
957 "Verifying preliminary link signature using passed signing key..."
958 )
959 keyid = signing_key["keyid"]
960 verification_key = signing_key
961
962 elif gpg_keyid:
963 LOG.info("Verifying preliminary link signature using passed gpg key...")
964 gpg_pubkey = securesystemslib.gpg.functions.export_pubkey(
965 gpg_keyid, gpg_home
966 )
967 keyid = gpg_pubkey["keyid"]
968 verification_key = gpg_pubkey
969
970 else: # must be gpg_use_default
971 # FIXME: Currently there is no way to know the default GPG key's keyid
972 # before signing. As a workaround we extract the keyid of the preliminary
973 # Link file's signature and try to export a pubkey from the gpg
974 # home directory. We do this even if a gpg_keyid was specified, because gpg
975 # accepts many different ids (mail, name, parts of an id, ...) but we
976 # need a specific format.
977 LOG.info(
978 "Verifying preliminary link signature using default gpg key..."
979 )
980 # signatures are objects in DSSE.
981 sig = link_metadata.signatures[0]
982 if isinstance(sig, Signature):
983 keyid = sig.keyid
984 else:
985 keyid = sig["keyid"]
986 gpg_pubkey = securesystemslib.gpg.functions.export_pubkey(
987 keyid, gpg_home
988 )
989 verification_key = gpg_pubkey
990
991 link_metadata.verify_signature(verification_key)
992
993 LOG.info("Extracting Link from metadata...")
994 link = link_metadata.get_payload()
995
996 # Record products if a product path list was passed
997 if product_list:
998 LOG.info("Recording products '{}'...".format(", ".join(product_list)))
999
1000 link.products = record_artifacts_as_dict(
1001 product_list,
1002 exclude_patterns=exclude_patterns,
1003 base_path=base_path,
1004 follow_symlink_dirs=True,
1005 normalize_line_endings=normalize_line_endings,
1006 lstrip_paths=lstrip_paths,
1007 )
1008
1009 if command:
1010 link.command = command
1011
1012 if byproducts:
1013 link.byproducts = byproducts
1014
1015 if environment:
1016 link.environment = environment
1017
1018 if isinstance(link_metadata, Metablock):
1019 LOG.info("Generating link metadata using Metablock...")
1020 link_metadata = Metablock(signed=link)
1021 else:
1022 LOG.info("Generating link metadata using DSSE...")
1023 link_metadata = Envelope.from_signable(link)
1024
1025 if signing_key:
1026 LOG.info("Updating signature with key '{:.8}...'...".format(keyid))
1027 signer = SSlibSigner(signing_key)
1028
1029 else: # gpg_keyid or gpg_use_default
1030 # In both cases we use the keyid we got from verifying the preliminary
1031 # link signature above.
1032 LOG.info("Updating signature with gpg key '{:.8}...'...".format(keyid))
1033 signer = GPGSigner(keyid=keyid, homedir=gpg_home)
1034
1035 link_metadata.create_signature(signer)
1036 fn = FILENAME_FORMAT.format(step_name=step_name, keyid=keyid)
1037
1038 if metadata_directory is not None:
1039 fn = os.path.join(metadata_directory, fn)
1040
1041 LOG.info("Storing link metadata to '{}'...".format(fn))
1042 link_metadata.dump(fn)
1043
1044 LOG.info("Removing unfinished link metadata '{}'...".format(unfinished_fn))
1045 os.remove(unfinished_fn)
1046
1047
1048 def in_toto_match_products(
1049 link, paths=None, exclude_patterns=None, lstrip_paths=None
1050 ):
1051 """Check if local artifacts match products in passed link.
1052
1053 NOTE: Does not check integrity or authenticity of passed link!
1054
1055 Arguments:
1056 link: The Link object to match.
1057
1058 See ``in_toto_run`` for details about arguments, and exceptions that may
1059 occur while recording artifact hashes.
1060
1061 Returns:
1062 A 3-tuple with artifact names that are
1063 - only in products,
1064 - not in products,
1065 - have different hashes.
1066 """
1067 if paths is None:
1068 paths = ["."]
1069
1070 artifacts = record_artifacts_as_dict(
1071 paths, exclude_patterns=exclude_patterns, lstrip_paths=lstrip_paths
1072 )
1073
1074 artifact_names = artifacts.keys()
1075 product_names = link.products.keys()
1076
1077 only_products = product_names - artifact_names
1078 not_in_products = artifact_names - product_names
1079 differ = {
1080 name
1081 for name in product_names & artifact_names
1082 if link.products[name] != artifacts[name]
1083 }
1084
1085 return only_products, not_in_products, differ