| 1 |
# Copyright 2021, New York University and the TUF contributors |
| 2 |
# SPDX-License-Identifier: MIT OR Apache-2.0 |
| 3 |
|
| 4 |
"""Test ngclient Updater top-level metadata update workflow""" |
| 5 |
|
| 6 |
from __future__ import annotations |
| 7 |
|
| 8 |
import builtins |
| 9 |
import datetime |
| 10 |
import os |
| 11 |
import sys |
| 12 |
import tempfile |
| 13 |
import unittest |
| 14 |
from datetime import timezone |
| 15 |
from pathlib import Path |
| 16 |
from typing import TYPE_CHECKING |
| 17 |
from unittest.mock import MagicMock, call, patch |
| 18 |
|
| 19 |
import freezegun |
| 20 |
|
| 21 |
from tests import utils |
| 22 |
from tests.repository_simulator import RepositorySimulator |
| 23 |
from tuf.api.exceptions import ( |
| 24 |
BadVersionNumberError, |
| 25 |
DownloadLengthMismatchError, |
| 26 |
ExpiredMetadataError, |
| 27 |
LengthOrHashMismatchError, |
| 28 |
UnsignedMetadataError, |
| 29 |
) |
| 30 |
from tuf.api.metadata import ( |
| 31 |
SPECIFICATION_VERSION, |
| 32 |
TOP_LEVEL_ROLE_NAMES, |
| 33 |
DelegatedRole, |
| 34 |
Metadata, |
| 35 |
Root, |
| 36 |
Snapshot, |
| 37 |
Targets, |
| 38 |
Timestamp, |
| 39 |
) |
| 40 |
from tuf.ngclient import Updater |
| 41 |
|
| 42 |
if TYPE_CHECKING: |
| 43 |
from collections.abc import Iterable |
| 44 |
|
| 45 |
|
| 46 |
class TestRefresh(unittest.TestCase): |
| 47 |
"""Test update of top-level metadata following |
| 48 |
'Detailed client workflow' in the specification.""" |
| 49 |
|
| 50 |
# set dump_dir to trigger repository state dumps |
| 51 |
dump_dir: str | None = None |
| 52 |
|
| 53 |
past_datetime = datetime.datetime.now(timezone.utc).replace( |
| 54 |
microsecond=0 |
| 55 |
) - datetime.timedelta(days=5) |
| 56 |
|
| 57 |
def setUp(self) -> None: |
| 58 |
self.temp_dir = tempfile.TemporaryDirectory() |
| 59 |
self.metadata_dir = os.path.join(self.temp_dir.name, "metadata") |
| 60 |
self.targets_dir = os.path.join(self.temp_dir.name, "targets") |
| 61 |
|
| 62 |
self.sim = RepositorySimulator() |
| 63 |
|
| 64 |
if self.dump_dir is not None: |
| 65 |
# create test specific dump directory |
| 66 |
name = self.id().split(".")[-1] |
| 67 |
self.sim.dump_dir = os.path.join(self.dump_dir, name) |
| 68 |
os.mkdir(self.sim.dump_dir) |
| 69 |
|
| 70 |
def tearDown(self) -> None: |
| 71 |
self.temp_dir.cleanup() |
| 72 |
|
| 73 |
def _run_refresh(self, skip_bootstrap: bool = False) -> Updater: |
| 74 |
"""Create a new Updater instance and refresh""" |
| 75 |
updater = self._init_updater(skip_bootstrap) |
| 76 |
updater.refresh() |
| 77 |
return updater |
| 78 |
|
| 79 |
def _init_updater(self, skip_bootstrap: bool = False) -> Updater: |
| 80 |
"""Create a new Updater instance""" |
| 81 |
if self.dump_dir is not None: |
| 82 |
self.sim.write() |
| 83 |
|
| 84 |
return Updater( |
| 85 |
self.metadata_dir, |
| 86 |
"https://example.com/metadata/", |
| 87 |
self.targets_dir, |
| 88 |
"https://example.com/targets/", |
| 89 |
self.sim, |
| 90 |
bootstrap=None if skip_bootstrap else self.sim.signed_roots[0], |
| 91 |
) |
| 92 |
|
| 93 |
def _assert_files_exist(self, roles: Iterable[str]) -> None: |
| 94 |
"""Assert that local metadata files match 'roles'""" |
| 95 |
expected_files = [f"{role}.json" for role in roles] |
| 96 |
found_files = [ |
| 97 |
e.name for e in os.scandir(self.metadata_dir) if e.is_file() |
| 98 |
] |
| 99 |
|
| 100 |
self.assertListEqual(sorted(found_files), sorted(expected_files)) |
| 101 |
|
| 102 |
def _assert_content_equals( |
| 103 |
self, role: str, version: int | None = None |
| 104 |
) -> None: |
| 105 |
"""Assert that local file content is the expected""" |
| 106 |
expected_content = self.sim.fetch_metadata(role, version) |
| 107 |
with open(os.path.join(self.metadata_dir, f"{role}.json"), "rb") as f: |
| 108 |
self.assertEqual(f.read(), expected_content) |
| 109 |
|
| 110 |
def _assert_version_equals(self, role: str, expected_version: int) -> None: |
| 111 |
"""Assert that local metadata version is the expected""" |
| 112 |
md = Metadata.from_file(os.path.join(self.metadata_dir, f"{role}.json")) |
| 113 |
self.assertEqual(md.signed.version, expected_version) |
| 114 |
|
| 115 |
def test_first_time_refresh(self) -> None: |
| 116 |
# Add one more root version to repository so that |
| 117 |
# refresh() updates from local trusted root (v1) to |
| 118 |
# remote root (v2) |
| 119 |
self.sim.root.version += 1 |
| 120 |
self.sim.publish_root() |
| 121 |
|
| 122 |
self._run_refresh() |
| 123 |
|
| 124 |
self._assert_files_exist(TOP_LEVEL_ROLE_NAMES) |
| 125 |
for role in TOP_LEVEL_ROLE_NAMES: |
| 126 |
version = 2 if role == Root.type else None |
| 127 |
self._assert_content_equals(role, version) |
| 128 |
|
| 129 |
def test_cached_root_missing_without_bootstrap(self) -> None: |
| 130 |
# Run update without a bootstrap, with empty cache: this fails since there is no |
| 131 |
# trusted root |
| 132 |
with self.assertRaises(OSError): |
| 133 |
self._run_refresh(skip_bootstrap=True) |
| 134 |
|
| 135 |
# Metadata dir is empty |
| 136 |
with self.assertRaises(FileNotFoundError): |
| 137 |
os.listdir(self.metadata_dir) |
| 138 |
|
| 139 |
def test_trusted_root_expired(self) -> None: |
| 140 |
# Create an expired root version |
| 141 |
self.sim.root.expires = self.past_datetime |
| 142 |
self.sim.root.version += 1 |
| 143 |
self.sim.publish_root() |
| 144 |
|
| 145 |
# Update to latest root which is expired but still |
| 146 |
# saved as a local root. |
| 147 |
updater = self._init_updater() |
| 148 |
with self.assertRaises(ExpiredMetadataError): |
| 149 |
updater.refresh() |
| 150 |
|
| 151 |
self._assert_files_exist([Root.type]) |
| 152 |
self._assert_content_equals(Root.type, 2) |
| 153 |
|
| 154 |
# Local root metadata can be loaded even if expired |
| 155 |
updater = self._init_updater() |
| 156 |
|
| 157 |
# Create a non-expired root version and refresh |
| 158 |
self.sim.root.expires = self.sim.safe_expiry |
| 159 |
self.sim.root.version += 1 |
| 160 |
self.sim.publish_root() |
| 161 |
updater.refresh() |
| 162 |
|
| 163 |
# Root is successfully updated to latest version |
| 164 |
self._assert_files_exist(TOP_LEVEL_ROLE_NAMES) |
| 165 |
self._assert_content_equals(Root.type, 3) |
| 166 |
|
| 167 |
def test_trusted_root_unsigned_without_bootstrap(self) -> None: |
| 168 |
# Cached root is not signed, bootstrap root is not used |
| 169 |
Path(self.metadata_dir).mkdir(parents=True) |
| 170 |
root_path = os.path.join(self.metadata_dir, "root.json") |
| 171 |
md_root = Metadata.from_bytes(self.sim.signed_roots[0]) |
| 172 |
md_root.signatures.clear() |
| 173 |
md_root.to_file(root_path) |
| 174 |
|
| 175 |
with self.assertRaises(UnsignedMetadataError): |
| 176 |
self._run_refresh(skip_bootstrap=True) |
| 177 |
|
| 178 |
# The update failed, no changes in metadata |
| 179 |
self._assert_files_exist([Root.type]) |
| 180 |
md_root_after = Metadata.from_file(root_path) |
| 181 |
self.assertEqual(md_root.to_bytes(), md_root_after.to_bytes()) |
| 182 |
|
| 183 |
def test_max_root_rotations(self) -> None: |
| 184 |
# Root must stop looking for new versions after Y number of |
| 185 |
# intermediate files were downloaded. |
| 186 |
updater = self._init_updater() |
| 187 |
updater.config.max_root_rotations = 3 |
| 188 |
|
| 189 |
# Create some number of roots greater than 'max_root_rotations' |
| 190 |
while self.sim.root.version < updater.config.max_root_rotations + 3: |
| 191 |
self.sim.root.version += 1 |
| 192 |
self.sim.publish_root() |
| 193 |
|
| 194 |
initial_root_version = 1 |
| 195 |
|
| 196 |
updater.refresh() |
| 197 |
|
| 198 |
# Assert that root version was increased with no more |
| 199 |
# than 'max_root_rotations' |
| 200 |
self._assert_version_equals( |
| 201 |
Root.type, initial_root_version + updater.config.max_root_rotations |
| 202 |
) |
| 203 |
|
| 204 |
def test_intermediate_root_incorrectly_signed(self) -> None: |
| 205 |
# Check for an arbitrary software attack |
| 206 |
|
| 207 |
# Intermediate root v2 is unsigned |
| 208 |
self.sim.root.version += 1 |
| 209 |
root_signers = self.sim.signers[Root.type].copy() |
| 210 |
self.sim.signers[Root.type].clear() |
| 211 |
self.sim.publish_root() |
| 212 |
|
| 213 |
# Final root v3 is correctly signed |
| 214 |
self.sim.root.version += 1 |
| 215 |
self.sim.signers[Root.type] = root_signers |
| 216 |
self.sim.publish_root() |
| 217 |
|
| 218 |
# Incorrectly signed intermediate root is detected |
| 219 |
with self.assertRaises(UnsignedMetadataError): |
| 220 |
self._run_refresh() |
| 221 |
|
| 222 |
# The update failed, latest root version is v1 |
| 223 |
self._assert_files_exist([Root.type]) |
| 224 |
self._assert_content_equals(Root.type, 1) |
| 225 |
|
| 226 |
def test_intermediate_root_expired(self) -> None: |
| 227 |
# The expiration of the new (intermediate) root metadata file |
| 228 |
# does not matter yet |
| 229 |
|
| 230 |
# Intermediate root v2 is expired |
| 231 |
self.sim.root.expires = self.past_datetime |
| 232 |
self.sim.root.version += 1 |
| 233 |
self.sim.publish_root() |
| 234 |
|
| 235 |
# Final root v3 is up to date |
| 236 |
self.sim.root.expires = self.sim.safe_expiry |
| 237 |
self.sim.root.version += 1 |
| 238 |
self.sim.publish_root() |
| 239 |
|
| 240 |
self._run_refresh() |
| 241 |
|
| 242 |
# Successfully updated to root v3 |
| 243 |
self._assert_files_exist(TOP_LEVEL_ROLE_NAMES) |
| 244 |
self._assert_content_equals(Root.type, 3) |
| 245 |
|
| 246 |
def test_final_root_incorrectly_signed(self) -> None: |
| 247 |
# Check for an arbitrary software attack |
| 248 |
self.sim.root.version += 1 # root v2 |
| 249 |
self.sim.signers[Root.type].clear() |
| 250 |
self.sim.publish_root() |
| 251 |
|
| 252 |
with self.assertRaises(UnsignedMetadataError): |
| 253 |
self._run_refresh() |
| 254 |
|
| 255 |
# The update failed, latest root version is v1 |
| 256 |
self._assert_files_exist([Root.type]) |
| 257 |
self._assert_content_equals(Root.type, 1) |
| 258 |
|
| 259 |
def test_new_root_same_version(self) -> None: |
| 260 |
# Check for a rollback_attack |
| 261 |
# Repository serves a root file with the same version as previous |
| 262 |
self.sim.publish_root() |
| 263 |
with self.assertRaises(BadVersionNumberError): |
| 264 |
self._run_refresh() |
| 265 |
|
| 266 |
# The update failed, latest root version is v1 |
| 267 |
self._assert_files_exist([Root.type]) |
| 268 |
self._assert_content_equals(Root.type, 1) |
| 269 |
|
| 270 |
def test_new_root_nonconsecutive_version(self) -> None: |
| 271 |
# Repository serves non-consecutive root version |
| 272 |
self.sim.root.version += 2 |
| 273 |
self.sim.publish_root() |
| 274 |
with self.assertRaises(BadVersionNumberError): |
| 275 |
self._run_refresh() |
| 276 |
|
| 277 |
# The update failed, latest root version is v1 |
| 278 |
self._assert_files_exist([Root.type]) |
| 279 |
self._assert_content_equals(Root.type, 1) |
| 280 |
|
| 281 |
def test_final_root_expired(self) -> None: |
| 282 |
# Check for a freeze attack |
| 283 |
# Final root is expired |
| 284 |
self.sim.root.expires = self.past_datetime |
| 285 |
self.sim.root.version += 1 |
| 286 |
self.sim.publish_root() |
| 287 |
|
| 288 |
with self.assertRaises(ExpiredMetadataError): |
| 289 |
self._run_refresh() |
| 290 |
|
| 291 |
# The update failed but final root is persisted on the file system |
| 292 |
self._assert_files_exist([Root.type]) |
| 293 |
self._assert_content_equals(Root.type, 2) |
| 294 |
|
| 295 |
def test_new_timestamp_unsigned(self) -> None: |
| 296 |
# Check for an arbitrary software attack |
| 297 |
self.sim.signers[Timestamp.type].clear() |
| 298 |
with self.assertRaises(UnsignedMetadataError): |
| 299 |
self._run_refresh() |
| 300 |
|
| 301 |
self._assert_files_exist([Root.type]) |
| 302 |
|
| 303 |
def test_expired_timestamp_version_rollback(self) -> None: |
| 304 |
"""Verifies that local timestamp is used in rollback checks even if it is expired. |
| 305 |
|
| 306 |
The timestamp updates and rollback checks are performed |
| 307 |
with the following timing: |
| 308 |
- Timestamp v1 expiry set to day 7 |
| 309 |
- First updater refresh performed on day 0 |
| 310 |
- Repository publishes timestamp v2 on day 0 |
| 311 |
- Timestamp v2 expiry set to day 21 |
| 312 |
- Second updater refresh performed on day 18: |
| 313 |
assert that rollback check uses expired timestamp v1""" |
| 314 |
|
| 315 |
now = datetime.datetime.now(timezone.utc) |
| 316 |
self.sim.timestamp.expires = now + datetime.timedelta(days=7) |
| 317 |
|
| 318 |
self.sim.timestamp.version = 2 |
| 319 |
|
| 320 |
# Make a successful update of valid metadata which stores it in cache |
| 321 |
self._run_refresh() |
| 322 |
|
| 323 |
self.sim.timestamp.expires = now + datetime.timedelta(days=21) |
| 324 |
|
| 325 |
self.sim.timestamp.version = 1 |
| 326 |
|
| 327 |
patcher = freezegun.freeze_time( |
| 328 |
datetime.datetime.now(timezone.utc) + datetime.timedelta(days=18) |
| 329 |
) |
| 330 |
# Check that a rollback protection is performed even if |
| 331 |
# local timestamp has expired |
| 332 |
with patcher, self.assertRaises(BadVersionNumberError): |
| 333 |
self._run_refresh() |
| 334 |
|
| 335 |
self._assert_version_equals(Timestamp.type, 2) |
| 336 |
|
| 337 |
def test_expired_timestamp_snapshot_rollback(self) -> None: |
| 338 |
"""Verifies that rollback protection is done even if local timestamp has expired. |
| 339 |
|
| 340 |
The snapshot updates and rollback protection checks are performed |
| 341 |
with the following timing: |
| 342 |
- Timestamp v1 expiry set to day 7 |
| 343 |
- Repository bumps snapshot to v3 on day 0 |
| 344 |
- First updater refresh performed on day 0 |
| 345 |
- Timestamp v2 expiry set to day 21 |
| 346 |
- Second updater refresh performed on day 18: |
| 347 |
assert that rollback protection is done with expired timestamp v1""" |
| 348 |
|
| 349 |
now = datetime.datetime.now(timezone.utc) |
| 350 |
self.sim.timestamp.expires = now + datetime.timedelta(days=7) |
| 351 |
|
| 352 |
# Bump the snapshot version number to 3 |
| 353 |
self.sim.update_snapshot() |
| 354 |
self.sim.update_snapshot() |
| 355 |
|
| 356 |
# Make a successful update of valid metadata which stores it in cache |
| 357 |
self._run_refresh() |
| 358 |
|
| 359 |
self.sim.snapshot.version = 1 |
| 360 |
# Snapshot version number is set to 2, which is still less than 3 |
| 361 |
self.sim.update_snapshot() |
| 362 |
self.sim.timestamp.expires = now + datetime.timedelta(days=21) |
| 363 |
|
| 364 |
patcher = freezegun.freeze_time( |
| 365 |
datetime.datetime.now(timezone.utc) + datetime.timedelta(days=18) |
| 366 |
) |
| 367 |
# Assert that rollback protection is done even if |
| 368 |
# local timestamp has expired |
| 369 |
with patcher, self.assertRaises(BadVersionNumberError): |
| 370 |
self._run_refresh() |
| 371 |
|
| 372 |
self._assert_version_equals(Timestamp.type, 3) |
| 373 |
|
| 374 |
def test_new_timestamp_version_rollback(self) -> None: |
| 375 |
# Check for a rollback attack |
| 376 |
self.sim.timestamp.version = 2 |
| 377 |
self._run_refresh() |
| 378 |
|
| 379 |
self.sim.timestamp.version = 1 |
| 380 |
with self.assertRaises(BadVersionNumberError): |
| 381 |
self._run_refresh() |
| 382 |
|
| 383 |
self._assert_version_equals(Timestamp.type, 2) |
| 384 |
|
| 385 |
def test_new_timestamp_snapshot_rollback(self) -> None: |
| 386 |
# Check for a rollback attack. |
| 387 |
self.sim.snapshot.version = 2 |
| 388 |
self.sim.update_timestamp() # timestamp v2 |
| 389 |
self._run_refresh() |
| 390 |
|
| 391 |
# Snapshot meta version is smaller than previous |
| 392 |
self.sim.timestamp.snapshot_meta.version = 1 |
| 393 |
self.sim.timestamp.version += 1 # timestamp v3 |
| 394 |
|
| 395 |
with self.assertRaises(BadVersionNumberError): |
| 396 |
self._run_refresh() |
| 397 |
|
| 398 |
self._assert_version_equals(Timestamp.type, 2) |
| 399 |
|
| 400 |
def test_new_timestamp_expired(self) -> None: |
| 401 |
# Check for a freeze attack |
| 402 |
self.sim.timestamp.expires = self.past_datetime |
| 403 |
self.sim.update_timestamp() |
| 404 |
|
| 405 |
with self.assertRaises(ExpiredMetadataError): |
| 406 |
self._run_refresh() |
| 407 |
|
| 408 |
self._assert_files_exist([Root.type]) |
| 409 |
|
| 410 |
def test_new_timestamp_fast_forward_recovery(self) -> None: |
| 411 |
"""Test timestamp fast-forward recovery using key rotation. |
| 412 |
|
| 413 |
The timestamp recovery is made by the following steps |
| 414 |
- Remove the timestamp key |
| 415 |
- Create and add a new key for timestamp |
| 416 |
- Bump and publish root |
| 417 |
- Rollback the timestamp version |
| 418 |
""" |
| 419 |
|
| 420 |
# attacker updates to a higher version |
| 421 |
self.sim.timestamp.version = 99999 |
| 422 |
|
| 423 |
# client refreshes the metadata and see the new timestamp version |
| 424 |
self._run_refresh() |
| 425 |
self._assert_version_equals(Timestamp.type, 99999) |
| 426 |
|
| 427 |
# repository rotates timestamp keys, rolls back timestamp version |
| 428 |
self.sim.rotate_keys(Timestamp.type) |
| 429 |
self.sim.root.version += 1 |
| 430 |
self.sim.publish_root() |
| 431 |
self.sim.timestamp.version = 1 |
| 432 |
|
| 433 |
# client refresh the metadata and see the initial timestamp version |
| 434 |
self._run_refresh() |
| 435 |
self._assert_version_equals(Timestamp.type, 1) |
| 436 |
|
| 437 |
def test_new_snapshot_hash_mismatch(self) -> None: |
| 438 |
# Check against timestamp role's snapshot hash |
| 439 |
|
| 440 |
# Update timestamp with snapshot's hashes |
| 441 |
self.sim.compute_metafile_hashes_length = True |
| 442 |
self.sim.update_timestamp() # timestamp v2 |
| 443 |
self._run_refresh() |
| 444 |
|
| 445 |
# Modify snapshot contents without updating |
| 446 |
# timestamp's snapshot hash |
| 447 |
self.sim.snapshot.expires += datetime.timedelta(days=1) |
| 448 |
self.sim.snapshot.version += 1 # snapshot v2 |
| 449 |
self.sim.timestamp.snapshot_meta.version = self.sim.snapshot.version |
| 450 |
self.sim.timestamp.version += 1 # timestamp v3 |
| 451 |
|
| 452 |
# Hash mismatch error |
| 453 |
with self.assertRaises(LengthOrHashMismatchError): |
| 454 |
self._run_refresh() |
| 455 |
|
| 456 |
self._assert_version_equals(Timestamp.type, 3) |
| 457 |
self._assert_version_equals(Snapshot.type, 1) |
| 458 |
|
| 459 |
def test_new_snapshot_unsigned(self) -> None: |
| 460 |
# Check for an arbitrary software attack |
| 461 |
self.sim.signers[Snapshot.type].clear() |
| 462 |
with self.assertRaises(UnsignedMetadataError): |
| 463 |
self._run_refresh() |
| 464 |
|
| 465 |
self._assert_files_exist([Root.type, Timestamp.type]) |
| 466 |
|
| 467 |
def test_new_snapshot_version_mismatch(self) -> None: |
| 468 |
# Check against timestamp role's snapshot version |
| 469 |
|
| 470 |
# Increase snapshot version without updating timestamp |
| 471 |
self.sim.snapshot.version += 1 |
| 472 |
with self.assertRaises(BadVersionNumberError): |
| 473 |
self._run_refresh() |
| 474 |
|
| 475 |
self._assert_files_exist([Root.type, Timestamp.type]) |
| 476 |
|
| 477 |
def test_new_snapshot_version_rollback(self) -> None: |
| 478 |
# Check for a rollback attack |
| 479 |
self.sim.snapshot.version = 2 |
| 480 |
self.sim.update_timestamp() |
| 481 |
self._run_refresh() |
| 482 |
|
| 483 |
self.sim.snapshot.version = 1 |
| 484 |
self.sim.update_timestamp() |
| 485 |
|
| 486 |
with self.assertRaises(BadVersionNumberError): |
| 487 |
self._run_refresh() |
| 488 |
|
| 489 |
self._assert_version_equals(Snapshot.type, 2) |
| 490 |
|
| 491 |
def test_new_snapshot_fast_forward_recovery(self) -> None: |
| 492 |
"""Test snapshot fast-forward recovery using key rotation. |
| 493 |
|
| 494 |
The snapshot recovery requires the snapshot and timestamp key rotation. |
| 495 |
It is made by the following steps: |
| 496 |
- Remove the snapshot and timestamp keys |
| 497 |
- Create and add a new key for snapshot and timestamp |
| 498 |
- Rollback snapshot version |
| 499 |
- Bump and publish root |
| 500 |
- Bump the timestamp |
| 501 |
""" |
| 502 |
|
| 503 |
# attacker updates to a higher version (bumping timestamp is required) |
| 504 |
self.sim.snapshot.version = 99999 |
| 505 |
self.sim.update_timestamp() |
| 506 |
|
| 507 |
# client refreshes the metadata and see the new snapshot version |
| 508 |
self._run_refresh() |
| 509 |
self._assert_version_equals(Snapshot.type, 99999) |
| 510 |
|
| 511 |
# repository rotates snapshot & timestamp keys, rolls back snapshot |
| 512 |
self.sim.rotate_keys(Snapshot.type) |
| 513 |
self.sim.rotate_keys(Timestamp.type) |
| 514 |
self.sim.root.version += 1 |
| 515 |
self.sim.publish_root() |
| 516 |
|
| 517 |
self.sim.snapshot.version = 1 |
| 518 |
self.sim.update_timestamp() |
| 519 |
|
| 520 |
# client refresh the metadata and see the initial snapshot version |
| 521 |
self._run_refresh() |
| 522 |
self._assert_version_equals(Snapshot.type, 1) |
| 523 |
|
| 524 |
def test_new_snapshot_expired(self) -> None: |
| 525 |
# Check for a freeze attack |
| 526 |
self.sim.snapshot.expires = self.past_datetime |
| 527 |
self.sim.update_snapshot() |
| 528 |
|
| 529 |
with self.assertRaises(ExpiredMetadataError): |
| 530 |
self._run_refresh() |
| 531 |
|
| 532 |
self._assert_files_exist([Root.type, Timestamp.type]) |
| 533 |
|
| 534 |
def test_new_targets_hash_mismatch(self) -> None: |
| 535 |
# Check against snapshot role's targets hashes |
| 536 |
|
| 537 |
# Update snapshot with target's hashes |
| 538 |
self.sim.compute_metafile_hashes_length = True |
| 539 |
self.sim.update_snapshot() |
| 540 |
self._run_refresh() |
| 541 |
|
| 542 |
# Modify targets contents without updating |
| 543 |
# snapshot's targets hashes |
| 544 |
self.sim.targets.version += 1 |
| 545 |
self.sim.snapshot.meta[ |
| 546 |
"targets.json" |
| 547 |
].version = self.sim.targets.version |
| 548 |
self.sim.snapshot.version += 1 |
| 549 |
self.sim.update_timestamp() |
| 550 |
|
| 551 |
with self.assertRaises(LengthOrHashMismatchError): |
| 552 |
self._run_refresh() |
| 553 |
|
| 554 |
self._assert_version_equals(Snapshot.type, 3) |
| 555 |
self._assert_version_equals(Targets.type, 1) |
| 556 |
|
| 557 |
def test_new_targets_unsigned(self) -> None: |
| 558 |
# Check for an arbitrary software attack |
| 559 |
self.sim.signers[Targets.type].clear() |
| 560 |
with self.assertRaises(UnsignedMetadataError): |
| 561 |
self._run_refresh() |
| 562 |
|
| 563 |
self._assert_files_exist([Root.type, Timestamp.type, Snapshot.type]) |
| 564 |
|
| 565 |
def test_new_targets_version_mismatch(self) -> None: |
| 566 |
# Check against snapshot role's targets version |
| 567 |
|
| 568 |
# Increase targets version without updating snapshot |
| 569 |
self.sim.targets.version += 1 |
| 570 |
with self.assertRaises(BadVersionNumberError): |
| 571 |
self._run_refresh() |
| 572 |
|
| 573 |
self._assert_files_exist([Root.type, Timestamp.type, Snapshot.type]) |
| 574 |
|
| 575 |
def test_new_targets_expired(self) -> None: |
| 576 |
# Check for a freeze attack. |
| 577 |
self.sim.targets.expires = self.past_datetime |
| 578 |
self.sim.update_snapshot() |
| 579 |
|
| 580 |
with self.assertRaises(ExpiredMetadataError): |
| 581 |
self._run_refresh() |
| 582 |
|
| 583 |
self._assert_files_exist([Root.type, Timestamp.type, Snapshot.type]) |
| 584 |
|
| 585 |
def test_compute_metafile_hashes_length(self) -> None: |
| 586 |
self.sim.compute_metafile_hashes_length = True |
| 587 |
self.sim.update_snapshot() |
| 588 |
self._run_refresh() |
| 589 |
self._assert_version_equals(Timestamp.type, 2) |
| 590 |
self._assert_version_equals(Snapshot.type, 2) |
| 591 |
|
| 592 |
self.sim.compute_metafile_hashes_length = False |
| 593 |
self.sim.update_snapshot() |
| 594 |
self._run_refresh() |
| 595 |
|
| 596 |
self._assert_version_equals(Timestamp.type, 3) |
| 597 |
self._assert_version_equals(Snapshot.type, 3) |
| 598 |
|
| 599 |
def test_new_targets_fast_forward_recovery(self) -> None: |
| 600 |
"""Test targets fast-forward recovery using key rotation. |
| 601 |
|
| 602 |
The targets recovery is made by issuing new Snapshot keys, by following |
| 603 |
steps: |
| 604 |
- Remove the snapshot key |
| 605 |
- Create and add a new key for snapshot |
| 606 |
- Bump and publish root |
| 607 |
- Rollback the target version |
| 608 |
""" |
| 609 |
# attacker updates to a higher version |
| 610 |
self.sim.targets.version = 99999 |
| 611 |
self.sim.update_snapshot() |
| 612 |
|
| 613 |
# client refreshes the metadata and see the new targets version |
| 614 |
self._run_refresh() |
| 615 |
self._assert_version_equals(Targets.type, 99999) |
| 616 |
|
| 617 |
# repository rotates snapshot keys, rolls back targets version |
| 618 |
self.sim.rotate_keys(Snapshot.type) |
| 619 |
self.sim.root.version += 1 |
| 620 |
self.sim.publish_root() |
| 621 |
|
| 622 |
self.sim.targets.version = 1 |
| 623 |
self.sim.update_snapshot() |
| 624 |
|
| 625 |
# client refreshes the metadata version and see initial targets version |
| 626 |
self._run_refresh() |
| 627 |
self._assert_version_equals(Targets.type, 1) |
| 628 |
|
| 629 |
@patch.object(builtins, "open", wraps=builtins.open) |
| 630 |
def test_not_loading_targets_twice(self, wrapped_open: MagicMock) -> None: |
| 631 |
# Do not load targets roles more than once when traversing |
| 632 |
# the delegations tree |
| 633 |
|
| 634 |
# Add new delegated targets, update the snapshot |
| 635 |
spec_version = ".".join(SPECIFICATION_VERSION) |
| 636 |
targets = Targets(1, spec_version, self.sim.safe_expiry, {}, None) |
| 637 |
role = DelegatedRole("role1", [], 1, False, ["*"], None) |
| 638 |
self.sim.add_delegation("targets", role, targets) |
| 639 |
self.sim.update_snapshot() |
| 640 |
|
| 641 |
# Run refresh, top-level roles are loaded |
| 642 |
updater = self._run_refresh() |
| 643 |
# Clean up calls to open during refresh() |
| 644 |
wrapped_open.reset_mock() |
| 645 |
|
| 646 |
# First time looking for "somepath", only 'role1' must be loaded |
| 647 |
updater.get_targetinfo("somepath") |
| 648 |
wrapped_open.assert_called_once_with( |
| 649 |
os.path.join(self.metadata_dir, "role1.json"), "rb" |
| 650 |
) |
| 651 |
wrapped_open.reset_mock() |
| 652 |
# Second call to get_targetinfo, all metadata is already loaded |
| 653 |
updater.get_targetinfo("somepath") |
| 654 |
wrapped_open.assert_not_called() |
| 655 |
|
| 656 |
def test_snapshot_rollback_with_local_snapshot_hash_mismatch(self) -> None: |
| 657 |
# Test triggering snapshot rollback check on a newly downloaded snapshot |
| 658 |
# when the local snapshot is loaded even when there is a hash mismatch |
| 659 |
# with timestamp.snapshot_meta. |
| 660 |
|
| 661 |
# By raising this flag on timestamp update the simulator would: |
| 662 |
# 1) compute the hash of the new modified version of snapshot |
| 663 |
# 2) assign the hash to timestamp.snapshot_meta |
| 664 |
# The purpose is to create a hash mismatch between timestamp.meta and |
| 665 |
# the local snapshot, but to have hash match between timestamp.meta and |
| 666 |
# the next snapshot version. |
| 667 |
self.sim.compute_metafile_hashes_length = True |
| 668 |
|
| 669 |
# Initialize all metadata and assign targets version higher than 1. |
| 670 |
self.sim.targets.version = 2 |
| 671 |
self.sim.update_snapshot() |
| 672 |
self._run_refresh() |
| 673 |
|
| 674 |
# The new targets must have a lower version than the local trusted one. |
| 675 |
self.sim.targets.version = 1 |
| 676 |
self.sim.update_snapshot() |
| 677 |
|
| 678 |
# During the snapshot update, the local snapshot will be loaded even if |
| 679 |
# there is a hash mismatch with timestamp.snapshot_meta, because it will |
| 680 |
# be considered as trusted. |
| 681 |
# Should fail as a new version of snapshot will be fetched which lowers |
| 682 |
# the snapshot.meta["targets.json"] version by 1 and throws an error. |
| 683 |
with self.assertRaises(BadVersionNumberError): |
| 684 |
self._run_refresh() |
| 685 |
|
| 686 |
@patch.object(builtins, "open", wraps=builtins.open) |
| 687 |
def test_load_metadata_from_cache(self, wrapped_open: MagicMock) -> None: |
| 688 |
# Add new delegated targets |
| 689 |
spec_version = ".".join(SPECIFICATION_VERSION) |
| 690 |
targets = Targets(1, spec_version, self.sim.safe_expiry, {}, None) |
| 691 |
role = DelegatedRole("role1", [], 1, False, ["*"], None) |
| 692 |
self.sim.add_delegation("targets", role, targets) |
| 693 |
self.sim.update_snapshot() |
| 694 |
|
| 695 |
# Make a successful update of valid metadata which stores it in cache |
| 696 |
updater = self._run_refresh() |
| 697 |
updater.get_targetinfo("non_existent_target") |
| 698 |
|
| 699 |
# Clear statistics for open() calls and metadata requests |
| 700 |
wrapped_open.reset_mock() |
| 701 |
self.sim.fetch_tracker.metadata.clear() |
| 702 |
|
| 703 |
# Create a new updater and perform a second update while |
| 704 |
# the metadata is already stored in cache (metadata dir) |
| 705 |
updater = self._init_updater() |
| 706 |
updater.get_targetinfo("non_existent_target") |
| 707 |
|
| 708 |
# Test that metadata is loaded from cache and not downloaded |
| 709 |
root_dir = os.path.join(self.metadata_dir, "root_history") |
| 710 |
wrapped_open.assert_has_calls( |
| 711 |
[ |
| 712 |
call(os.path.join(root_dir, "2.root.json"), "rb"), |
| 713 |
call(os.path.join(self.metadata_dir, "timestamp.json"), "rb"), |
| 714 |
call(os.path.join(self.metadata_dir, "snapshot.json"), "rb"), |
| 715 |
call(os.path.join(self.metadata_dir, "targets.json"), "rb"), |
| 716 |
call(os.path.join(self.metadata_dir, "role1.json"), "rb"), |
| 717 |
] |
| 718 |
) |
| 719 |
|
| 720 |
expected_calls = [("root", 2), ("timestamp", None)] |
| 721 |
self.assertListEqual(self.sim.fetch_tracker.metadata, expected_calls) |
| 722 |
|
| 723 |
@patch.object(builtins, "open", wraps=builtins.open) |
| 724 |
def test_intermediate_root_cache(self, wrapped_open: MagicMock) -> None: |
| 725 |
"""Test that refresh uses the intermediate roots from cache""" |
| 726 |
# Add root versions 2, 3 |
| 727 |
self.sim.root.version += 1 |
| 728 |
self.sim.publish_root() |
| 729 |
self.sim.root.version += 1 |
| 730 |
self.sim.publish_root() |
| 731 |
|
| 732 |
# Make a successful update of valid metadata which stores it in cache |
| 733 |
self._run_refresh() |
| 734 |
|
| 735 |
# assert that cache lookups happened but data was downloaded from remote |
| 736 |
root_dir = os.path.join(self.metadata_dir, "root_history") |
| 737 |
wrapped_open.assert_has_calls( |
| 738 |
[ |
| 739 |
call(os.path.join(root_dir, "2.root.json"), "rb"), |
| 740 |
call(os.path.join(root_dir, "3.root.json"), "rb"), |
| 741 |
call(os.path.join(root_dir, "4.root.json"), "rb"), |
| 742 |
call(os.path.join(self.metadata_dir, "timestamp.json"), "rb"), |
| 743 |
call(os.path.join(self.metadata_dir, "snapshot.json"), "rb"), |
| 744 |
call(os.path.join(self.metadata_dir, "targets.json"), "rb"), |
| 745 |
] |
| 746 |
) |
| 747 |
expected_calls = [ |
| 748 |
("root", 2), |
| 749 |
("root", 3), |
| 750 |
("root", 4), |
| 751 |
("timestamp", None), |
| 752 |
("snapshot", 1), |
| 753 |
("targets", 1), |
| 754 |
] |
| 755 |
self.assertListEqual(self.sim.fetch_tracker.metadata, expected_calls) |
| 756 |
|
| 757 |
# Clear statistics for open() calls and metadata requests |
| 758 |
wrapped_open.reset_mock() |
| 759 |
self.sim.fetch_tracker.metadata.clear() |
| 760 |
|
| 761 |
# Run update again, assert that metadata from cache was used (including intermediate roots) |
| 762 |
self._run_refresh() |
| 763 |
wrapped_open.assert_has_calls( |
| 764 |
[ |
| 765 |
call(os.path.join(root_dir, "2.root.json"), "rb"), |
| 766 |
call(os.path.join(root_dir, "3.root.json"), "rb"), |
| 767 |
call(os.path.join(root_dir, "4.root.json"), "rb"), |
| 768 |
call(os.path.join(self.metadata_dir, "timestamp.json"), "rb"), |
| 769 |
call(os.path.join(self.metadata_dir, "snapshot.json"), "rb"), |
| 770 |
call(os.path.join(self.metadata_dir, "targets.json"), "rb"), |
| 771 |
] |
| 772 |
) |
| 773 |
expected_calls = [("root", 4), ("timestamp", None)] |
| 774 |
self.assertListEqual(self.sim.fetch_tracker.metadata, expected_calls) |
| 775 |
|
| 776 |
def test_intermediate_root_cache_poisoning(self) -> None: |
| 777 |
"""Test that refresh works as expected when intermediate roots in cache are poisoned""" |
| 778 |
# Add root versions 2, 3 |
| 779 |
self.sim.root.version += 1 |
| 780 |
self.sim.publish_root() |
| 781 |
self.sim.root.version += 1 |
| 782 |
self.sim.publish_root() |
| 783 |
|
| 784 |
# Make a successful update of valid metadata which stores it in cache |
| 785 |
self._run_refresh() |
| 786 |
|
| 787 |
# Modify cached intermediate root v2 so that it's no longer signed correctly |
| 788 |
root_path = os.path.join( |
| 789 |
self.metadata_dir, "root_history", "2.root.json" |
| 790 |
) |
| 791 |
md = Metadata.from_file(root_path) |
| 792 |
md.signatures.clear() |
| 793 |
md.to_file(root_path) |
| 794 |
|
| 795 |
# Clear statistics for metadata requests |
| 796 |
self.sim.fetch_tracker.metadata.clear() |
| 797 |
|
| 798 |
# Update again, assert that intermediate root v2 was downloaded again |
| 799 |
self._run_refresh() |
| 800 |
|
| 801 |
expected_calls = [("root", 2), ("root", 4), ("timestamp", None)] |
| 802 |
self.assertListEqual(self.sim.fetch_tracker.metadata, expected_calls) |
| 803 |
|
| 804 |
# Clear statistics for metadata requests |
| 805 |
self.sim.fetch_tracker.metadata.clear() |
| 806 |
|
| 807 |
# Update again, this time assert that intermediate root v2 was used from cache |
| 808 |
self._run_refresh() |
| 809 |
|
| 810 |
expected_calls = [("root", 4), ("timestamp", None)] |
| 811 |
self.assertListEqual(self.sim.fetch_tracker.metadata, expected_calls) |
| 812 |
|
| 813 |
def test_expired_metadata(self) -> None: |
| 814 |
"""Verifies that expired local timestamp/snapshot can be used for |
| 815 |
updating from remote. |
| 816 |
|
| 817 |
The updates and verifications are performed with the following timing: |
| 818 |
- Timestamp v1 expiry set to day 7 |
| 819 |
- First updater refresh performed on day 0 |
| 820 |
- Repository bumps snapshot and targets to v2 on day 0 |
| 821 |
- Timestamp v2 expiry set to day 21 |
| 822 |
- Second updater refresh performed on day 18, |
| 823 |
it is successful and timestamp/snapshot final versions are v2""" |
| 824 |
|
| 825 |
now = datetime.datetime.now(timezone.utc) |
| 826 |
self.sim.timestamp.expires = now + datetime.timedelta(days=7) |
| 827 |
|
| 828 |
# Make a successful update of valid metadata which stores it in cache |
| 829 |
self._run_refresh() |
| 830 |
|
| 831 |
self.sim.targets.version += 1 |
| 832 |
self.sim.update_snapshot() |
| 833 |
self.sim.timestamp.expires = now + datetime.timedelta(days=21) |
| 834 |
|
| 835 |
# Mocking time so that local timestam has expired |
| 836 |
# but the new timestamp has not |
| 837 |
with freezegun.freeze_time( |
| 838 |
datetime.datetime.now(timezone.utc) + datetime.timedelta(days=18) |
| 839 |
): |
| 840 |
self._run_refresh() |
| 841 |
|
| 842 |
# Assert that the final version of timestamp/snapshot is version 2 |
| 843 |
# which means a successful refresh is performed |
| 844 |
# with expired local metadata |
| 845 |
for role in ["timestamp", "snapshot", "targets"]: |
| 846 |
md = Metadata.from_file( |
| 847 |
os.path.join(self.metadata_dir, f"{role}.json") |
| 848 |
) |
| 849 |
self.assertEqual(md.signed.version, 2) |
| 850 |
|
| 851 |
def test_max_metadata_lengths(self) -> None: |
| 852 |
"""Test that clients configured max metadata lengths are respected""" |
| 853 |
|
| 854 |
# client has root v1 already: create a new one available for download |
| 855 |
self.sim.root.version += 1 |
| 856 |
self.sim.publish_root() |
| 857 |
|
| 858 |
config_vars = [ |
| 859 |
"root_max_length", |
| 860 |
"timestamp_max_length", |
| 861 |
"snapshot_max_length", |
| 862 |
"targets_max_length", |
| 863 |
] |
| 864 |
# make sure going over any length limit raises DownloadLengthMismatchError |
| 865 |
for var_name in config_vars: |
| 866 |
updater = self._init_updater() |
| 867 |
setattr(updater.config, var_name, 100) |
| 868 |
with self.assertRaises(DownloadLengthMismatchError): |
| 869 |
updater.refresh() |
| 870 |
|
| 871 |
# All good with normal length limits |
| 872 |
updater = self._init_updater() |
| 873 |
updater.refresh() |
| 874 |
|
| 875 |
def test_timestamp_eq_versions_check(self) -> None: |
| 876 |
# Test that a modified timestamp with different content, but the same |
| 877 |
# version doesn't replace the valid locally stored one. |
| 878 |
|
| 879 |
# Make a successful update of valid metadata which stores it in cache |
| 880 |
self._run_refresh() |
| 881 |
initial_timestamp_meta_ver = self.sim.timestamp.snapshot_meta.version |
| 882 |
|
| 883 |
# Change timestamp without bumping its version in order to test if a new |
| 884 |
# timestamp with the same version will be persisted. |
| 885 |
self.sim.timestamp.snapshot_meta.version = 100 |
| 886 |
self._run_refresh() |
| 887 |
|
| 888 |
# If the local timestamp md file has the same snapshot_meta.version as |
| 889 |
# the initial one, then the new modified timestamp has not been stored. |
| 890 |
timestamp_path = os.path.join(self.metadata_dir, "timestamp.json") |
| 891 |
timestamp: Metadata[Timestamp] = Metadata.from_file(timestamp_path) |
| 892 |
self.assertEqual( |
| 893 |
initial_timestamp_meta_ver, timestamp.signed.snapshot_meta.version |
| 894 |
) |
| 895 |
|
| 896 |
|
| 897 |
if __name__ == "__main__": |
| 898 |
if "--dump" in sys.argv: |
| 899 |
TestRefresh.dump_dir = tempfile.mkdtemp() |
| 900 |
print(f"Repository Simulator dumps in {TestRefresh.dump_dir}") |
| 901 |
sys.argv.remove("--dump") |
| 902 |
|
| 903 |
utils.configure_test_logging(sys.argv) |
| 904 |
unittest.main() |