| 1 |
# Copyright New York University and the in-toto contributors |
| 2 |
# SPDX-License-Identifier: Apache-2.0 |
| 3 |
|
| 4 |
""" |
| 5 |
<Program Name> |
| 6 |
metadata.py |
| 7 |
|
| 8 |
<Author> |
| 9 |
Lukas Puehringer <[email protected]> |
| 10 |
Santiago Torres <[email protected]> |
| 11 |
|
| 12 |
<Started> |
| 13 |
Oct 23, 2017 |
| 14 |
|
| 15 |
<Copyright> |
| 16 |
See LICENSE for licensing information. |
| 17 |
|
| 18 |
<Purpose> |
| 19 |
Provides a container class `Metablock` for signed metadata and |
| 20 |
functions for signing, signature verification, de-serialization and |
| 21 |
serialization from and to JSON. |
| 22 |
|
| 23 |
""" |
| 24 |
|
| 25 |
import json |
| 26 |
from typing import Union |
| 27 |
|
| 28 |
import attr |
| 29 |
import securesystemslib.exceptions |
| 30 |
import securesystemslib.formats |
| 31 |
import securesystemslib.gpg.functions |
| 32 |
import securesystemslib.keys |
| 33 |
from securesystemslib.dsse import Envelope as SSlibEnvelope |
| 34 |
from securesystemslib.exceptions import VerificationError |
| 35 |
from securesystemslib.signer import Signature, Signer, SSlibKey |
| 36 |
|
| 37 |
from in_toto.exceptions import InvalidMetadata, SignatureVerificationError |
| 38 |
from in_toto.models._signer import GPGSigner |
| 39 |
from in_toto.models.common import Signable, ValidationMixin |
| 40 |
from in_toto.models.layout import Layout |
| 41 |
from in_toto.models.link import Link |
| 42 |
|
| 43 |
ENVELOPE_PAYLOAD_TYPE = "application/vnd.in-toto+json" |
| 44 |
|
| 45 |
|
| 46 |
class Metadata: |
| 47 |
"""A Metadata abstraction between DSSE Envelope and Metablock.""" |
| 48 |
|
| 49 |
@classmethod |
| 50 |
def from_dict(cls, data): |
| 51 |
"""Loads DSSE or Traditional Metadata from its JSON/dict representation.""" |
| 52 |
|
| 53 |
if "payload" in data: |
| 54 |
if data.get("payloadType") == ENVELOPE_PAYLOAD_TYPE: |
| 55 |
return Envelope.from_dict(data) |
| 56 |
|
| 57 |
elif "signed" in data: |
| 58 |
return Metablock.from_dict(data) |
| 59 |
|
| 60 |
raise InvalidMetadata |
| 61 |
|
| 62 |
def to_dict(self): |
| 63 |
"""Returns the JSON-serializable dictionary representation of self.""" |
| 64 |
raise NotImplementedError # pragma: no cover |
| 65 |
|
| 66 |
@classmethod |
| 67 |
def load(cls, path): |
| 68 |
"""Loads the JSON string representation of metadata from disk. |
| 69 |
|
| 70 |
Arguments: |
| 71 |
path: The path to read the file from. |
| 72 |
|
| 73 |
Raises: |
| 74 |
IOError: The file cannot be read. |
| 75 |
InvalidMetadata: Metadata format is invalid. |
| 76 |
securesystemslib.exceptions.FormatError: Metadata format is invalid. |
| 77 |
|
| 78 |
Returns: |
| 79 |
A Metadata containing a Link or Layout object. |
| 80 |
|
| 81 |
""" |
| 82 |
with open(path, "r", encoding="utf8") as fp: |
| 83 |
data = json.load(fp) |
| 84 |
|
| 85 |
return cls.from_dict(data) |
| 86 |
|
| 87 |
def dump(self, path): |
| 88 |
"""Writes the JSON string representation of the instance to disk. |
| 89 |
|
| 90 |
Arguments: |
| 91 |
path: The path to write the file to. |
| 92 |
|
| 93 |
Raises: |
| 94 |
IOError: File cannot be written. |
| 95 |
|
| 96 |
""" |
| 97 |
json_bytes = json.dumps( |
| 98 |
self.to_dict(), |
| 99 |
sort_keys=True, |
| 100 |
).encode("utf-8") |
| 101 |
|
| 102 |
with open(path, "wb") as fp: |
| 103 |
fp.write(json_bytes) |
| 104 |
|
| 105 |
def create_signature(self, signer: Signer) -> Signature: |
| 106 |
"""Creates signature over signable with Signer and adds it to signatures. |
| 107 |
|
| 108 |
Arguments: |
| 109 |
signer: A "Signer" class instance to create signature. |
| 110 |
|
| 111 |
Raises: |
| 112 |
securesystemslib.exceptions.CryptoError, \ |
| 113 |
securesystemslib.exceptions.UnsupportedAlgorithmError: |
| 114 |
Signing errors. |
| 115 |
|
| 116 |
Returns: |
| 117 |
The signature. A securesystemslib.signer.Signature type. |
| 118 |
""" |
| 119 |
raise NotImplementedError # pragma: no cover |
| 120 |
|
| 121 |
def verify_signature(self, verification_key): |
| 122 |
"""Verifies a signature over signable in signatures with verification_key. |
| 123 |
|
| 124 |
Arguments: |
| 125 |
verification_key: A verification key. The format is |
| 126 |
securesystemslib.formats.ANY_VERIFICATION_KEY_SCHEMA. |
| 127 |
|
| 128 |
Raises: |
| 129 |
securesystemslib.exceptions.FormatError: The passed key is malformed. |
| 130 |
|
| 131 |
SignatureVerificationError: No signature keyid matches |
| 132 |
the verification key keyid, or the matching signature is malformed, |
| 133 |
or the matching signature is invalid. |
| 134 |
""" |
| 135 |
raise NotImplementedError # pragma: no cover |
| 136 |
|
| 137 |
def get_payload(self): |
| 138 |
"""Returns ``Link`` or ``Layout``.""" |
| 139 |
raise NotImplementedError # pragma: no cover |
| 140 |
|
| 141 |
|
| 142 |
class Envelope(SSlibEnvelope, Metadata): |
| 143 |
"""DSSE Envelope for in-toto payloads.""" |
| 144 |
|
| 145 |
@classmethod |
| 146 |
def from_signable(cls, signable: Signable) -> "Envelope": |
| 147 |
"""Creates DSSE envelope with signable bytes as payload.""" |
| 148 |
|
| 149 |
json_bytes = json.dumps( |
| 150 |
attr.asdict(signable), |
| 151 |
sort_keys=True, |
| 152 |
).encode("utf-8") |
| 153 |
|
| 154 |
return cls( |
| 155 |
payload=json_bytes, |
| 156 |
payload_type=ENVELOPE_PAYLOAD_TYPE, |
| 157 |
signatures=[], |
| 158 |
) |
| 159 |
|
| 160 |
def create_signature(self, signer: Signer) -> Signature: |
| 161 |
if isinstance(signer, GPGSigner): |
| 162 |
raise NotImplementedError("GPG Signing is not implemented") |
| 163 |
|
| 164 |
return super().sign(signer) |
| 165 |
|
| 166 |
def verify_signature(self, verification_key): |
| 167 |
key = SSlibKey.from_securesystemslib_key(verification_key) |
| 168 |
try: |
| 169 |
super().verify(keys=[key], threshold=1) |
| 170 |
except VerificationError as exc: |
| 171 |
raise SignatureVerificationError from exc |
| 172 |
|
| 173 |
def get_payload(self) -> Union[Link, Layout]: |
| 174 |
"""Parse DSSE payload into Link or Layout object. |
| 175 |
|
| 176 |
Raises: |
| 177 |
InvalidMetadata: If type in payload is not ``link`` or ``layout``. |
| 178 |
|
| 179 |
Returns: |
| 180 |
Link or Layout. |
| 181 |
""" |
| 182 |
|
| 183 |
data = json.loads(self.payload.decode("utf-8")) |
| 184 |
_type = data.get("_type") |
| 185 |
if _type == "link": |
| 186 |
return Link.read(data) |
| 187 |
if _type == "layout": |
| 188 |
return Layout.read(data) |
| 189 |
|
| 190 |
raise InvalidMetadata |
| 191 |
|
| 192 |
|
| 193 |
@attr.s(repr=False, init=False) |
| 194 |
class Metablock(Metadata, ValidationMixin): |
| 195 |
"""A container for signed in-toto metadata. |
| 196 |
|
| 197 |
Provides methods for metadata JSON (de-)serialization, reading from and |
| 198 |
writing to disk, creating and verifying signatures, and self-validation. |
| 199 |
|
| 200 |
Attributes: |
| 201 |
signed: A subclass of Signable which has the actual metadata payload, |
| 202 |
usually a Link or Layout object. |
| 203 |
signatures: A list of signatures over the canonical JSON representation |
| 204 |
of the value of the signed attribute. |
| 205 |
compact_json: A boolean indicating if the dump method should write a |
| 206 |
compact JSON string representation of the metadata. |
| 207 |
|
| 208 |
""" |
| 209 |
|
| 210 |
signatures = attr.ib() |
| 211 |
signed = attr.ib() |
| 212 |
|
| 213 |
def __init__(self, **kwargs): |
| 214 |
self.signatures = kwargs.get("signatures", []) |
| 215 |
self.signed = kwargs.get("signed") |
| 216 |
self.compact_json = kwargs.get("compact_json", False) |
| 217 |
|
| 218 |
self.validate() |
| 219 |
|
| 220 |
def __repr__(self): |
| 221 |
"""Returns the JSON string representation.""" |
| 222 |
indent = None if self.compact_json else 1 |
| 223 |
separators = (",", ":") if self.compact_json else (",", ": ") |
| 224 |
|
| 225 |
return json.dumps( |
| 226 |
{"signatures": self.signatures, "signed": attr.asdict(self.signed)}, |
| 227 |
indent=indent, |
| 228 |
separators=separators, |
| 229 |
sort_keys=True, |
| 230 |
) |
| 231 |
|
| 232 |
def dump(self, path): |
| 233 |
"""Writes the JSON string representation of the instance to disk. |
| 234 |
|
| 235 |
Arguments: |
| 236 |
path: The path to write the file to. |
| 237 |
|
| 238 |
Raises: |
| 239 |
IOError: File cannot be written. |
| 240 |
|
| 241 |
""" |
| 242 |
with open(path, "wb") as fp: |
| 243 |
fp.write("{}".format(self).encode("utf-8")) |
| 244 |
|
| 245 |
@classmethod |
| 246 |
def from_dict(cls, data): |
| 247 |
"""Creates a Metablock object from its JSON/dict representation.""" |
| 248 |
|
| 249 |
signatures = data.get("signatures", []) |
| 250 |
signed_data = data.get("signed", {}) |
| 251 |
signed_type = signed_data.get("_type") |
| 252 |
|
| 253 |
if signed_type == "link": |
| 254 |
signed = Link.read(signed_data) |
| 255 |
|
| 256 |
elif signed_type == "layout": |
| 257 |
signed = Layout.read(signed_data) |
| 258 |
|
| 259 |
else: |
| 260 |
raise securesystemslib.exceptions.FormatError( |
| 261 |
"Invalid Metadata format" |
| 262 |
) |
| 263 |
|
| 264 |
return cls(signatures=signatures, signed=signed) |
| 265 |
|
| 266 |
def to_dict(self): |
| 267 |
"""Returns the JSON-serializable dictionary representation of self.""" |
| 268 |
|
| 269 |
return { |
| 270 |
"signatures": self.signatures, |
| 271 |
"signed": attr.asdict(self.signed), |
| 272 |
} |
| 273 |
|
| 274 |
@property |
| 275 |
def type_(self): |
| 276 |
"""A shortcut to the `type_` attribute of the object on the signable |
| 277 |
attribute (should be one of "link" or "layout").""" |
| 278 |
# NOTE: Trailing underscore is used by convention (pep8) to avoid conflict |
| 279 |
# with Python's type keyword. |
| 280 |
return self.signed.type_ |
| 281 |
|
| 282 |
def create_signature(self, signer: Signer): |
| 283 |
signature = signer.sign(self.signed.signable_bytes) |
| 284 |
self.signatures.append(signature.to_dict()) |
| 285 |
|
| 286 |
return signature |
| 287 |
|
| 288 |
def sign(self, key): |
| 289 |
"""Creates signature over signable with key and adds it to signatures. |
| 290 |
|
| 291 |
Uses the UTF-8 encoded canonical JSON byte representation of the signable |
| 292 |
attribute to create signatures deterministically. |
| 293 |
|
| 294 |
Attributes: |
| 295 |
key: A signing key. The format is securesystemslib.formats.KEY_SCHEMA. |
| 296 |
|
| 297 |
Raises: |
| 298 |
securesystemslib.exceptions.FormatError: Key argument is malformed. |
| 299 |
securesystemslib.exceptions.CryptoError, \ |
| 300 |
securesystemslib.exceptions.UnsupportedAlgorithmError: |
| 301 |
Signing errors. |
| 302 |
|
| 303 |
Returns: |
| 304 |
The signature. Format is securesystemslib.formats.SIGNATURE_SCHEMA. |
| 305 |
|
| 306 |
""" |
| 307 |
securesystemslib.formats.KEY_SCHEMA.check_match(key) |
| 308 |
|
| 309 |
signature = securesystemslib.keys.create_signature( |
| 310 |
key, self.signed.signable_bytes |
| 311 |
) |
| 312 |
|
| 313 |
self.signatures.append(signature) |
| 314 |
|
| 315 |
return signature |
| 316 |
|
| 317 |
def sign_gpg(self, gpg_keyid=None, gpg_home=None): |
| 318 |
"""Creates signature over signable with gpg and adds it to signatures. |
| 319 |
|
| 320 |
Uses the UTF-8 encoded canonical JSON byte representation of the signable |
| 321 |
attribute to create signatures deterministically. |
| 322 |
|
| 323 |
Arguments: |
| 324 |
gpg_keyid (optional): A keyid used to identify a local gpg signing key. |
| 325 |
If omitted the default signing key is used. |
| 326 |
|
| 327 |
gpg_home (optional): A path to the gpg home directory. If not set the |
| 328 |
default gpg home directory is used. |
| 329 |
|
| 330 |
Raises: |
| 331 |
ValueError, OSError, securesystemslib.gpg.exceptions.CommandError, \ |
| 332 |
securesystemslib.gpg.exceptions.KeyNotFoundError: |
| 333 |
gpg signing errors. |
| 334 |
|
| 335 |
Side Effects: |
| 336 |
Calls system gpg command in a subprocess. |
| 337 |
|
| 338 |
Returns: |
| 339 |
The signature. Format is securesystemslib.formats.GPG_SIGNATURE_SCHEMA. |
| 340 |
|
| 341 |
""" |
| 342 |
signature = securesystemslib.gpg.functions.create_signature( |
| 343 |
self.signed.signable_bytes, gpg_keyid, gpg_home |
| 344 |
) |
| 345 |
|
| 346 |
self.signatures.append(signature) |
| 347 |
|
| 348 |
return signature |
| 349 |
|
| 350 |
def verify_signature(self, verification_key): |
| 351 |
"""Verifies a signature over signable in signatures with verification_key. |
| 352 |
|
| 353 |
Uses the UTF-8 encoded canonical JSON byte representation of the signable |
| 354 |
attribute to verify the signature deterministically. |
| 355 |
|
| 356 |
NOTE: Only the first signature in the signatures attribute, whose keyid |
| 357 |
matches the verification_key keyid, is verified. If the verification_key |
| 358 |
format is securesystemslib.formats.GPG_PUBKEY_SCHEMA, subkey keyids are |
| 359 |
considered too. |
| 360 |
|
| 361 |
Arguments: |
| 362 |
verification_key: A verification key. The format is |
| 363 |
securesystemslib.formats.ANY_VERIFICATION_KEY_SCHEMA. |
| 364 |
|
| 365 |
Raises: |
| 366 |
securesystemslib.exceptions.FormatError: The passed key is malformed. |
| 367 |
|
| 368 |
SignatureVerificationError: No signature keyid matches the verification |
| 369 |
key keyid, or the matching signature is malformed, or the matching |
| 370 |
signature is invalid. |
| 371 |
|
| 372 |
securesystemslib.gpg.exceptions.KeyExpirationError: Passed verification |
| 373 |
key is an expired gpg key. |
| 374 |
|
| 375 |
""" |
| 376 |
securesystemslib.formats.ANY_VERIFICATION_KEY_SCHEMA.check_match( |
| 377 |
verification_key |
| 378 |
) |
| 379 |
verification_keyid = verification_key["keyid"] |
| 380 |
|
| 381 |
# Find a signature that corresponds to the keyid of the passed |
| 382 |
# verification key or one of its subkeys |
| 383 |
signature = None |
| 384 |
for signature in self.signatures: |
| 385 |
if signature["keyid"] == verification_keyid: |
| 386 |
break |
| 387 |
|
| 388 |
if signature["keyid"] in list( |
| 389 |
verification_key.get("subkeys", {}).keys() |
| 390 |
): |
| 391 |
break |
| 392 |
|
| 393 |
else: |
| 394 |
raise SignatureVerificationError( |
| 395 |
"No signature found for key '{}'".format(verification_keyid) |
| 396 |
) |
| 397 |
|
| 398 |
if securesystemslib.formats.GPG_SIGNATURE_SCHEMA.matches(signature): |
| 399 |
valid = securesystemslib.gpg.functions.verify_signature( |
| 400 |
signature, verification_key, self.signed.signable_bytes |
| 401 |
) |
| 402 |
|
| 403 |
elif securesystemslib.formats.SIGNATURE_SCHEMA.matches(signature): |
| 404 |
valid = securesystemslib.keys.verify_signature( |
| 405 |
verification_key, signature, self.signed.signable_bytes |
| 406 |
) |
| 407 |
|
| 408 |
else: |
| 409 |
valid = False |
| 410 |
|
| 411 |
if not valid: |
| 412 |
raise SignatureVerificationError( |
| 413 |
"Invalid signature for keyid '{}'".format(verification_keyid) |
| 414 |
) |
| 415 |
|
| 416 |
def _validate_signed(self): |
| 417 |
"""Private method to check if the 'signed' attribute contains a valid |
| 418 |
Layout or Link object.""" |
| 419 |
|
| 420 |
if not ( |
| 421 |
isinstance(self.signed, Layout) or isinstance(self.signed, Link) |
| 422 |
): |
| 423 |
raise securesystemslib.exceptions.FormatError( |
| 424 |
"The Metblock's 'signed'" |
| 425 |
" property has has to be of type 'Link' or 'Layout'." |
| 426 |
) |
| 427 |
|
| 428 |
# If the signed object is a Link or Layout object validate it. |
| 429 |
self.signed.validate() |
| 430 |
|
| 431 |
def _validate_signatures(self): |
| 432 |
"""Private method to check that the 'signatures' attribute is a list of |
| 433 |
signatures in the format 'securesystemslib.formats.ANY_SIGNATURE_SCHEMA'. |
| 434 |
""" |
| 435 |
|
| 436 |
if not isinstance(self.signatures, list): |
| 437 |
raise securesystemslib.exceptions.FormatError( |
| 438 |
"The Metablock's" |
| 439 |
" 'signatures' property has to be of type 'list'." |
| 440 |
) |
| 441 |
|
| 442 |
for signature in self.signatures: |
| 443 |
securesystemslib.formats.ANY_SIGNATURE_SCHEMA.check_match(signature) |
| 444 |
|
| 445 |
def get_payload(self): |
| 446 |
"""Returns signed of the Metablock.""" |
| 447 |
|
| 448 |
return self.signed |