| 1 |
# Copyright New York University and the in-toto contributors |
| 2 |
# SPDX-License-Identifier: Apache-2.0 |
| 3 |
|
| 4 |
""" |
| 5 |
<Program Name> |
| 6 |
verifylib.py |
| 7 |
|
| 8 |
<Author> |
| 9 |
Lukas Puehringer <[email protected]> |
| 10 |
Santiago Torres-Arias <[email protected]> |
| 11 |
|
| 12 |
<Started> |
| 13 |
June 28, 2016 |
| 14 |
|
| 15 |
<Copyright> |
| 16 |
See LICENSE for licensing information. |
| 17 |
|
| 18 |
<Purpose> |
| 19 |
|
| 20 |
Provides a library to verify an in-toto final product containing |
| 21 |
a software supply chain layout. |
| 22 |
|
| 23 |
Take a look at `in_toto_verify`'s docstring for more details about the |
| 24 |
entire verification workflow. |
| 25 |
|
| 26 |
""" |
| 27 |
|
| 28 |
import datetime |
| 29 |
import fnmatch |
| 30 |
import logging |
| 31 |
import os |
| 32 |
|
| 33 |
import iso8601 |
| 34 |
import securesystemslib.exceptions |
| 35 |
import securesystemslib.formats |
| 36 |
from dateutil import tz |
| 37 |
from securesystemslib.gpg.exceptions import KeyExpirationError |
| 38 |
|
| 39 |
import in_toto.formats |
| 40 |
import in_toto.models.layout |
| 41 |
import in_toto.models.link |
| 42 |
import in_toto.rulelib |
| 43 |
import in_toto.runlib |
| 44 |
import in_toto.settings |
| 45 |
from in_toto.exceptions import ( |
| 46 |
BadReturnValueError, |
| 47 |
LayoutExpiredError, |
| 48 |
RuleVerificationError, |
| 49 |
SignatureVerificationError, |
| 50 |
ThresholdVerificationError, |
| 51 |
) |
| 52 |
from in_toto.models.metadata import Metadata |
| 53 |
|
| 54 |
# Inherits from in_toto base logger (c.f. in_toto.log) |
| 55 |
LOG = logging.getLogger(__name__) |
| 56 |
|
| 57 |
RULE_TRACE = {} |
| 58 |
|
| 59 |
|
| 60 |
def _raise_on_bad_retval(return_value, command=None): |
| 61 |
""" |
| 62 |
<Purpose> |
| 63 |
Internal function that checks return values of shell commands, e.g. from |
| 64 |
inspections. Raises exception if the passed value is non-int and non-zero. |
| 65 |
|
| 66 |
<Arguments> |
| 67 |
return_value: |
| 68 |
The return value to be verified |
| 69 |
command: (optional) |
| 70 |
The command whose execution returned the value, used for exception |
| 71 |
message. |
| 72 |
|
| 73 |
<Exceptions> |
| 74 |
BadReturnValueError if the return_value is non-int and non-zero |
| 75 |
|
| 76 |
<Side Effects> |
| 77 |
None. |
| 78 |
|
| 79 |
<Returns> |
| 80 |
None. |
| 81 |
""" |
| 82 |
|
| 83 |
msg = "Got non-{what} " + "return value '{}'".format(return_value) |
| 84 |
if command: |
| 85 |
msg = "{0} from command '{1}'.".format(msg, command) |
| 86 |
else: |
| 87 |
msg = "{0}.".format(msg) |
| 88 |
|
| 89 |
if not isinstance(return_value, int): |
| 90 |
raise BadReturnValueError(msg.format(what="int")) |
| 91 |
|
| 92 |
# TODO: in-toto specification suggests special behavior on |
| 93 |
# return_value == 127, but does not fully define that behavior yet |
| 94 |
|
| 95 |
if return_value != 0: |
| 96 |
raise BadReturnValueError(msg.format(what="zero")) |
| 97 |
|
| 98 |
|
| 99 |
def load_links_for_layout(layout, link_dir_path): |
| 100 |
""" |
| 101 |
<Purpose> |
| 102 |
Try to load all existing metadata files for each Step of the Layout |
| 103 |
from the current directory. |
| 104 |
|
| 105 |
For each step the metadata might consist of multiple (thresholds) Link |
| 106 |
or Layout (sub-layouts) files. |
| 107 |
|
| 108 |
<Arguments> |
| 109 |
layout: |
| 110 |
Layout object |
| 111 |
|
| 112 |
link_dir_path: |
| 113 |
A path to directory where links are loaded from |
| 114 |
|
| 115 |
|
| 116 |
<Side Effects> |
| 117 |
Calls function to read files from disk |
| 118 |
|
| 119 |
<Exceptions> |
| 120 |
in_toto.exceptions.LinkNotFoundError, |
| 121 |
if fewer than `threshold` link files can be found for any given |
| 122 |
step of the supply chain (preliminary threshold check) |
| 123 |
|
| 124 |
<Returns> |
| 125 |
A dictionary carrying all the found metadata corresponding to the |
| 126 |
passed layout, e.g.: |
| 127 |
|
| 128 |
{ |
| 129 |
<step name> : { |
| 130 |
<functionary key id> : <Metadata containing a Link or Layout object>, |
| 131 |
... |
| 132 |
}, ... |
| 133 |
} |
| 134 |
|
| 135 |
|
| 136 |
""" |
| 137 |
steps_metadata = {} |
| 138 |
|
| 139 |
# Iterate over all the steps in the layout |
| 140 |
for step in layout.steps: |
| 141 |
links_per_step = {} |
| 142 |
|
| 143 |
# We try to load a link for every authorized functionary, but don't fail |
| 144 |
# if the file does not exist (authorized != required) |
| 145 |
# FIXME: Should we really pass on IOError, or just skip inexistent links? |
| 146 |
for authorized_keyid in step.pubkeys: |
| 147 |
# Iterate over the authorized key and if present over subkeys |
| 148 |
for keyid in [authorized_keyid] + list( |
| 149 |
layout.keys.get(authorized_keyid, {}).get("subkeys", {}).keys() |
| 150 |
): |
| 151 |
filename = in_toto.models.link.FILENAME_FORMAT.format( |
| 152 |
step_name=step.name, keyid=keyid |
| 153 |
) |
| 154 |
filepath = os.path.join(link_dir_path, filename) |
| 155 |
|
| 156 |
try: |
| 157 |
metadata = Metadata.load(filepath) |
| 158 |
links_per_step[keyid] = metadata |
| 159 |
|
| 160 |
except IOError: |
| 161 |
pass |
| 162 |
|
| 163 |
# This is only a preliminary threshold check, based on (authorized) |
| 164 |
# filenames, to fail early. A more thorough signature-based threshold |
| 165 |
# check is indispensable. |
| 166 |
if len(links_per_step) < step.threshold: |
| 167 |
raise in_toto.exceptions.LinkNotFoundError( |
| 168 |
"Step '{0}' requires '{1}'" |
| 169 |
" link metadata file(s), found '{2}'.".format( |
| 170 |
step.name, step.threshold, len(links_per_step) |
| 171 |
) |
| 172 |
) |
| 173 |
|
| 174 |
steps_metadata[step.name] = links_per_step |
| 175 |
|
| 176 |
return steps_metadata |
| 177 |
|
| 178 |
|
| 179 |
def run_all_inspections(layout, persist_inspection_links): |
| 180 |
""" |
| 181 |
<Purpose> |
| 182 |
Extracts all inspections from a passed Layout's inspect field and |
| 183 |
iteratively runs each command defined in the Inspection's `run` field using |
| 184 |
`runlib.in_toto_run`, which returns a Link object. |
| 185 |
|
| 186 |
If a link command returns non-zero the verification is aborted. |
| 187 |
|
| 188 |
<Arguments> |
| 189 |
layout: |
| 190 |
A Layout object which is used to extract the Inspections. |
| 191 |
|
| 192 |
persist_inspection_links: |
| 193 |
A boolean indicating whether link metadata files for inspection |
| 194 |
are written to cwd. |
| 195 |
|
| 196 |
<Exceptions> |
| 197 |
Calls function that raises BadReturnValueError if an inspection returned |
| 198 |
non-int or non-zero. |
| 199 |
|
| 200 |
<Returns> |
| 201 |
A dictionary of metadata about the executed inspections, e.g.: |
| 202 |
|
| 203 |
{ |
| 204 |
<inspection name> : { |
| 205 |
<Link object>, |
| 206 |
... |
| 207 |
}, ... |
| 208 |
} |
| 209 |
|
| 210 |
""" |
| 211 |
inspection_links_dict = {} |
| 212 |
for inspection in layout.inspect: |
| 213 |
LOG.info( |
| 214 |
"Executing command for inspection '{}'...".format(inspection.name) |
| 215 |
) |
| 216 |
|
| 217 |
# FIXME: We don't want to use the base path for runlib so we patch this |
| 218 |
# for now. This will not stay! |
| 219 |
base_path_backup = in_toto.settings.ARTIFACT_BASE_PATH |
| 220 |
in_toto.settings.ARTIFACT_BASE_PATH = None |
| 221 |
|
| 222 |
# FIXME: What should we record as material/product? |
| 223 |
# Is the current directory a sensible default? In general? |
| 224 |
# If so, we should probably make it a default in run_link |
| 225 |
# We could use artifact rule paths. |
| 226 |
material_list = product_list = ["."] |
| 227 |
link = in_toto.runlib.in_toto_run( |
| 228 |
inspection.name, material_list, product_list, inspection.run |
| 229 |
) |
| 230 |
|
| 231 |
_raise_on_bad_retval( |
| 232 |
link.signed.byproducts.get("return-value"), inspection.run |
| 233 |
) |
| 234 |
|
| 235 |
inspection_links_dict[inspection.name] = link.signed |
| 236 |
|
| 237 |
# If client requests persistent inspection links, |
| 238 |
# Dump the inspection link file for auditing |
| 239 |
# Keep in mind that this pollutes the verifier's (client's) filesystem. |
| 240 |
if persist_inspection_links: |
| 241 |
filename = in_toto.models.link.FILENAME_FORMAT_SHORT.format( |
| 242 |
step_name=inspection.name |
| 243 |
) |
| 244 |
link.dump(filename) |
| 245 |
|
| 246 |
in_toto.settings.ARTIFACT_BASE_PATH = base_path_backup |
| 247 |
|
| 248 |
return inspection_links_dict |
| 249 |
|
| 250 |
|
| 251 |
def verify_layout_expiration(layout): |
| 252 |
""" |
| 253 |
<Purpose> |
| 254 |
Raises an exception if the passed layout has expired, i.e. if its |
| 255 |
`expires` property is lesser "now". |
| 256 |
Time zone aware datetime objects in UTC+00:00 (Zulu Time) are used. |
| 257 |
|
| 258 |
<Arguments> |
| 259 |
layout: |
| 260 |
The Layout object to be verified. |
| 261 |
|
| 262 |
<Exceptions> |
| 263 |
LayoutExpiredError |
| 264 |
TBA (see https://github.com/in-toto/in-toto/issues/6) |
| 265 |
|
| 266 |
<Side Effects> |
| 267 |
None. |
| 268 |
|
| 269 |
""" |
| 270 |
expire_datetime = iso8601.parse_date(layout.expires) |
| 271 |
if expire_datetime < datetime.datetime.now(tz.tzutc()): |
| 272 |
raise LayoutExpiredError("Layout expired") |
| 273 |
|
| 274 |
|
| 275 |
def substitute_parameters(layout, parameter_dictionary): |
| 276 |
""" |
| 277 |
<Purpose> |
| 278 |
This function is a transitionary measure for parameter substitution (or |
| 279 |
any other solution defined by the in-toto team). As of now, it acts as |
| 280 |
a very simple replacement layer for python-like parameters |
| 281 |
|
| 282 |
<Arguments> |
| 283 |
layout: |
| 284 |
The Layout object to process. |
| 285 |
|
| 286 |
parameter_dictionary: |
| 287 |
A dictionary containing key-value pairs for substitution. |
| 288 |
|
| 289 |
<Exceptions> |
| 290 |
securesystemslib.exceptions.FormatError: |
| 291 |
if the parameter dictionary is malformed. |
| 292 |
|
| 293 |
KeyError: |
| 294 |
if one of the keys in the parameter dictionary are not present for |
| 295 |
substitution |
| 296 |
|
| 297 |
<Side Effects> |
| 298 |
The layout object will have any tags replaced with the corresponding |
| 299 |
values defined in the parameter dictionary. |
| 300 |
""" |
| 301 |
in_toto.formats.PARAMETER_DICTIONARY_SCHEMA.check_match( |
| 302 |
parameter_dictionary |
| 303 |
) |
| 304 |
|
| 305 |
for step in layout.steps: |
| 306 |
new_material_rules = [] |
| 307 |
for rule in step.expected_materials: |
| 308 |
new_rule = [] |
| 309 |
for stanza in rule: |
| 310 |
new_rule.append(stanza.format(**parameter_dictionary)) |
| 311 |
new_material_rules.append(new_rule) |
| 312 |
|
| 313 |
new_product_rules = [] |
| 314 |
for rule in step.expected_products: |
| 315 |
new_rule = [] |
| 316 |
for stanza in rule: |
| 317 |
new_rule.append(stanza.format(**parameter_dictionary)) |
| 318 |
new_product_rules.append(new_rule) |
| 319 |
|
| 320 |
new_expected_command = [] |
| 321 |
for argv in step.expected_command: |
| 322 |
new_expected_command.append(argv.format(**parameter_dictionary)) |
| 323 |
|
| 324 |
step.expected_command = new_expected_command |
| 325 |
step.expected_materials = new_material_rules |
| 326 |
step.expected_products = new_product_rules |
| 327 |
|
| 328 |
for inspection in layout.inspect: |
| 329 |
new_material_rules = [] |
| 330 |
for rule in inspection.expected_materials: |
| 331 |
new_rule = [] |
| 332 |
for stanza in rule: |
| 333 |
new_rule.append(stanza.format(**parameter_dictionary)) |
| 334 |
new_material_rules.append(new_rule) |
| 335 |
|
| 336 |
new_product_rules = [] |
| 337 |
for rule in inspection.expected_products: |
| 338 |
new_rule = [] |
| 339 |
for stanza in rule: |
| 340 |
new_rule.append(stanza.format(**parameter_dictionary)) |
| 341 |
new_product_rules.append(new_rule) |
| 342 |
|
| 343 |
new_run = [] |
| 344 |
for argv in inspection.run: |
| 345 |
new_run.append(argv.format(**parameter_dictionary)) |
| 346 |
|
| 347 |
inspection.run = new_run |
| 348 |
inspection.expected_materials = new_material_rules |
| 349 |
inspection.expected_products = new_product_rules |
| 350 |
|
| 351 |
|
| 352 |
def verify_metadata_signatures(metadata, keys_dict): |
| 353 |
""" |
| 354 |
<Purpose> |
| 355 |
Iteratively verifies the signatures of a Metadata object containing |
| 356 |
a Layout object for every verification key in the passed keys dictionary. |
| 357 |
|
| 358 |
Requires at least one key to be passed and requires every passed key to |
| 359 |
find a valid signature. |
| 360 |
|
| 361 |
<Arguments> |
| 362 |
metadata: |
| 363 |
A Metadata object containing a Layout whose signatures are |
| 364 |
verified. |
| 365 |
|
| 366 |
keys_dict: |
| 367 |
A dictionary of keys to verify the signatures conformant with |
| 368 |
securesystemslib.formats.VERIFICATION_KEY_DICT_SCHEMA. |
| 369 |
|
| 370 |
<Exceptions> |
| 371 |
securesystemslib.exceptions.FormatError |
| 372 |
if the passed key dict does not match VERIFICATION_KEY_DICT_SCHEMA. |
| 373 |
|
| 374 |
SignatureVerificationError |
| 375 |
if an empty verification key dictionary was passed, or |
| 376 |
if any of the passed verification keys fails to verify a signature. |
| 377 |
|
| 378 |
securesystemslib.gpg.exceptions.KeyExpirationError: |
| 379 |
if any of the passed verification keys is an expired gpg key |
| 380 |
|
| 381 |
""" |
| 382 |
securesystemslib.formats.VERIFICATION_KEY_DICT_SCHEMA.check_match(keys_dict) |
| 383 |
|
| 384 |
# Fail if an empty verification key dictionary was passed |
| 385 |
if len(keys_dict) < 1: |
| 386 |
raise SignatureVerificationError( |
| 387 |
"Layout signature verification requires at least one key." |
| 388 |
) |
| 389 |
|
| 390 |
# Fail if any of the passed keys can't verify a signature on the Layout |
| 391 |
for junk, verify_key in keys_dict.items(): |
| 392 |
metadata.verify_signature(verify_key) |
| 393 |
|
| 394 |
|
| 395 |
def verify_link_signature_thresholds(layout, steps_metadata): |
| 396 |
""" |
| 397 |
<Purpose> |
| 398 |
Verify that for each step of the layout there are at least `threshold` |
| 399 |
links metadata, signed by different authorized functionaries and return the |
| 400 |
verified link metadata dictionary containing only authorized links metadata |
| 401 |
whose signatures were successfully verified. |
| 402 |
|
| 403 |
NOTE: If the layout's key store (`layout.keys`) lists a (master) key `K`, |
| 404 |
with a subkey `K'`, then `K'` is authorized implicitly, to sign any link |
| 405 |
that `K` is authorized to sign. In other words, the trust in a master key |
| 406 |
extends to the trust in a subkey. The inverse is not true. |
| 407 |
|
| 408 |
<Arguments> |
| 409 |
layout: |
| 410 |
A Layout object whose Steps are extracted and verified. |
| 411 |
|
| 412 |
steps_metadata: |
| 413 |
A dictionary containing link metadata per functionary per step, |
| 414 |
e.g.: |
| 415 |
{ |
| 416 |
<link name> : { |
| 417 |
<functionary key id> : <Metadata containing a Link or Layout |
| 418 |
object>, |
| 419 |
... |
| 420 |
}, ... |
| 421 |
} |
| 422 |
|
| 423 |
<Exceptions> |
| 424 |
ThresholdVerificationError |
| 425 |
If any of the steps of the passed layout does not have enough |
| 426 |
(`step.threshold`) links signed by different authorized |
| 427 |
functionaries. |
| 428 |
|
| 429 |
<Returns> |
| 430 |
A steps_metadata containing only links with valid signatures created by |
| 431 |
authorized functionaries. |
| 432 |
|
| 433 |
""" |
| 434 |
# Create an inverse keys-subkeys dictionary, with subkey keyids as |
| 435 |
# dictionary keys and main keys as dictionary values. This will be |
| 436 |
# required below to assess main-subkey trust delegations. |
| 437 |
# We assume that a given subkey can only belong to one master key |
| 438 |
# TODO: Is this a safe assumption? Should we assert for it? |
| 439 |
main_keys_for_subkeys = {} |
| 440 |
for main_key in list(layout.keys.values()): |
| 441 |
for sub_keyid in main_key.get("subkeys", []): |
| 442 |
main_keys_for_subkeys[sub_keyid] = main_key |
| 443 |
|
| 444 |
# Dict for valid and authorized links of all steps of the layout |
| 445 |
verified_steps_metadata = {} |
| 446 |
|
| 447 |
# For each step of the layout check the signatures of corresponding links. |
| 448 |
# Consider only links where the signature is valid and keys are authorized, |
| 449 |
# and discard others. |
| 450 |
# Only count one of multiple links signed with different subkeys of a main |
| 451 |
# key towards link threshold. |
| 452 |
# Only proceed with final product verification if threshold requirements are |
| 453 |
# fulfilled. |
| 454 |
for step in layout.steps: |
| 455 |
# Dict for valid and authorized links of a given step |
| 456 |
verified_key_link_dict = {} |
| 457 |
# List of used keyids |
| 458 |
used_main_keyids = [] |
| 459 |
|
| 460 |
# Do per step link threshold verification |
| 461 |
for link_keyid, link in steps_metadata.get(step.name, {}).items(): |
| 462 |
# Iterate over authorized keyids to find a key or subkey corresponding |
| 463 |
# to the given link and check if the link's keyid is authorized. |
| 464 |
# Subkeys of authorized main keys are authorized implicitly. |
| 465 |
for authorized_keyid in step.pubkeys: |
| 466 |
authorized_key = layout.keys.get(authorized_keyid) |
| 467 |
main_key_for_subkey = main_keys_for_subkeys.get( |
| 468 |
authorized_keyid |
| 469 |
) |
| 470 |
|
| 471 |
# The signing key is authorized ... |
| 472 |
if authorized_key and link_keyid == authorized_keyid: |
| 473 |
verification_key = authorized_key |
| 474 |
break |
| 475 |
|
| 476 |
# ... or the signing key is an authorized subkey ... |
| 477 |
if main_key_for_subkey and link_keyid == authorized_keyid: |
| 478 |
verification_key = main_key_for_subkey |
| 479 |
break |
| 480 |
|
| 481 |
# ... or the signing key is a subkey of an authorized key |
| 482 |
if ( |
| 483 |
authorized_key |
| 484 |
and link_keyid in authorized_key.get("subkeys", {}).keys() |
| 485 |
): |
| 486 |
verification_key = authorized_key |
| 487 |
break |
| 488 |
|
| 489 |
else: |
| 490 |
LOG.info( |
| 491 |
"Skipping link. Keyid '{0}' is not authorized to sign links" |
| 492 |
" for step '{1}'".format(link_keyid, step.name) |
| 493 |
) |
| 494 |
continue |
| 495 |
|
| 496 |
# Verify signature and skip invalidly signed links |
| 497 |
try: |
| 498 |
link.verify_signature(verification_key) |
| 499 |
|
| 500 |
except SignatureVerificationError: |
| 501 |
LOG.info( |
| 502 |
"Skipping link. Broken link signature with keyid '{0}'" |
| 503 |
" for step '{1}'".format(link_keyid, step.name) |
| 504 |
) |
| 505 |
continue |
| 506 |
|
| 507 |
except KeyExpirationError as e: |
| 508 |
LOG.info("Skipping link. {}".format(e)) |
| 509 |
continue |
| 510 |
|
| 511 |
# Warn if there are links signed by different subkeys of same main key |
| 512 |
if verification_key["keyid"] in used_main_keyids: |
| 513 |
LOG.warning( |
| 514 |
"Found links signed by different subkeys of the same main" |
| 515 |
" key '{}' for step '{}'. Only one of them is counted towards the" |
| 516 |
" step threshold.".format( |
| 517 |
verification_key["keyid"], step.name |
| 518 |
) |
| 519 |
) |
| 520 |
|
| 521 |
used_main_keyids.append(verification_key["keyid"]) |
| 522 |
|
| 523 |
# Keep only links with valid and authorized signature |
| 524 |
verified_key_link_dict[link_keyid] = link |
| 525 |
|
| 526 |
# For each step, verify that we have enough validly signed links from |
| 527 |
# distinct authorized functionaries. Links signed by different subkeys of |
| 528 |
# the same main key are counted only once towards the threshold. |
| 529 |
valid_authorized_links_cnt = len(set(used_main_keyids)) |
| 530 |
# TODO: To guarantee that links are signed by different functionaries |
| 531 |
# we rely on the layout to not carry duplicate verification keys under |
| 532 |
# different dictionary keys, e.g. {keyid1: KEY1, keyid2: KEY1} |
| 533 |
# Maybe we should add such a check to the layout validation? Or here? |
| 534 |
if valid_authorized_links_cnt < step.threshold: |
| 535 |
raise ThresholdVerificationError( |
| 536 |
"Step '{}' requires at least '{}' links" |
| 537 |
" validly signed by different authorized functionaries. Only" |
| 538 |
" found '{}'".format( |
| 539 |
step.name, step.threshold, valid_authorized_links_cnt |
| 540 |
) |
| 541 |
) |
| 542 |
|
| 543 |
# Add all good links of this step to the dictionary of links of all steps |
| 544 |
verified_steps_metadata[step.name] = verified_key_link_dict |
| 545 |
|
| 546 |
# Threshold verification succeeded, return valid and authorized links for |
| 547 |
# further verification |
| 548 |
return verified_steps_metadata |
| 549 |
|
| 550 |
|
| 551 |
def verify_command_alignment(command, expected_command): |
| 552 |
""" |
| 553 |
<Purpose> |
| 554 |
Checks if a run command aligns with an expected command. The commands align |
| 555 |
if all of their elements are equal. If alignment fails, a warning is |
| 556 |
printed. |
| 557 |
|
| 558 |
Note: |
| 559 |
Command alignment is a weak guarantee. Because a functionary can easily |
| 560 |
alias commands. |
| 561 |
|
| 562 |
<Arguments> |
| 563 |
command: |
| 564 |
A command list, e.g. ["vi", "foo.py"] |
| 565 |
expected_command: |
| 566 |
A command list, e.g. ["make", "install"] |
| 567 |
|
| 568 |
<Exceptions> |
| 569 |
None. |
| 570 |
|
| 571 |
<Side Effects> |
| 572 |
Logs warning in case commands do not align. |
| 573 |
|
| 574 |
""" |
| 575 |
# In what case command alignment should fail and how that failure should be |
| 576 |
# propagated has been thoughly discussed in: |
| 577 |
# https://github.com/in-toto/in-toto/issues/46 and |
| 578 |
# https://github.com/in-toto/in-toto/pull/47 |
| 579 |
# We chose the simplest solution for now, i.e. Warn if they do not align. |
| 580 |
if command != expected_command: |
| 581 |
LOG.warning( |
| 582 |
"Run command '{0}' differs from expected command '{1}'".format( |
| 583 |
command, expected_command |
| 584 |
) |
| 585 |
) |
| 586 |
|
| 587 |
|
| 588 |
def verify_all_steps_command_alignment(layout, chain_link_dict): |
| 589 |
""" |
| 590 |
<Purpose> |
| 591 |
Iteratively checks if all expected commands as defined in the |
| 592 |
Steps of a Layout align with the actual commands as recorded in the Link |
| 593 |
metadata. |
| 594 |
|
| 595 |
<Arguments> |
| 596 |
layout: |
| 597 |
A Layout object to extract the expected commands from. |
| 598 |
|
| 599 |
chain_link_dict: |
| 600 |
A dictionary containing link metadata per functionary per step, |
| 601 |
e.g.: |
| 602 |
{ |
| 603 |
<link name> : { |
| 604 |
<functionary key id> : <Link object>, |
| 605 |
... |
| 606 |
}, ... |
| 607 |
} |
| 608 |
|
| 609 |
<Exceptions> |
| 610 |
None. |
| 611 |
|
| 612 |
<Side Effects> |
| 613 |
None. |
| 614 |
|
| 615 |
""" |
| 616 |
for step in layout.steps: |
| 617 |
# Find the according link for this step |
| 618 |
expected_command = step.expected_command |
| 619 |
key_link_dict = chain_link_dict[step.name] |
| 620 |
|
| 621 |
# FIXME: I think we could do this for one link per step only |
| 622 |
# providing that we verify command alignment AFTER threshold equality |
| 623 |
for keyid, link in key_link_dict.items(): |
| 624 |
LOG.info( |
| 625 |
"Verifying command alignment for '{0}'...".format( |
| 626 |
in_toto.models.link.FILENAME_FORMAT.format( |
| 627 |
step_name=step.name, keyid=keyid |
| 628 |
) |
| 629 |
) |
| 630 |
) |
| 631 |
|
| 632 |
command = link.command |
| 633 |
verify_command_alignment(command, expected_command) |
| 634 |
|
| 635 |
|
| 636 |
def verify_match_rule(rule_data, artifacts_queue, source_artifacts, links): |
| 637 |
""" |
| 638 |
<Purpose> |
| 639 |
Filters artifacts from artifact queue using rule pattern and optional rule |
| 640 |
source prefix and consumes them if there is a corresponding destination |
| 641 |
artifact, filtered using the same rule pattern and an optional rule |
| 642 |
destination prefix, and source and destination artifacts have matching |
| 643 |
hashes. |
| 644 |
|
| 645 |
NOTE: The destination artifacts are extracted from the links dictionary, |
| 646 |
using destination name and destination type from the rule data. The source |
| 647 |
artifacts could also be extracted from the links dictionary, but would |
| 648 |
require the caller to pass source name and source type, as those are not |
| 649 |
encoded in the rule. However, we choose to let the caller directly pass the |
| 650 |
relevant artifacts. |
| 651 |
|
| 652 |
|
| 653 |
<Arguments> |
| 654 |
rule_data: |
| 655 |
An unpacked "MATCH" rule (see in_toto.rulelib). |
| 656 |
|
| 657 |
artifacts_queue: |
| 658 |
Not yet consumed artifacts (paths only). |
| 659 |
|
| 660 |
|
| 661 |
source_artifacts: |
| 662 |
All artifacts of the source item (including hashes). |
| 663 |
|
| 664 |
links: |
| 665 |
A dictionary containing link metadata per step or inspection, e.g.: |
| 666 |
{ |
| 667 |
<link name> : <Link object>, |
| 668 |
... |
| 669 |
} |
| 670 |
|
| 671 |
<Exceptions> |
| 672 |
None. |
| 673 |
|
| 674 |
<Side Effects> |
| 675 |
None. |
| 676 |
|
| 677 |
<Returns> |
| 678 |
The set of consumed artifacts (paths only). |
| 679 |
|
| 680 |
""" |
| 681 |
consumed = set() |
| 682 |
|
| 683 |
# The rule can only consume artifacts if the destination link exists |
| 684 |
dest_link = links.get(rule_data["dest_name"]) |
| 685 |
if not dest_link: |
| 686 |
return consumed |
| 687 |
|
| 688 |
# Extract destination artifacts from destination link |
| 689 |
dest_artifacts = getattr(dest_link, rule_data["dest_type"]) |
| 690 |
|
| 691 |
# Filter part 1 - Filter artifacts using optional source prefix, and subtract |
| 692 |
# prefix before filtering with rule pattern (see filter part 2) to prevent |
| 693 |
# globbing in the prefix. |
| 694 |
if rule_data["source_prefix"]: |
| 695 |
filtered_source_paths = [] |
| 696 |
# Add trailing slash to source prefix if it does not exist |
| 697 |
normalized_source_prefix = os.path.join( |
| 698 |
rule_data["source_prefix"], "" |
| 699 |
).replace("\\", "/") |
| 700 |
|
| 701 |
for artifact_path in artifacts_queue: |
| 702 |
if artifact_path.startswith(normalized_source_prefix): |
| 703 |
filtered_source_paths.append( |
| 704 |
artifact_path[len(normalized_source_prefix) :] |
| 705 |
) |
| 706 |
|
| 707 |
else: |
| 708 |
filtered_source_paths = artifacts_queue |
| 709 |
|
| 710 |
# Filter part 2 - glob above filtered artifact paths |
| 711 |
filtered_source_paths = fnmatch.filter( |
| 712 |
filtered_source_paths, rule_data["pattern"] |
| 713 |
) |
| 714 |
|
| 715 |
# Iterate over filtered source paths and try to match the corresponding |
| 716 |
# source artifact hash with the corresponding destination artifact hash |
| 717 |
for path in filtered_source_paths: |
| 718 |
# If a source prefix was specified, we subtracted the prefix above before |
| 719 |
# globbing. We have to re-prepend the prefix in order to retrieve the |
| 720 |
# corresponding source artifact below. |
| 721 |
if rule_data["source_prefix"]: |
| 722 |
full_source_path = os.path.join( |
| 723 |
rule_data["source_prefix"], path |
| 724 |
).replace("\\", "/") |
| 725 |
|
| 726 |
else: |
| 727 |
full_source_path = path |
| 728 |
|
| 729 |
# If a destination prefix was specified, the destination artifact should |
| 730 |
# be queried with the full destination path, i.e. the prefix joined with |
| 731 |
# the globbed path. |
| 732 |
if rule_data["dest_prefix"]: |
| 733 |
full_dest_path = os.path.join( |
| 734 |
rule_data["dest_prefix"], path |
| 735 |
).replace("\\", "/") |
| 736 |
|
| 737 |
else: |
| 738 |
full_dest_path = path |
| 739 |
|
| 740 |
# Extract source artifact hash dict |
| 741 |
# We know the source artifact is available, it is also in the queue |
| 742 |
source_artifact = source_artifacts[full_source_path] |
| 743 |
|
| 744 |
# Don't consume source artifact w/o corresponding dest artifact (by path) |
| 745 |
try: |
| 746 |
dest_artifact = dest_artifacts[full_dest_path] |
| 747 |
except KeyError: |
| 748 |
continue |
| 749 |
|
| 750 |
# Don't consume source artifact w/o corresponding dest artifact (by hash) |
| 751 |
if source_artifact != dest_artifact: |
| 752 |
continue |
| 753 |
|
| 754 |
# Source and destination matched, consume artifact |
| 755 |
consumed.add(full_source_path) |
| 756 |
|
| 757 |
return consumed |
| 758 |
|
| 759 |
|
| 760 |
def verify_create_rule(rule_pattern, artifacts_queue, materials, products): |
| 761 |
""" |
| 762 |
<Purpose> |
| 763 |
Filters artifacts from artifacts queue using rule pattern and consumes them |
| 764 |
if they are not in the materials set but are in the products set, i.e. |
| 765 |
were created. |
| 766 |
|
| 767 |
<Arguments> |
| 768 |
rule_pattern: |
| 769 |
A "CREATE" rule pattern (see in_toto.rulelib). |
| 770 |
|
| 771 |
artifacts_queue: |
| 772 |
Not yet consumed artifacts (paths only). |
| 773 |
|
| 774 |
materials: |
| 775 |
All materials of an item (paths only). |
| 776 |
|
| 777 |
products: |
| 778 |
All products of an item (paths only). |
| 779 |
|
| 780 |
<Exceptions> |
| 781 |
None. |
| 782 |
|
| 783 |
<Side Effects> |
| 784 |
None. |
| 785 |
|
| 786 |
<Returns> |
| 787 |
The set of consumed artifacts (paths only). |
| 788 |
|
| 789 |
""" |
| 790 |
# Filter queued artifacts using the rule pattern |
| 791 |
filtered_artifacts = fnmatch.filter(artifacts_queue, rule_pattern) |
| 792 |
|
| 793 |
# Consume filtered artifacts that are products but not materials |
| 794 |
consumed = set(filtered_artifacts) & (products - materials) |
| 795 |
|
| 796 |
return consumed |
| 797 |
|
| 798 |
|
| 799 |
def verify_delete_rule(rule_pattern, artifacts_queue, materials, products): |
| 800 |
""" |
| 801 |
<Purpose> |
| 802 |
Filters artifacts from artifacts queue using rule pattern and consumes them |
| 803 |
if they are in the materials set but are not in the products set, i.e. |
| 804 |
were deleted. |
| 805 |
|
| 806 |
<Arguments> |
| 807 |
rule_pattern: |
| 808 |
A "DELETE" rule pattern (see in_toto.rulelib). |
| 809 |
|
| 810 |
artifacts_queue: |
| 811 |
Not yet consumed artifacts (paths only). |
| 812 |
|
| 813 |
materials: |
| 814 |
All materials of an item (paths only). |
| 815 |
|
| 816 |
products: |
| 817 |
All products of an item (paths only). |
| 818 |
|
| 819 |
<Exceptions> |
| 820 |
None. |
| 821 |
|
| 822 |
<Side Effects> |
| 823 |
None. |
| 824 |
|
| 825 |
<Returns> |
| 826 |
The set of consumed artifacts (paths only). |
| 827 |
|
| 828 |
""" |
| 829 |
# Filter queued artifacts using the rule pattern |
| 830 |
filtered_artifacts = fnmatch.filter(artifacts_queue, rule_pattern) |
| 831 |
|
| 832 |
# Consume filtered artifacts that are materials but not products |
| 833 |
consumed = set(filtered_artifacts) & (materials - products) |
| 834 |
|
| 835 |
return consumed |
| 836 |
|
| 837 |
|
| 838 |
def verify_modify_rule(rule_pattern, artifacts_queue, materials, products): |
| 839 |
""" |
| 840 |
<Purpose> |
| 841 |
Filters artifacts from artifacts queue using rule pattern and consumes them |
| 842 |
if they are in both the materials dict and in the products doct, but have |
| 843 |
different hashes, i.e. were modified. |
| 844 |
|
| 845 |
<Arguments> |
| 846 |
rule_pattern: |
| 847 |
A "MODIFY" rule pattern (see in_toto.rulelib). |
| 848 |
|
| 849 |
artifacts_queue: |
| 850 |
Not yet consumed artifacts (paths only). |
| 851 |
|
| 852 |
materials: |
| 853 |
All materials of an item (including hashes). |
| 854 |
|
| 855 |
products: |
| 856 |
All products of an item (including hashes). |
| 857 |
|
| 858 |
<Exceptions> |
| 859 |
None. |
| 860 |
|
| 861 |
<Side Effects> |
| 862 |
None. |
| 863 |
|
| 864 |
<Returns> |
| 865 |
The set of consumed artifacts (paths only). |
| 866 |
|
| 867 |
""" |
| 868 |
# Filter queued artifacts using the rule pattern |
| 869 |
filtered_artifacts = fnmatch.filter(artifacts_queue, rule_pattern) |
| 870 |
|
| 871 |
# Filter filtered artifacts that are materials and products |
| 872 |
filtered_artifacts = ( |
| 873 |
set(filtered_artifacts) & set(materials.keys()) & set(products.keys()) |
| 874 |
) |
| 875 |
|
| 876 |
# Consume filtered artifacts that have different hashes |
| 877 |
consumed = set() |
| 878 |
for path in filtered_artifacts: |
| 879 |
if materials[path] != products[path]: |
| 880 |
consumed.add(path) |
| 881 |
|
| 882 |
return consumed |
| 883 |
|
| 884 |
|
| 885 |
def verify_allow_rule(rule_pattern, artifacts_queue): |
| 886 |
""" |
| 887 |
<Purpose> |
| 888 |
Consumes artifacts, filtered from the artifacts queue using rule pattern. |
| 889 |
|
| 890 |
<Arguments> |
| 891 |
rule_pattern: |
| 892 |
An "ALLOW" rule pattern (see in_toto.rulelib). |
| 893 |
|
| 894 |
artifacts_queue: |
| 895 |
Not yet consumed artifacts (paths only). |
| 896 |
|
| 897 |
<Exceptions> |
| 898 |
None. |
| 899 |
|
| 900 |
<Side Effects> |
| 901 |
None. |
| 902 |
|
| 903 |
<Returns> |
| 904 |
The set of consumed artifacts (paths only). |
| 905 |
|
| 906 |
""" |
| 907 |
# Filter queued artifacts using the rule pattern |
| 908 |
filtered_artifacts = fnmatch.filter(artifacts_queue, rule_pattern) |
| 909 |
|
| 910 |
# Consume all filtered artifacts |
| 911 |
return set(filtered_artifacts) |
| 912 |
|
| 913 |
|
| 914 |
def verify_disallow_rule(rule_pattern, artifacts_queue): |
| 915 |
""" |
| 916 |
<Purpose> |
| 917 |
Raises RuleVerificationError if rule pattern applies to any artifacts in |
| 918 |
the queue. |
| 919 |
|
| 920 |
NOTE: Each set of rules should have a terminal DISALLOW rule to make |
| 921 |
overall verification fail in case preceding rules did not consume all |
| 922 |
artifacts as intended. |
| 923 |
|
| 924 |
<Arguments> |
| 925 |
rule_pattern: |
| 926 |
A "DISALLOW" rule pattern (see in_toto.rulelib). |
| 927 |
|
| 928 |
artifacts_queue: |
| 929 |
Not yet consumed artifacts (paths only). |
| 930 |
|
| 931 |
<Exceptions> |
| 932 |
RuleVerificationError |
| 933 |
if the rule pattern filters artifacts in the artifact queue. |
| 934 |
|
| 935 |
<Side Effects> |
| 936 |
None. |
| 937 |
|
| 938 |
<Returns> |
| 939 |
None. |
| 940 |
|
| 941 |
""" |
| 942 |
filtered_artifacts = fnmatch.filter(artifacts_queue, rule_pattern) |
| 943 |
|
| 944 |
if len(filtered_artifacts): |
| 945 |
raise RuleVerificationError( |
| 946 |
"'DISALLOW {}' matched the following " |
| 947 |
"artifacts: {}\n{}".format( |
| 948 |
rule_pattern, filtered_artifacts, _get_artifact_rule_traceback() |
| 949 |
) |
| 950 |
) |
| 951 |
|
| 952 |
|
| 953 |
def verify_require_rule(filename, artifacts_queue): |
| 954 |
""" |
| 955 |
<Purpose> |
| 956 |
Raises RuleVerificationError if the filename provided does not exist in the |
| 957 |
artifacts_queue |
| 958 |
|
| 959 |
<Arguments> |
| 960 |
filename: |
| 961 |
A single filename (see issues #193 and #152). We will ignore the |
| 962 |
artifact rule pattern because it's ambiguous and instead treat it |
| 963 |
as a literal file name. |
| 964 |
|
| 965 |
artifacts_queue: |
| 966 |
Not yet consumed artifacts (paths only). |
| 967 |
|
| 968 |
<Exceptions> |
| 969 |
RuleVerificationError: |
| 970 |
if the filename is not present in the artifacts queue |
| 971 |
|
| 972 |
<Side Effects> |
| 973 |
None. |
| 974 |
|
| 975 |
<Returns> |
| 976 |
None. |
| 977 |
|
| 978 |
""" |
| 979 |
if filename not in artifacts_queue: |
| 980 |
raise RuleVerificationError( |
| 981 |
"'REQUIRE {filename}' did not find {filename} " |
| 982 |
"in: {queue}\n{traceback}".format( |
| 983 |
filename=filename, |
| 984 |
queue=artifacts_queue, |
| 985 |
traceback=_get_artifact_rule_traceback(), |
| 986 |
) |
| 987 |
) |
| 988 |
|
| 989 |
|
| 990 |
def _get_artifact_rule_traceback(): |
| 991 |
"""Build and return string form global `RULE_TRACE` which may be used as |
| 992 |
error message for RuleVerificationError. |
| 993 |
|
| 994 |
""" |
| 995 |
traceback_str = "Full trace for 'expected_{0}' of item '{1}':\n".format( |
| 996 |
RULE_TRACE["source_type"], RULE_TRACE["source_name"] |
| 997 |
) |
| 998 |
|
| 999 |
# Show all materials and products available in the beginning and |
| 1000 |
# label the one that is used to generate a queue. |
| 1001 |
for source_type in ["materials", "products"]: |
| 1002 |
traceback_str += "Available {}{}:\n{}\n".format( |
| 1003 |
source_type, |
| 1004 |
[" (used for queue)", ""][RULE_TRACE["source_type"] != source_type], |
| 1005 |
RULE_TRACE[source_type], |
| 1006 |
) |
| 1007 |
|
| 1008 |
for trace_entry in RULE_TRACE["trace"]: |
| 1009 |
traceback_str += "Queue after '{0}':\n".format( |
| 1010 |
" ".join(trace_entry["rule"]) |
| 1011 |
) |
| 1012 |
traceback_str += "{}\n".format(trace_entry["queue"]) |
| 1013 |
|
| 1014 |
return traceback_str |
| 1015 |
|
| 1016 |
|
| 1017 |
def verify_item_rules(source_name, source_type, rules, links): |
| 1018 |
""" |
| 1019 |
<Purpose> |
| 1020 |
Apply all passed material or product rules (see source_type) of a given |
| 1021 |
step or inspection (see source_name), to enforce and authorize the |
| 1022 |
corresponding artifacts and to guarantee that artifacts are linked together |
| 1023 |
across steps of the supply chain. |
| 1024 |
|
| 1025 |
The mode of operation is similar to that of a firewall: |
| 1026 |
In the beginning all materials or products of the step or inspection are |
| 1027 |
placed into an artifact queue. The rules are then applied sequentially, |
| 1028 |
consuming artifacts in the queue, i.e. removing them from the queue upon |
| 1029 |
successful application. |
| 1030 |
|
| 1031 |
The consumption of artifacts by itself has no effects on the verification. |
| 1032 |
Only through a subsequent "DISALLOW" rule, that finds unconsumed artifacts, |
| 1033 |
is an exception raised. Similarly does the "REQUIRE" rule raise exception, |
| 1034 |
if it does not find the artifact it requires, because it has falsely been |
| 1035 |
consumed or was not there from the beginning. |
| 1036 |
|
| 1037 |
|
| 1038 |
|
| 1039 |
<Arguments> |
| 1040 |
source_name: |
| 1041 |
The name of the item (step or inspection) being verified. |
| 1042 |
|
| 1043 |
source_type: |
| 1044 |
One of "materials" or "products" depending on whether the rules are |
| 1045 |
taken from the "expected_materials" or "expected_products" field of |
| 1046 |
the item being verified. |
| 1047 |
|
| 1048 |
rules: |
| 1049 |
The list of rules (material or product rules) for the item being |
| 1050 |
verified. |
| 1051 |
|
| 1052 |
links: |
| 1053 |
A dictionary containing link metadata per step or inspection, e.g.: |
| 1054 |
{ |
| 1055 |
<link name> : <Link object>, |
| 1056 |
... |
| 1057 |
} |
| 1058 |
|
| 1059 |
<Exceptions> |
| 1060 |
FormatError |
| 1061 |
if source_type is not "materials" or "products", or |
| 1062 |
if a rule in the passed list of rules does not conform with any rule |
| 1063 |
format. |
| 1064 |
|
| 1065 |
RuleVerificationError |
| 1066 |
if a DISALLOW rule matches disallowed artifacts, or |
| 1067 |
if a REQUIRE rule does not find a required artifact. |
| 1068 |
|
| 1069 |
<Side Effects> |
| 1070 |
Clears and populates the global RULE_TRACE data structure. |
| 1071 |
|
| 1072 |
""" |
| 1073 |
if source_type not in ["materials", "products"]: |
| 1074 |
raise securesystemslib.exceptions.FormatError( |
| 1075 |
"Argument 'source_type' of function 'verify_item_rules' has to be " |
| 1076 |
"one of 'materials' or 'products'. Got: '{}'".format(source_type) |
| 1077 |
) |
| 1078 |
|
| 1079 |
# Create shortcuts to item's materials and products (including hashes), |
| 1080 |
# required to verify "modify" and "match" rules. |
| 1081 |
materials_dict = links[source_name].materials |
| 1082 |
products_dict = links[source_name].products |
| 1083 |
|
| 1084 |
# All other rules only require materials or products paths (without hashes) |
| 1085 |
materials_paths = set(materials_dict.keys()) |
| 1086 |
products_paths = set(products_dict.keys()) |
| 1087 |
|
| 1088 |
# Depending on the source type we create the artifact queue from the item's |
| 1089 |
# materials or products and use it to keep track of (not) consumed artifacts. |
| 1090 |
# The queue also only contains aritfact keys (without hashes) |
| 1091 |
artifacts = getattr(links[source_name], source_type) |
| 1092 |
artifacts_queue = set(artifacts.keys()) |
| 1093 |
|
| 1094 |
# Reset and re-populate rule traceback info dict for a rich error message |
| 1095 |
RULE_TRACE.clear() |
| 1096 |
RULE_TRACE["source_name"] = source_name |
| 1097 |
RULE_TRACE["source_type"] = source_type |
| 1098 |
RULE_TRACE["materials"] = list(materials_dict) |
| 1099 |
RULE_TRACE["products"] = list(products_dict) |
| 1100 |
RULE_TRACE["trace"] = [] |
| 1101 |
|
| 1102 |
# Process rules and remove consumed items from queue in each iteration |
| 1103 |
for rule in rules: |
| 1104 |
LOG.info("Verifying '{}'...".format(" ".join(rule))) |
| 1105 |
|
| 1106 |
# Parse the rule and create two shortcuts to contained rule data |
| 1107 |
rule_data = in_toto.rulelib.unpack_rule(rule) |
| 1108 |
_type = rule_data["rule_type"] |
| 1109 |
_pattern = rule_data["pattern"] |
| 1110 |
|
| 1111 |
# Initialize empty consumed set as fallback for rules that do not consume |
| 1112 |
# artifacts. All rules except "disallow" and "require" consume artifacts. |
| 1113 |
consumed = set() |
| 1114 |
|
| 1115 |
if _type == "match": |
| 1116 |
consumed = verify_match_rule( |
| 1117 |
rule_data, artifacts_queue, artifacts, links |
| 1118 |
) |
| 1119 |
|
| 1120 |
elif _type == "create": |
| 1121 |
consumed = verify_create_rule( |
| 1122 |
_pattern, artifacts_queue, materials_paths, products_paths |
| 1123 |
) |
| 1124 |
|
| 1125 |
elif _type == "delete": |
| 1126 |
consumed = verify_delete_rule( |
| 1127 |
_pattern, artifacts_queue, materials_paths, products_paths |
| 1128 |
) |
| 1129 |
|
| 1130 |
elif _type == "modify": |
| 1131 |
consumed = verify_modify_rule( |
| 1132 |
_pattern, artifacts_queue, materials_dict, products_dict |
| 1133 |
) |
| 1134 |
|
| 1135 |
elif _type == "allow": |
| 1136 |
consumed = verify_allow_rule(_pattern, artifacts_queue) |
| 1137 |
|
| 1138 |
# It's up to the "disallow" and "require" rule to raise an error if |
| 1139 |
# artifacts were not consumed as intended |
| 1140 |
elif _type == "disallow": |
| 1141 |
verify_disallow_rule(_pattern, artifacts_queue) |
| 1142 |
|
| 1143 |
elif _type == "require": |
| 1144 |
verify_require_rule(_pattern, artifacts_queue) |
| 1145 |
|
| 1146 |
else: # pragma: no cover (unreachable) |
| 1147 |
raise securesystemslib.exceptions.FormatError( |
| 1148 |
"Invaldid rule type '{}'.".format(_type) |
| 1149 |
) |
| 1150 |
|
| 1151 |
artifacts_queue -= consumed |
| 1152 |
|
| 1153 |
# Append rule and copy of queue to global info for a rich error message |
| 1154 |
RULE_TRACE["trace"].append( |
| 1155 |
{"rule": rule, "queue": list(artifacts_queue)} |
| 1156 |
) |
| 1157 |
|
| 1158 |
|
| 1159 |
def verify_all_item_rules(items, links): |
| 1160 |
""" |
| 1161 |
<Purpose> |
| 1162 |
Iteratively verifies artifact rules of passed items (Steps or Inspections). |
| 1163 |
|
| 1164 |
<Arguments> |
| 1165 |
items: |
| 1166 |
A list containing Step or Inspection objects whose material |
| 1167 |
and product rules will be verified. |
| 1168 |
|
| 1169 |
links: |
| 1170 |
A dictionary containing link metadata per step or inspection, e.g.: |
| 1171 |
{ |
| 1172 |
<link name> : <Link object>, |
| 1173 |
... |
| 1174 |
} |
| 1175 |
|
| 1176 |
<Exceptions> |
| 1177 |
None. |
| 1178 |
|
| 1179 |
<Side Effects> |
| 1180 |
None. |
| 1181 |
|
| 1182 |
""" |
| 1183 |
for item in items: |
| 1184 |
LOG.info("Verifying material rules for '{}'...".format(item.name)) |
| 1185 |
verify_item_rules( |
| 1186 |
item.name, "materials", item.expected_materials, links |
| 1187 |
) |
| 1188 |
|
| 1189 |
LOG.info("Verifying product rules for '{}'...".format(item.name)) |
| 1190 |
verify_item_rules(item.name, "products", item.expected_products, links) |
| 1191 |
|
| 1192 |
|
| 1193 |
def verify_threshold_constraints(layout, chain_link_dict): |
| 1194 |
""" |
| 1195 |
<Purpose> |
| 1196 |
Verifies that all links corresponding to a given step report the same |
| 1197 |
materials and products. |
| 1198 |
|
| 1199 |
NOTE: This function does not verify if the signatures of each link |
| 1200 |
corresponding to a step are valid or created by a different authorized |
| 1201 |
functionary. This should be done earlier, using the function |
| 1202 |
`verify_link_signature_thresholds`. |
| 1203 |
|
| 1204 |
<Arguments> |
| 1205 |
layout: |
| 1206 |
The layout whose step thresholds are being verified |
| 1207 |
|
| 1208 |
chain_link_dict: |
| 1209 |
A dictionary containing link metadata per functionary per step, |
| 1210 |
e.g.: |
| 1211 |
{ |
| 1212 |
<link name> : { |
| 1213 |
<functionary key id> : <Link object>, |
| 1214 |
... |
| 1215 |
}, ... |
| 1216 |
} |
| 1217 |
|
| 1218 |
<Exceptions> |
| 1219 |
ThresholdVerificationError |
| 1220 |
If there are not enough (threshold) links for a steps |
| 1221 |
|
| 1222 |
If the artifacts for all links of a step are not equal |
| 1223 |
|
| 1224 |
|
| 1225 |
<Side Effects> |
| 1226 |
None. |
| 1227 |
|
| 1228 |
""" |
| 1229 |
|
| 1230 |
# We are only interested in links that are related to steps defined in the |
| 1231 |
# Layout, so iterate over layout.steps |
| 1232 |
for step in layout.steps: |
| 1233 |
# Skip steps that don't require multiple functionaries |
| 1234 |
if step.threshold <= 1: |
| 1235 |
LOG.info( |
| 1236 |
"Skipping threshold verification for step '{0}' with" |
| 1237 |
" threshold '{1}'...".format(step.name, step.threshold) |
| 1238 |
) |
| 1239 |
continue |
| 1240 |
|
| 1241 |
LOG.info( |
| 1242 |
"Verifying threshold for step '{0}' with" |
| 1243 |
" threshold '{1}'...".format(step.name, step.threshold) |
| 1244 |
) |
| 1245 |
# Extract the key_link_dict for this step from the passed chain_link_dict |
| 1246 |
key_link_dict = chain_link_dict[step.name] |
| 1247 |
|
| 1248 |
# Check if we have at least <threshold> links for this step |
| 1249 |
# NOTE: This is already done in `verify_link_signature_thresholds`, |
| 1250 |
# Should we remove the check? |
| 1251 |
if len(key_link_dict) < step.threshold: |
| 1252 |
raise ThresholdVerificationError( |
| 1253 |
"Step '{0}' not performed" |
| 1254 |
" by enough functionaries!".format(step.name) |
| 1255 |
) |
| 1256 |
|
| 1257 |
# Take a reference link (e.g. the first in the step_link_dict) |
| 1258 |
reference_keyid = list(key_link_dict.keys())[0] |
| 1259 |
reference_link = key_link_dict[reference_keyid] |
| 1260 |
|
| 1261 |
# Iterate over all links to compare their properties with a reference_link |
| 1262 |
for keyid, link in key_link_dict.items(): |
| 1263 |
# TODO: Do we only care for artifacts, or do we want to |
| 1264 |
# assert equality of other properties as well? |
| 1265 |
if ( |
| 1266 |
reference_link.materials != link.materials |
| 1267 |
or reference_link.products != link.products |
| 1268 |
): |
| 1269 |
raise ThresholdVerificationError( |
| 1270 |
"Links '{0}' and '{1}' have different" |
| 1271 |
" artifacts!".format( |
| 1272 |
in_toto.models.link.FILENAME_FORMAT.format( |
| 1273 |
step_name=step.name, keyid=reference_keyid |
| 1274 |
), |
| 1275 |
in_toto.models.link.FILENAME_FORMAT.format( |
| 1276 |
step_name=step.name, keyid=keyid |
| 1277 |
), |
| 1278 |
) |
| 1279 |
) |
| 1280 |
|
| 1281 |
|
| 1282 |
def reduce_chain_links(chain_link_dict): |
| 1283 |
""" |
| 1284 |
<Purpose> |
| 1285 |
Iterates through the passed chain_link_dict and builds a dict with |
| 1286 |
step-name as keys and link objects as values. |
| 1287 |
We already check if the links of different functionaries are |
| 1288 |
identical. |
| 1289 |
|
| 1290 |
<Arguments> |
| 1291 |
layout: |
| 1292 |
The layout specified by the project owner against which the |
| 1293 |
threshold will be verified. |
| 1294 |
|
| 1295 |
chain_link_dict: |
| 1296 |
A dictionary containing link metadata per functionary per step, |
| 1297 |
e.g.: |
| 1298 |
{ |
| 1299 |
<link name> : { |
| 1300 |
<functionary key id> : <Link object>, |
| 1301 |
... |
| 1302 |
}, ... |
| 1303 |
} |
| 1304 |
|
| 1305 |
<Exceptions> |
| 1306 |
None. |
| 1307 |
|
| 1308 |
<Side Effects> |
| 1309 |
None. |
| 1310 |
|
| 1311 |
<Returns> |
| 1312 |
A dictionary containing one Link metadata object per step only if |
| 1313 |
the link artifacts of all link objects are identical for a step. |
| 1314 |
|
| 1315 |
""" |
| 1316 |
|
| 1317 |
reduced_chain_link_dict = {} |
| 1318 |
|
| 1319 |
for step_name, key_link_dict in chain_link_dict.items(): |
| 1320 |
# Extract the key_link_dict for this step from the passed chain_link_dict |
| 1321 |
# take one exemplary link (e.g. the first in the step_link_dict) |
| 1322 |
# form the reduced_chain_link_dict to return |
| 1323 |
reduced_chain_link_dict[step_name] = list(key_link_dict.values())[0] |
| 1324 |
|
| 1325 |
return reduced_chain_link_dict |
| 1326 |
|
| 1327 |
|
| 1328 |
def verify_sublayouts(layout, steps_metadata, superlayout_link_dir_path): |
| 1329 |
""" |
| 1330 |
<Purpose> |
| 1331 |
Extracts link or layout object for each step in steps_metadata. Checks if |
| 1332 |
any step has been delegated by the functionary, recurses into the |
| 1333 |
delegation, and replaces the layout object with an equivalent link object. |
| 1334 |
Returns the extracted link objects in a dict called chain_link_dict. |
| 1335 |
|
| 1336 |
<Arguments> |
| 1337 |
layout: |
| 1338 |
The layout specified by the project owner. |
| 1339 |
|
| 1340 |
steps_metadata: |
| 1341 |
A dictionary containing link metadata per functionary per step, |
| 1342 |
e.g.: |
| 1343 |
{ |
| 1344 |
<link name> : { |
| 1345 |
<functionary key id> : <Metadata containing a Link or Layout |
| 1346 |
object>, |
| 1347 |
... |
| 1348 |
}, ... |
| 1349 |
} |
| 1350 |
|
| 1351 |
superlayout_link_dir_path: |
| 1352 |
A path to a directory, where links of the superlayout are loaded |
| 1353 |
from. Links of the sublayout are expected to be in a subdirectory |
| 1354 |
relative to this path, with a name in the format |
| 1355 |
in_toto.models.layout.SUBLAYOUT_LINK_DIR_FORMAT. |
| 1356 |
|
| 1357 |
<Exceptions> |
| 1358 |
raises an Exception if verification of the delegated step fails. |
| 1359 |
|
| 1360 |
<Side Effects> |
| 1361 |
None. |
| 1362 |
|
| 1363 |
<Returns> |
| 1364 |
The passed dictionary containing Link objects instead of metadata per |
| 1365 |
functionary per step, with layouts replaced with summary links. |
| 1366 |
e.g.: |
| 1367 |
{ |
| 1368 |
<link name> : { |
| 1369 |
<functionary key id> : <Link object>, |
| 1370 |
... |
| 1371 |
}, ... |
| 1372 |
} |
| 1373 |
|
| 1374 |
""" |
| 1375 |
chain_link_dict = {} |
| 1376 |
|
| 1377 |
for step_name, metadata_dict in steps_metadata.items(): |
| 1378 |
key_link_dict = {} |
| 1379 |
for keyid, metadata in metadata_dict.items(): |
| 1380 |
payload = metadata.get_payload() |
| 1381 |
|
| 1382 |
if payload.type_ == "layout": |
| 1383 |
LOG.info("Verifying sublayout {}...".format(step_name)) |
| 1384 |
layout_key_dict = {} |
| 1385 |
|
| 1386 |
# Retrieve the entire key object for the keyid |
| 1387 |
# corresponding to the link |
| 1388 |
layout_key_dict = {keyid: layout.keys.get(keyid)} |
| 1389 |
|
| 1390 |
# Sublayout links are expected to be in a directory with the following |
| 1391 |
# name relative the the current link directory path, i.e. if there |
| 1392 |
# are multiple levels of sublayout nesting, the links are expected to |
| 1393 |
# be nested accordingly |
| 1394 |
sub_link_dir = ( |
| 1395 |
in_toto.models.layout.SUBLAYOUT_LINK_DIR_FORMAT.format( |
| 1396 |
name=step_name, keyid=keyid |
| 1397 |
) |
| 1398 |
) |
| 1399 |
|
| 1400 |
sublayout_link_dir_path = os.path.join( |
| 1401 |
superlayout_link_dir_path, sub_link_dir |
| 1402 |
) |
| 1403 |
|
| 1404 |
# Make a recursive call to in_toto_verify with the |
| 1405 |
# layout and the extracted key object |
| 1406 |
summary_link = in_toto_verify( |
| 1407 |
metadata, |
| 1408 |
layout_key_dict, |
| 1409 |
link_dir_path=sublayout_link_dir_path, |
| 1410 |
step_name=step_name, |
| 1411 |
) |
| 1412 |
|
| 1413 |
# Replace the layout object with the link object returned |
| 1414 |
# by in-toto-verify |
| 1415 |
payload = summary_link |
| 1416 |
|
| 1417 |
key_link_dict[keyid] = payload |
| 1418 |
chain_link_dict[step_name] = key_link_dict |
| 1419 |
|
| 1420 |
return chain_link_dict |
| 1421 |
|
| 1422 |
|
| 1423 |
def get_summary_link(layout, reduced_chain_link_dict, name): |
| 1424 |
""" |
| 1425 |
<Purpose> |
| 1426 |
Merges the materials of the first step (as mentioned in the layout) |
| 1427 |
and the products of the last step and returns a new link. |
| 1428 |
This link reports the materials and products and summarizes the |
| 1429 |
overall software supply chain. |
| 1430 |
NOTE: The assumption is that the steps mentioned in the layout are |
| 1431 |
to be performed sequentially. So, the first step mentioned in the |
| 1432 |
layout denotes what comes into the supply chain and the last step |
| 1433 |
denotes what goes out. |
| 1434 |
|
| 1435 |
<Arguments> |
| 1436 |
layout: |
| 1437 |
The layout specified by the project owner. |
| 1438 |
|
| 1439 |
reduced_chain_link_dict: |
| 1440 |
A dictionary containing link metadata per step, |
| 1441 |
e.g.: |
| 1442 |
{ |
| 1443 |
<link name> : <Link object>, |
| 1444 |
... |
| 1445 |
} |
| 1446 |
name: |
| 1447 |
The name that the summary link will be associated with. |
| 1448 |
|
| 1449 |
<Exceptions> |
| 1450 |
None. |
| 1451 |
|
| 1452 |
<Side Effects> |
| 1453 |
None. |
| 1454 |
|
| 1455 |
<Returns> |
| 1456 |
A Link object which summarizes the materials and products of the overall |
| 1457 |
software supply chain. |
| 1458 |
|
| 1459 |
""" |
| 1460 |
# Create empty link object |
| 1461 |
summary_link = in_toto.models.link.Link() |
| 1462 |
|
| 1463 |
# Take first and last link in the order the corresponding |
| 1464 |
# steps appear in the layout, if there are any. |
| 1465 |
if len(layout.steps) > 0: |
| 1466 |
first_step_link = reduced_chain_link_dict[layout.steps[0].name] |
| 1467 |
last_step_link = reduced_chain_link_dict[layout.steps[-1].name] |
| 1468 |
|
| 1469 |
summary_link.materials = first_step_link.materials |
| 1470 |
summary_link.name = name |
| 1471 |
|
| 1472 |
summary_link.products = last_step_link.products |
| 1473 |
summary_link.byproducts = last_step_link.byproducts |
| 1474 |
summary_link.command = last_step_link.command |
| 1475 |
|
| 1476 |
return summary_link |
| 1477 |
|
| 1478 |
|
| 1479 |
def in_toto_verify( |
| 1480 |
metadata, |
| 1481 |
layout_key_dict, |
| 1482 |
link_dir_path=".", |
| 1483 |
substitution_parameters=None, |
| 1484 |
step_name="", |
| 1485 |
persist_inspection_links=True, |
| 1486 |
): |
| 1487 |
"""Performs complete in-toto supply chain verification for a final product. |
| 1488 |
|
| 1489 |
The verification procedure consists of the following activities, performed in |
| 1490 |
the given order: |
| 1491 |
|
| 1492 |
1. Verify layout signatures |
| 1493 |
2. Verify layout expiration date |
| 1494 |
3. Substitute placeholders in the layout |
| 1495 |
4. Load link metadata |
| 1496 |
5. Verify link signatures with keys in layout |
| 1497 |
6. Recurse into sublayout verification |
| 1498 |
7. Soft-verify alignment of reported and expected commands. Note: |
| 1499 |
verification does not fail if commands don't match, instead a warning is |
| 1500 |
logged as per the in-toto specification -- |
| 1501 |
https://github.com/in-toto/docs/blob/master/in-toto-spec.md#431-steps |
| 1502 |
8. Verify threshold artifact constraints |
| 1503 |
9. Process step product and material rules |
| 1504 |
10. Execute inspection commands and generate inspection links |
| 1505 |
11. Process inspection product and material rules |
| 1506 |
|
| 1507 |
Note: in-toto's verification workflow directly uses the key for verifying |
| 1508 |
signatures. It does not communicate with external sources of information for |
| 1509 |
specific attributes about keys. This ensures that verification can be |
| 1510 |
performed in isolation. It is the supply chain owner's responsibility to |
| 1511 |
consider such attributes before using the key to sign the layout or adding |
| 1512 |
it to the layout. For example, in-toto does not rely on the creation time, |
| 1513 |
revocation status, and usage flags for PGP keys. To revoke or otherwise |
| 1514 |
affect the usage of a key, the supply chain owner must sign a new layout |
| 1515 |
with the corresponding changes. |
| 1516 |
|
| 1517 |
Arguments: |
| 1518 |
metadata: A Metadata object that contains a Layout object to be verified. |
| 1519 |
|
| 1520 |
layout_key_dict: A public key dictionary. The verification routine requires |
| 1521 |
at least one key, and a valid signature on the layout for each key. |
| 1522 |
|
| 1523 |
link_dir_path (optional): A directory path to link metadata files. The |
| 1524 |
expected filename format for link metadata files is |
| 1525 |
``STEP-NAME.KEYID-PREFIX.link``. Link metadata files for a sublayout |
| 1526 |
are loaded from a subdirectory relative to the link_dir_path of the |
| 1527 |
superlayout. The expected directory name format is |
| 1528 |
``SUBLAYOUT-STEP-NAME.KEYID-PREFIX``. |
| 1529 |
|
| 1530 |
substitution_parameters (optional): A dictionary with substitution values |
| 1531 |
for artifact rules (steps and inspections), the expected command |
| 1532 |
attribute (steps), and the run attribute (inspections) in the layout. |
| 1533 |
|
| 1534 |
step_name (optional): A name assigned to the returned link. This is mostly |
| 1535 |
useful during recursive sublayout verification. |
| 1536 |
|
| 1537 |
persist_inspection_links (optional): A boolean that determines whether or |
| 1538 |
not link metadata files for inspection are written to cwd. |
| 1539 |
|
| 1540 |
Raises: |
| 1541 |
securesystemslib.exceptions.FormatError: Passed parameters are malformed. |
| 1542 |
|
| 1543 |
SignatureVerificationError: No layout verification key is passed, or any of |
| 1544 |
the passed keys fails to verify a signature. |
| 1545 |
|
| 1546 |
LayoutExpiredError: The layout is expired. |
| 1547 |
|
| 1548 |
LinkNotFoundError: Fewer than threshold link metadata files can be found |
| 1549 |
for a step of the layout. |
| 1550 |
|
| 1551 |
ThresholdVerificationError: Fewer than threshold links, validly signed by |
| 1552 |
different authorized functionaries, who agree on the recorded materials |
| 1553 |
and products, can be found for a step of the layout. (Links with |
| 1554 |
invalid signatures or signatures by unauthorized functionaries are |
| 1555 |
ignored.) |
| 1556 |
|
| 1557 |
RuleVerificationError: A DISALLOW rule matches disallowed artifacts, or |
| 1558 |
a REQUIRE rule does not find a required artifact. |
| 1559 |
|
| 1560 |
BadReturnValueError: An inspection command returns a non-zero value. |
| 1561 |
|
| 1562 |
Side Effects: |
| 1563 |
Reads link metadata files from disk. |
| 1564 |
Runs inspection commands in subprocess. |
| 1565 |
|
| 1566 |
Returns: |
| 1567 |
A Link object, which summarizes the materials and products of the overall |
| 1568 |
software supply chain. This is mostly useful during recursive sublayout |
| 1569 |
verification. |
| 1570 |
|
| 1571 |
""" |
| 1572 |
|
| 1573 |
LOG.info("Verifying layout metadata signatures...") |
| 1574 |
verify_metadata_signatures(metadata, layout_key_dict) |
| 1575 |
|
| 1576 |
# For the rest of the verification we only care about the layout payload |
| 1577 |
# (Layout) that carries all the information and not about the layout |
| 1578 |
# container (Metablock) that also carries the signatures |
| 1579 |
LOG.info("Extracting layout from metadata...") |
| 1580 |
layout = metadata.get_payload() |
| 1581 |
|
| 1582 |
LOG.info("Verifying layout expiration...") |
| 1583 |
verify_layout_expiration(layout) |
| 1584 |
|
| 1585 |
# If there are parameters sent to the translation layer, substitute them |
| 1586 |
if substitution_parameters is not None: |
| 1587 |
LOG.info("Performing parameter substitution...") |
| 1588 |
substitute_parameters(layout, substitution_parameters) |
| 1589 |
|
| 1590 |
LOG.info("Reading link metadata files...") |
| 1591 |
steps_metadata = load_links_for_layout(layout, link_dir_path) |
| 1592 |
|
| 1593 |
LOG.info("Verifying link metadata signatures...") |
| 1594 |
steps_metadata = verify_link_signature_thresholds(layout, steps_metadata) |
| 1595 |
|
| 1596 |
LOG.info("Verifying sublayouts...") |
| 1597 |
chain_link_dict = verify_sublayouts(layout, steps_metadata, link_dir_path) |
| 1598 |
|
| 1599 |
LOG.info("Verifying alignment of reported commands...") |
| 1600 |
verify_all_steps_command_alignment(layout, chain_link_dict) |
| 1601 |
|
| 1602 |
LOG.info("Verifying threshold constraints...") |
| 1603 |
verify_threshold_constraints(layout, chain_link_dict) |
| 1604 |
reduced_chain_link_dict = reduce_chain_links(chain_link_dict) |
| 1605 |
|
| 1606 |
# NOTE: Processing step rules before executing inspections guarantees that |
| 1607 |
# inspection commands don't run on compromised target files, however, this |
| 1608 |
# also precludes step match rules from referencing inspection artifacts. |
| 1609 |
LOG.info("Verifying Step rules...") |
| 1610 |
verify_all_item_rules(layout.steps, reduced_chain_link_dict) |
| 1611 |
|
| 1612 |
LOG.info("Executing Inspection commands...") |
| 1613 |
inspection_link_dict = run_all_inspections(layout, persist_inspection_links) |
| 1614 |
|
| 1615 |
LOG.info("Verifying Inspection rules...") |
| 1616 |
# Artifact rules for inspections can reference links that correspond to |
| 1617 |
# Steps or Inspections, hence the concatenation of both collections of links |
| 1618 |
combined_links = reduced_chain_link_dict.copy() |
| 1619 |
combined_links.update(inspection_link_dict) |
| 1620 |
verify_all_item_rules(layout.inspect, combined_links) |
| 1621 |
|
| 1622 |
# We made it this far without exception that means, verification passed |
| 1623 |
LOG.info("The software product passed all verification.") |
| 1624 |
|
| 1625 |
# Return a link file which summarizes the entire software supply chain |
| 1626 |
# This is mostly relevant if the currently verified supply chain is embedded |
| 1627 |
# in another supply chain |
| 1628 |
return get_summary_link(layout, reduced_chain_link_dict, step_name) |