-
Notifications
You must be signed in to change notification settings - Fork 275
/
repository_lib.py
2306 lines (1753 loc) · 83.5 KB
/
repository_lib.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# Copyright 2014 - 2017, New York University and the TUF contributors
# SPDX-License-Identifier: MIT OR Apache-2.0
"""
<Program Name>
repository_lib.py
<Author>
Vladimir Diaz <[email protected]>
<Started>
June 1, 2014.
<Copyright>
See LICENSE-MIT OR LICENSE for licensing information.
<Purpose>
Provide a library for the repository tool that can create a TUF repository.
The repository tool can be used with the Python interpreter in interactive
mode, or imported directly into a Python module. See 'tuf/README' for the
complete guide to using 'tuf.repository_tool.py'.
"""
import os
import errno
import time
import logging
import shutil
import json
import tempfile
import securesystemslib # pylint: disable=unused-import
from securesystemslib import exceptions as sslib_exceptions
from securesystemslib import formats as sslib_formats
from securesystemslib import hash as sslib_hash
from securesystemslib import interface as sslib_interface
from securesystemslib import keys as sslib_keys
from securesystemslib import util as sslib_util
from securesystemslib import storage as sslib_storage
from tuf import exceptions
from tuf import formats
from tuf import keydb
from tuf import log
from tuf import roledb
from tuf import settings
from tuf import sig
# See 'log.py' to learn how logging is handled in TUF.
logger = logging.getLogger(__name__)
# The extension of TUF metadata.
METADATA_EXTENSION = '.json'
# The targets and metadata directory names. Metadata files are written
# to the staged metadata directory instead of the "live" one.
METADATA_STAGED_DIRECTORY_NAME = 'metadata.staged'
METADATA_DIRECTORY_NAME = 'metadata'
TARGETS_DIRECTORY_NAME = 'targets'
# The metadata filenames of the top-level roles.
ROOT_FILENAME = 'root' + METADATA_EXTENSION
TARGETS_FILENAME = 'targets' + METADATA_EXTENSION
SNAPSHOT_FILENAME = 'snapshot' + METADATA_EXTENSION
TIMESTAMP_FILENAME = 'timestamp' + METADATA_EXTENSION
# Log warning when metadata expires in n days, or less.
# root = 1 month, snapshot = 1 day, targets = 10 days, timestamp = 1 day.
ROOT_EXPIRES_WARN_SECONDS = 2630000
SNAPSHOT_EXPIRES_WARN_SECONDS = 86400
TARGETS_EXPIRES_WARN_SECONDS = 864000
TIMESTAMP_EXPIRES_WARN_SECONDS = 86400
# Supported key types.
SUPPORTED_KEY_TYPES = ['rsa', 'ed25519', 'ecdsa', 'ecdsa-sha2-nistp256']
# The algorithm used by the repository to generate the path hash prefixes
# of hashed bin delegations. Please see delegate_hashed_bins()
HASH_FUNCTION = settings.DEFAULT_HASH_ALGORITHM
def _generate_and_write_metadata(rolename, metadata_filename,
targets_directory, metadata_directory, storage_backend,
consistent_snapshot=False, filenames=None, allow_partially_signed=False,
increment_version_number=True, repository_name='default',
use_existing_fileinfo=False, use_timestamp_length=True,
use_timestamp_hashes=True, use_snapshot_length=False,
use_snapshot_hashes=False):
"""
Non-public function that can generate and write the metadata for the
specified 'rolename'. It also increments the version number of 'rolename' if
the 'increment_version_number' argument is True.
"""
metadata = None
# Retrieve the roleinfo of 'rolename' to extract the needed metadata
# attributes, such as version number, expiration, etc.
roleinfo = roledb.get_roleinfo(rolename, repository_name)
previous_keyids = roleinfo.get('previous_keyids', [])
previous_threshold = roleinfo.get('previous_threshold', 1)
signing_keyids = sorted(set(roleinfo['signing_keyids']))
# Generate the appropriate role metadata for 'rolename'.
if rolename == 'root':
metadata = generate_root_metadata(roleinfo['version'], roleinfo['expires'],
consistent_snapshot, repository_name)
_log_warning_if_expires_soon(ROOT_FILENAME, roleinfo['expires'],
ROOT_EXPIRES_WARN_SECONDS)
elif rolename == 'snapshot':
metadata = generate_snapshot_metadata(metadata_directory,
roleinfo['version'], roleinfo['expires'],
storage_backend, consistent_snapshot, repository_name,
use_length=use_snapshot_length, use_hashes=use_snapshot_hashes)
_log_warning_if_expires_soon(SNAPSHOT_FILENAME, roleinfo['expires'],
SNAPSHOT_EXPIRES_WARN_SECONDS)
elif rolename == 'timestamp':
# If filenames don't have "snapshot_filename" key, defaults to "snapshot.json"
snapshot_file_path = (filenames and filenames['snapshot']) \
or SNAPSHOT_FILENAME
metadata = generate_timestamp_metadata(snapshot_file_path, roleinfo['version'],
roleinfo['expires'], storage_backend, repository_name,
use_length=use_timestamp_length, use_hashes=use_timestamp_hashes)
_log_warning_if_expires_soon(TIMESTAMP_FILENAME, roleinfo['expires'],
TIMESTAMP_EXPIRES_WARN_SECONDS)
# All other roles are either the top-level 'targets' role, or
# a delegated role.
else:
# Only print a warning if the top-level 'targets' role expires soon.
if rolename == 'targets':
_log_warning_if_expires_soon(TARGETS_FILENAME, roleinfo['expires'],
TARGETS_EXPIRES_WARN_SECONDS)
# Don't hash-prefix consistent target files if they are handled out of band
consistent_targets = consistent_snapshot and not use_existing_fileinfo
metadata = generate_targets_metadata(targets_directory,
roleinfo['paths'], roleinfo['version'], roleinfo['expires'],
roleinfo['delegations'], consistent_targets, use_existing_fileinfo,
storage_backend, repository_name)
# Update roledb with the latest delegations info collected during
# generate_targets_metadata()
roledb.update_roleinfo(rolename, roleinfo,
repository_name=repository_name)
# Before writing 'rolename' to disk, automatically increment its version
# number (if 'increment_version_number' is True) so that the caller does not
# have to manually perform this action. The version number should be
# incremented in both the metadata file and roledb (required so that Snapshot
# references the latest version).
# Store the 'current_version' in case the version number must be restored
# (e.g., if 'rolename' cannot be written to disk because its metadata is not
# properly signed).
current_version = metadata['version']
if increment_version_number:
roleinfo = roledb.get_roleinfo(rolename, repository_name)
metadata['version'] = metadata['version'] + 1
roleinfo['version'] = roleinfo['version'] + 1
roledb.update_roleinfo(rolename, roleinfo,
repository_name=repository_name)
else:
logger.debug('Not incrementing ' + repr(rolename) + '\'s version number.')
if rolename in roledb.TOP_LEVEL_ROLES and not allow_partially_signed:
# Verify that the top-level 'rolename' is fully signed. Only a delegated
# role should not be written to disk without full verification of its
# signature(s), since it can only be considered fully signed depending on
# the delegating role.
signable = sign_metadata(metadata, signing_keyids, metadata_filename,
repository_name)
def should_write():
# Root must be signed by its previous keys and threshold.
if rolename == 'root' and len(previous_keyids) > 0:
if not sig.verify(signable, rolename, repository_name,
previous_threshold, previous_keyids):
return False
else:
logger.debug('Root is signed by a threshold of its previous keyids.')
# In the normal case, we should write metadata if the threshold is met.
return sig.verify(signable, rolename, repository_name,
roleinfo['threshold'], roleinfo['signing_keyids'])
if should_write():
_remove_invalid_and_duplicate_signatures(signable, repository_name)
# Root should always be written as if consistent_snapshot is True (i.e.,
# write <version>.root.json and root.json to disk).
if rolename == 'root':
consistent_snapshot = True
filename = write_metadata_file(signable, metadata_filename,
metadata['version'], consistent_snapshot, storage_backend)
# 'signable' contains an invalid threshold of signatures.
else:
# Since new metadata cannot be successfully written, restore the current
# version number.
roleinfo = roledb.get_roleinfo(rolename, repository_name)
roleinfo['version'] = current_version
roledb.update_roleinfo(rolename, roleinfo,
repository_name=repository_name)
# Note that 'signable' is an argument to tuf.UnsignedMetadataError().
raise exceptions.UnsignedMetadataError('Not enough'
' signatures for ' + repr(metadata_filename), signable)
# 'rolename' is a delegated role or a top-level role that is partially
# signed, and thus its signatures should not be verified.
else:
signable = sign_metadata(metadata, signing_keyids, metadata_filename,
repository_name)
_remove_invalid_and_duplicate_signatures(signable, repository_name)
# Root should always be written as if consistent_snapshot is True (i.e.,
# <version>.root.json and root.json).
if rolename == 'root':
filename = write_metadata_file(signable, metadata_filename,
metadata['version'], consistent_snapshot=True,
storage_backend=storage_backend)
else:
filename = write_metadata_file(signable, metadata_filename,
metadata['version'], consistent_snapshot, storage_backend)
return signable, filename
def _metadata_is_partially_loaded(rolename, signable, repository_name):
"""
Non-public function that determines whether 'rolename' is loaded with
at least zero good signatures, but an insufficient threshold (which means
'rolename' was written to disk with repository.write_partial()). A repository
maintainer may write partial metadata without including a valid signature.
However, the final repository.write() must include a threshold number of
signatures.
If 'rolename' is found to be partially loaded, mark it as partially loaded in
its 'roledb' roleinfo. This function exists to assist in deciding whether
a role's version number should be incremented when write() or write_parital()
is called. Return True if 'rolename' was partially loaded, False otherwise.
"""
# The signature status lists the number of good signatures, including
# bad, untrusted, unknown, etc.
status = sig.get_signature_status(signable, rolename, repository_name)
if len(status['good_sigs']) < status['threshold'] and \
len(status['good_sigs']) >= 0:
return True
else:
return False
def _check_role_keys(rolename, repository_name):
"""
Non-public function that verifies the public and signing keys of 'rolename'.
If either contain an invalid threshold of keys, raise an exception.
"""
# Extract the total number of public and private keys of 'rolename' from its
# roleinfo in 'roledb'.
roleinfo = roledb.get_roleinfo(rolename, repository_name)
total_keyids = len(roleinfo['keyids'])
threshold = roleinfo['threshold']
total_signatures = len(roleinfo['signatures'])
total_signing_keys = len(roleinfo['signing_keyids'])
# Raise an exception for an invalid threshold of public keys.
if total_keyids < threshold:
raise exceptions.InsufficientKeysError(repr(rolename) + ' role contains'
' ' + repr(total_keyids) + ' / ' + repr(threshold) + ' public keys.')
# Raise an exception for an invalid threshold of signing keys.
if total_signatures == 0 and total_signing_keys < threshold:
raise exceptions.InsufficientKeysError(repr(rolename) + ' role contains'
' ' + repr(total_signing_keys) + ' / ' + repr(threshold) + ' signing keys.')
def _remove_invalid_and_duplicate_signatures(signable, repository_name):
"""
Non-public function that removes invalid or duplicate signatures from
'signable'. 'signable' may contain signatures (invalid) from previous
versions of the metadata that were loaded with load_repository(). Invalid,
or duplicate signatures, are removed from 'signable'.
"""
# Store the keyids of valid signatures. 'signature_keyids' is checked for
# duplicates rather than comparing signature objects because PSS may generate
# duplicate valid signatures for the same data, yet contain different
# signatures.
signature_keyids = []
for signature in signable['signatures']:
signed = sslib_formats.encode_canonical(signable['signed']).encode('utf-8')
keyid = signature['keyid']
key = None
# Remove 'signature' from 'signable' if the listed keyid does not exist
# in 'keydb'.
try:
key = keydb.get_key(keyid, repository_name=repository_name)
except exceptions.UnknownKeyError:
signable['signatures'].remove(signature)
continue
# Remove 'signature' from 'signable' if it is an invalid signature.
if not sslib_keys.verify_signature(key, signature, signed):
logger.debug('Removing invalid signature for ' + repr(keyid))
signable['signatures'].remove(signature)
# Although valid, it may still need removal if it is a duplicate. Check
# the keyid, rather than the signature, to remove duplicate PSS signatures.
# PSS may generate multiple different signatures for the same keyid.
else:
if keyid in signature_keyids:
signable['signatures'].remove(signature)
# 'keyid' is valid and not a duplicate, so add it to 'signature_keyids'.
else:
signature_keyids.append(keyid)
def _delete_obsolete_metadata(metadata_directory, snapshot_metadata,
consistent_snapshot, repository_name, storage_backend):
"""
Non-public function that deletes metadata files marked as removed by
'repository_tool.py'. Revoked metadata files are not actually deleted until
this function is called. Obsolete metadata should *not* be retained in
"metadata.staged", otherwise they may be re-loaded by 'load_repository()'.
Note: Obsolete metadata may not always be easily detected (by inspecting
top-level metadata during loading) due to partial metadata and top-level
metadata that have not been written yet.
"""
# Walk the repository's metadata sub-directory, which is where all metadata
# is stored (including delegated roles). The 'django.json' role (e.g.,
# delegated by Targets) would be located in the
# '{repository_directory}/metadata/' directory.
metadata_files = sorted(storage_backend.list_folder(metadata_directory))
for metadata_role in metadata_files:
if metadata_role.endswith('root.json'):
continue
metadata_path = os.path.join(metadata_directory, metadata_role)
# Strip the version number if 'consistent_snapshot' is True. Example:
# '10.django.json' --> 'django.json'. Consistent and non-consistent
# metadata might co-exist if write() and
# write(consistent_snapshot=True) are mixed, so ensure only
# '<version_number>.filename' metadata is stripped.
# Should we check if 'consistent_snapshot' is True? It might have been
# set previously, but 'consistent_snapshot' can potentially be False
# now. We'll proceed with the understanding that 'metadata_name' can
# have a prepended version number even though the repository is now
# a non-consistent one.
if metadata_role not in snapshot_metadata['meta']:
metadata_role, junk = _strip_version_number(metadata_role,
consistent_snapshot)
else:
logger.debug(repr(metadata_role) + ' found in the snapshot role.')
# Strip metadata extension from filename. The role database does not
# include the metadata extension.
if metadata_role.endswith(METADATA_EXTENSION):
metadata_role = metadata_role[:-len(METADATA_EXTENSION)]
else:
logger.debug(repr(metadata_role) + ' does not match'
' supported extension ' + repr(METADATA_EXTENSION))
if metadata_role in roledb.TOP_LEVEL_ROLES:
logger.debug('Not removing top-level metadata ' + repr(metadata_role))
return
# Delete the metadata file if it does not exist in 'roledb'.
# 'repository_tool.py' might have removed 'metadata_name,'
# but its metadata file is not actually deleted yet. Do it now.
if not roledb.role_exists(metadata_role, repository_name):
logger.info('Removing outdated metadata: ' + repr(metadata_path))
storage_backend.remove(metadata_path)
else:
logger.debug('Not removing metadata: ' + repr(metadata_path))
# TODO: Should we delete outdated consistent snapshots, or does it make
# more sense for integrators to remove outdated consistent snapshots?
def _get_written_metadata(metadata_signable):
"""
Non-public function that returns the actual content of written metadata.
"""
# Explicitly specify the JSON separators for Python 2 + 3 consistency.
written_metadata_content = json.dumps(metadata_signable, indent=1,
separators=(',', ': '), sort_keys=True).encode('utf-8')
return written_metadata_content
def _strip_version_number(metadata_filename, consistent_snapshot):
"""
Strip from 'metadata_filename' any version number (in the
expected '{dirname}/<version_number>.rolename.<ext>' format) that
it may contain, and return the stripped filename and version number,
as a tuple. 'consistent_snapshot' is a boolean indicating if a version
number is prepended to 'metadata_filename'.
"""
# Strip the version number if 'consistent_snapshot' is True.
# Example: '10.django.json' --> 'django.json'
if consistent_snapshot:
dirname, basename = os.path.split(metadata_filename)
version_number, basename = basename.split('.', 1)
stripped_metadata_filename = os.path.join(dirname, basename)
if not version_number.isdigit():
return metadata_filename, ''
else:
return stripped_metadata_filename, version_number
else:
return metadata_filename, ''
def _load_top_level_metadata(repository, top_level_filenames, repository_name):
"""
Load the metadata of the Root, Timestamp, Targets, and Snapshot roles. At a
minimum, the Root role must exist and load successfully.
"""
root_filename = top_level_filenames[ROOT_FILENAME]
targets_filename = top_level_filenames[TARGETS_FILENAME]
snapshot_filename = top_level_filenames[SNAPSHOT_FILENAME]
timestamp_filename = top_level_filenames[TIMESTAMP_FILENAME]
root_metadata = None
targets_metadata = None
snapshot_metadata = None
timestamp_metadata = None
# Load 'root.json'. A Root role file without a version number is always
# written.
try:
# Initialize the key and role metadata of the top-level roles.
signable = sslib_util.load_json_file(root_filename)
try:
formats.check_signable_object_format(signable)
except exceptions.UnsignedMetadataError:
# Downgrade the error to a warning because a use case exists where
# metadata may be generated unsigned on one machine and signed on another.
logger.warning('Unsigned metadata object: ' + repr(signable))
root_metadata = signable['signed']
keydb.create_keydb_from_root_metadata(root_metadata, repository_name)
roledb.create_roledb_from_root_metadata(root_metadata, repository_name)
# Load Root's roleinfo and update 'roledb'.
roleinfo = roledb.get_roleinfo('root', repository_name)
roleinfo['consistent_snapshot'] = root_metadata['consistent_snapshot']
roleinfo['signatures'] = []
for signature in signable['signatures']:
if signature not in roleinfo['signatures']:
roleinfo['signatures'].append(signature)
else:
logger.debug('Found a Root signature that is already loaded:'
' ' + repr(signature))
# By default, roleinfo['partial_loaded'] of top-level roles should be set
# to False in 'create_roledb_from_root_metadata()'. Update this field, if
# necessary, now that we have its signable object.
if _metadata_is_partially_loaded('root', signable, repository_name):
roleinfo['partial_loaded'] = True
else:
logger.debug('Root was not partially loaded.')
_log_warning_if_expires_soon(ROOT_FILENAME, roleinfo['expires'],
ROOT_EXPIRES_WARN_SECONDS)
roledb.update_roleinfo('root', roleinfo, mark_role_as_dirty=False,
repository_name=repository_name)
# Ensure the 'consistent_snapshot' field is extracted.
consistent_snapshot = root_metadata['consistent_snapshot']
except sslib_exceptions.StorageError as error:
raise exceptions.RepositoryError('Cannot load the required'
' root file: ' + repr(root_filename)) from error
# Load 'timestamp.json'. A Timestamp role file without a version number is
# always written.
try:
signable = sslib_util.load_json_file(timestamp_filename)
timestamp_metadata = signable['signed']
for signature in signable['signatures']:
repository.timestamp.add_signature(signature, mark_role_as_dirty=False)
# Load Timestamp's roleinfo and update 'roledb'.
roleinfo = roledb.get_roleinfo('timestamp', repository_name)
roleinfo['expires'] = timestamp_metadata['expires']
roleinfo['version'] = timestamp_metadata['version']
if _metadata_is_partially_loaded('timestamp', signable, repository_name):
roleinfo['partial_loaded'] = True
else:
logger.debug('The Timestamp role was not partially loaded.')
_log_warning_if_expires_soon(TIMESTAMP_FILENAME, roleinfo['expires'],
TIMESTAMP_EXPIRES_WARN_SECONDS)
roledb.update_roleinfo('timestamp', roleinfo, mark_role_as_dirty=False,
repository_name=repository_name)
except sslib_exceptions.StorageError as error:
raise exceptions.RepositoryError('Cannot load the Timestamp '
'file: ' + repr(timestamp_filename)) from error
# Load 'snapshot.json'. A consistent snapshot.json must be calculated if
# 'consistent_snapshot' is True.
# The Snapshot and Root roles are both accessed by their hashes.
if consistent_snapshot:
snapshot_version = timestamp_metadata['meta'][SNAPSHOT_FILENAME]['version']
dirname, basename = os.path.split(snapshot_filename)
basename = basename.split(METADATA_EXTENSION, 1)[0]
snapshot_filename = os.path.join(dirname,
str(snapshot_version) + '.' + basename + METADATA_EXTENSION)
try:
signable = sslib_util.load_json_file(snapshot_filename)
try:
formats.check_signable_object_format(signable)
except exceptions.UnsignedMetadataError:
# Downgrade the error to a warning because a use case exists where
# metadata may be generated unsigned on one machine and signed on another.
logger.warning('Unsigned metadata object: ' + repr(signable))
snapshot_metadata = signable['signed']
for signature in signable['signatures']:
repository.snapshot.add_signature(signature, mark_role_as_dirty=False)
# Load Snapshot's roleinfo and update 'roledb'.
roleinfo = roledb.get_roleinfo('snapshot', repository_name)
roleinfo['expires'] = snapshot_metadata['expires']
roleinfo['version'] = snapshot_metadata['version']
if _metadata_is_partially_loaded('snapshot', signable, repository_name):
roleinfo['partial_loaded'] = True
else:
logger.debug('Snapshot was not partially loaded.')
_log_warning_if_expires_soon(SNAPSHOT_FILENAME, roleinfo['expires'],
SNAPSHOT_EXPIRES_WARN_SECONDS)
roledb.update_roleinfo('snapshot', roleinfo, mark_role_as_dirty=False,
repository_name=repository_name)
except sslib_exceptions.StorageError as error:
raise exceptions.RepositoryError('The Snapshot file '
'cannot be loaded: '+ repr(snapshot_filename)) from error
# Load 'targets.json'. A consistent snapshot of the Targets role must be
# calculated if 'consistent_snapshot' is True.
if consistent_snapshot:
targets_version = snapshot_metadata['meta'][TARGETS_FILENAME]['version']
dirname, basename = os.path.split(targets_filename)
targets_filename = os.path.join(dirname, str(targets_version) + '.' + basename)
try:
signable = sslib_util.load_json_file(targets_filename)
try:
formats.check_signable_object_format(signable)
except exceptions.UnsignedMetadataError:
# Downgrade the error to a warning because a use case exists where
# metadata may be generated unsigned on one machine and signed on another.
logger.warning('Unsigned metadata object: ' + repr(signable))
targets_metadata = signable['signed']
for signature in signable['signatures']:
repository.targets.add_signature(signature, mark_role_as_dirty=False)
# Update 'targets.json' in 'roledb'
roleinfo = roledb.get_roleinfo('targets', repository_name)
roleinfo['paths'] = targets_metadata['targets']
roleinfo['version'] = targets_metadata['version']
roleinfo['expires'] = targets_metadata['expires']
roleinfo['delegations'] = targets_metadata['delegations']
if _metadata_is_partially_loaded('targets', signable, repository_name):
roleinfo['partial_loaded'] = True
else:
logger.debug('Targets file was not partially loaded.')
_log_warning_if_expires_soon(TARGETS_FILENAME, roleinfo['expires'],
TARGETS_EXPIRES_WARN_SECONDS)
roledb.update_roleinfo('targets', roleinfo, mark_role_as_dirty=False,
repository_name=repository_name)
# Add the keys specified in the delegations field of the Targets role.
for keyid, key_metadata in targets_metadata['delegations']['keys'].items():
# Use the keyid found in the delegation
key_object, _ = sslib_keys.format_metadata_to_key(key_metadata,
keyid)
# Add 'key_object' to the list of recognized keys. Keys may be shared,
# so do not raise an exception if 'key_object' has already been loaded.
# In contrast to the methods that may add duplicate keys, do not log
# a warning as there may be many such duplicate key warnings. The
# repository maintainer should have also been made aware of the duplicate
# key when it was added.
try:
keydb.add_key(key_object, keyid=None, repository_name=repository_name)
except exceptions.KeyAlreadyExistsError:
pass
except sslib_exceptions.StorageError as error:
raise exceptions.RepositoryError('The Targets file '
'can not be loaded: ' + repr(targets_filename)) from error
return repository, consistent_snapshot
def _log_warning_if_expires_soon(rolename, expires_iso8601_timestamp,
seconds_remaining_to_warn):
"""
Non-public function that logs a warning if 'rolename' expires in
'seconds_remaining_to_warn' seconds, or less.
"""
# Metadata stores expiration datetimes in ISO8601 format. Convert to
# unix timestamp, subtract from current time.time() (also in POSIX time)
# and compare against 'seconds_remaining_to_warn'. Log a warning message
# to console if 'rolename' expires soon.
datetime_object = formats.expiry_string_to_datetime(
expires_iso8601_timestamp)
expires_unix_timestamp = \
formats.datetime_to_unix_timestamp(datetime_object)
seconds_until_expires = expires_unix_timestamp - int(time.time())
if seconds_until_expires <= seconds_remaining_to_warn:
if seconds_until_expires <= 0:
logger.warning(
repr(rolename) + ' expired ' + repr(datetime_object.ctime() + ' (UTC).'))
else:
days_until_expires = seconds_until_expires / 86400
logger.warning(repr(rolename) + ' expires ' + datetime_object.ctime() + ''
' (UTC). ' + repr(days_until_expires) + ' day(s) until it expires.')
else:
pass
def import_rsa_privatekey_from_file(filepath, password=None):
"""
<Purpose>
Import the encrypted PEM file in 'filepath', decrypt it, and return the key
object in 'securesystemslib.RSAKEY_SCHEMA' format.
<Arguments>
filepath:
<filepath> file, an RSA encrypted PEM file. Unlike the public RSA PEM
key file, 'filepath' does not have an extension.
password:
The passphrase to decrypt 'filepath'.
<Exceptions>
securesystemslib.exceptions.FormatError, if the arguments are improperly
formatted.
securesystemslib.exceptions.CryptoError, if 'filepath' is not a valid
encrypted key file.
<Side Effects>
The contents of 'filepath' is read, decrypted, and the key stored.
<Returns>
An RSA key object, conformant to 'securesystemslib.RSAKEY_SCHEMA'.
"""
# Note: securesystemslib.interface.import_rsa_privatekey_from_file() does not
# allow both 'password' and 'prompt' to be True, nor does it automatically
# prompt for a password if the key file is encrypted and a password isn't
# given.
try:
private_key = sslib_interface.import_rsa_privatekey_from_file(
filepath, password)
# The user might not have given a password for an encrypted private key.
# Prompt for a password for convenience.
except sslib_exceptions.CryptoError:
if password is None:
private_key = sslib_interface.import_rsa_privatekey_from_file(
filepath, password, prompt=True)
else:
raise
return private_key
def import_ed25519_privatekey_from_file(filepath, password=None):
"""
<Purpose>
Import the encrypted ed25519 TUF key file in 'filepath', decrypt it, and
return the key object in 'securesystemslib.ED25519KEY_SCHEMA' format.
The TUF private key (may also contain the public part) is encrypted with
AES 256 and CTR the mode of operation. The password is strengthened with
PBKDF2-HMAC-SHA256.
<Arguments>
filepath:
<filepath> file, an RSA encrypted TUF key file.
password:
The password, or passphrase, to import the private key (i.e., the
encrypted key file 'filepath' must be decrypted before the ed25519 key
object can be returned.
<Exceptions>
securesystemslib.exceptions.FormatError, if the arguments are improperly
formatted or the imported key object contains an invalid key type (i.e.,
not 'ed25519').
securesystemslib.exceptions.CryptoError, if 'filepath' cannot be decrypted.
securesystemslib.exceptions.UnsupportedLibraryError, if 'filepath' cannot be
decrypted due to an invalid configuration setting (i.e., invalid
'tuf.settings' setting).
<Side Effects>
'password' is used to decrypt the 'filepath' key file.
<Returns>
An ed25519 key object of the form: 'securesystemslib.ED25519KEY_SCHEMA'.
"""
# Note: securesystemslib.interface.import_ed25519_privatekey_from_file() does
# not allow both 'password' and 'prompt' to be True, nor does it
# automatically prompt for a password if the key file is encrypted and a
# password isn't given.
try:
private_key = sslib_interface.import_ed25519_privatekey_from_file(
filepath, password)
# The user might not have given a password for an encrypted private key.
# Prompt for a password for convenience.
except sslib_exceptions.CryptoError:
if password is None:
private_key = sslib_interface.import_ed25519_privatekey_from_file(
filepath, password, prompt=True)
else:
raise
return private_key
def get_delegated_roles_metadata_filenames(metadata_directory,
consistent_snapshot, storage_backend=None):
"""
Return a dictionary containing all filenames in 'metadata_directory'
except the top-level roles.
If multiple versions of a file exist because of a consistent snapshot,
only the file with biggest version prefix is included.
"""
filenames = {}
metadata_files = sorted(storage_backend.list_folder(metadata_directory),
reverse=True)
# Iterate over role metadata files, sorted by their version-number prefix, with
# more recent versions first, and only add the most recent version of any
# (non top-level) metadata to the list of returned filenames. Note that there
# should only be one version of each file, if consistent_snapshot is False.
for metadata_role in metadata_files:
metadata_path = os.path.join(metadata_directory, metadata_role)
# Strip the version number if 'consistent_snapshot' is True,
# or if 'metadata_role' is Root.
# Example: '10.django.json' --> 'django.json'
consistent = \
metadata_role.endswith('root.json') or consistent_snapshot == True
metadata_name, junk = _strip_version_number(metadata_role,
consistent)
if metadata_name.endswith(METADATA_EXTENSION):
extension_length = len(METADATA_EXTENSION)
metadata_name = metadata_name[:-extension_length]
else:
logger.debug('Skipping file with unsupported metadata'
' extension: ' + repr(metadata_path))
continue
# Skip top-level roles, only interested in delegated roles.
if metadata_name in roledb.TOP_LEVEL_ROLES:
continue
# Prevent reloading duplicate versions if consistent_snapshot is True
if metadata_name not in filenames:
filenames[metadata_name] = metadata_path
return filenames
def get_top_level_metadata_filenames(metadata_directory):
"""
<Purpose>
Return a dictionary containing the filenames of the top-level roles.
If 'metadata_directory' is set to 'metadata', the dictionary
returned would contain:
filenames = {'root.json': 'metadata/root.json',
'targets.json': 'metadata/targets.json',
'snapshot.json': 'metadata/snapshot.json',
'timestamp.json': 'metadata/timestamp.json'}
If 'metadata_directory' is not set by the caller, the current directory is
used.
<Arguments>
metadata_directory:
The directory containing the metadata files.
<Exceptions>
securesystemslib.exceptions.FormatError, if 'metadata_directory' is
improperly formatted.
<Side Effects>
None.
<Returns>
A dictionary containing the expected filenames of the top-level
metadata files, such as 'root.json' and 'snapshot.json'.
"""
# Does 'metadata_directory' have the correct format?
# Ensure the arguments have the appropriate number of objects and object
# types, and that all dict keys are properly named.
# Raise 'securesystemslib.exceptions.FormatError' if there is a mismatch.
sslib_formats.PATH_SCHEMA.check_match(metadata_directory)
# Store the filepaths of the top-level roles, including the
# 'metadata_directory' for each one.
filenames = {}
filenames[ROOT_FILENAME] = \
os.path.join(metadata_directory, ROOT_FILENAME)
filenames[TARGETS_FILENAME] = \
os.path.join(metadata_directory, TARGETS_FILENAME)
filenames[SNAPSHOT_FILENAME] = \
os.path.join(metadata_directory, SNAPSHOT_FILENAME)
filenames[TIMESTAMP_FILENAME] = \
os.path.join(metadata_directory, TIMESTAMP_FILENAME)
return filenames
def get_targets_metadata_fileinfo(filename, storage_backend, custom=None):
"""
<Purpose>
Retrieve the file information of 'filename'. The object returned
conforms to 'tuf.formats.TARGETS_FILEINFO_SCHEMA'. The information
generated for 'filename' is stored in metadata files like 'targets.json'.
The fileinfo object returned has the form:
fileinfo = {'length': 1024,
'hashes': {'sha256': 1233dfba312, ...},
'custom': {...}}
<Arguments>
filename:
The metadata file whose file information is needed. It must exist.
custom:
An optional object providing additional information about the file.
storage_backend:
An object which implements
securesystemslib.storage.StorageBackendInterface.
<Exceptions>
securesystemslib.exceptions.FormatError, if 'filename' is improperly
formatted.
<Side Effects>
The file is opened and information about the file is generated,
such as file size and its hash.
<Returns>
A dictionary conformant to 'tuf.formats.TARGETS_FILEINFO_SCHEMA'. This
dictionary contains the length, hashes, and custom data about the
'filename' metadata file. SHA256 hashes are generated by default.
"""
# Does 'filename' and 'custom' have the correct format?
# Ensure the arguments have the appropriate number of objects and object
# types, and that all dict keys are properly named.
# Raise 'securesystemslib.exceptions.FormatError' if there is a mismatch.
sslib_formats.PATH_SCHEMA.check_match(filename)
if custom is not None:
formats.CUSTOM_SCHEMA.check_match(custom)
# Note: 'filehashes' is a dictionary of the form
# {'sha256': 1233dfba312, ...}. 'custom' is an optional
# dictionary that a client might define to include additional
# file information, such as the file's author, version/revision
# numbers, etc.
filesize, filehashes = sslib_util.get_file_details(filename,
settings.FILE_HASH_ALGORITHMS, storage_backend)
return formats.make_targets_fileinfo(filesize, filehashes, custom=custom)
def get_metadata_versioninfo(rolename, repository_name):
"""
<Purpose>
Retrieve the version information of 'rolename'. The object returned
conforms to 'tuf.formats.VERSIONINFO_SCHEMA'. The information