hashes.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  1. import hashlib
  2. from typing import TYPE_CHECKING, BinaryIO, Dict, Iterable, List, NoReturn, Optional
  3. from pip._internal.exceptions import HashMismatch, HashMissing, InstallationError
  4. from pip._internal.utils.misc import read_chunks
  5. if TYPE_CHECKING:
  6. from hashlib import _Hash
  7. # The recommended hash algo of the moment. Change this whenever the state of
  8. # the art changes; it won't hurt backward compatibility.
  9. FAVORITE_HASH = "sha256"
  10. # Names of hashlib algorithms allowed by the --hash option and ``pip hash``
  11. # Currently, those are the ones at least as collision-resistant as sha256.
  12. STRONG_HASHES = ["sha256", "sha384", "sha512"]
  13. class Hashes:
  14. """A wrapper that builds multiple hashes at once and checks them against
  15. known-good values
  16. """
  17. def __init__(self, hashes: Optional[Dict[str, List[str]]] = None) -> None:
  18. """
  19. :param hashes: A dict of algorithm names pointing to lists of allowed
  20. hex digests
  21. """
  22. allowed = {}
  23. if hashes is not None:
  24. for alg, keys in hashes.items():
  25. # Make sure values are always sorted (to ease equality checks)
  26. allowed[alg] = [k.lower() for k in sorted(keys)]
  27. self._allowed = allowed
  28. def __and__(self, other: "Hashes") -> "Hashes":
  29. if not isinstance(other, Hashes):
  30. return NotImplemented
  31. # If either of the Hashes object is entirely empty (i.e. no hash
  32. # specified at all), all hashes from the other object are allowed.
  33. if not other:
  34. return self
  35. if not self:
  36. return other
  37. # Otherwise only hashes that present in both objects are allowed.
  38. new = {}
  39. for alg, values in other._allowed.items():
  40. if alg not in self._allowed:
  41. continue
  42. new[alg] = [v for v in values if v in self._allowed[alg]]
  43. return Hashes(new)
  44. @property
  45. def digest_count(self) -> int:
  46. return sum(len(digests) for digests in self._allowed.values())
  47. def is_hash_allowed(self, hash_name: str, hex_digest: str) -> bool:
  48. """Return whether the given hex digest is allowed."""
  49. return hex_digest in self._allowed.get(hash_name, [])
  50. def check_against_chunks(self, chunks: Iterable[bytes]) -> None:
  51. """Check good hashes against ones built from iterable of chunks of
  52. data.
  53. Raise HashMismatch if none match.
  54. """
  55. gots = {}
  56. for hash_name in self._allowed.keys():
  57. try:
  58. gots[hash_name] = hashlib.new(hash_name)
  59. except (ValueError, TypeError):
  60. raise InstallationError(f"Unknown hash name: {hash_name}")
  61. for chunk in chunks:
  62. for hash in gots.values():
  63. hash.update(chunk)
  64. for hash_name, got in gots.items():
  65. if got.hexdigest() in self._allowed[hash_name]:
  66. return
  67. self._raise(gots)
  68. def _raise(self, gots: Dict[str, "_Hash"]) -> "NoReturn":
  69. raise HashMismatch(self._allowed, gots)
  70. def check_against_file(self, file: BinaryIO) -> None:
  71. """Check good hashes against a file-like object
  72. Raise HashMismatch if none match.
  73. """
  74. return self.check_against_chunks(read_chunks(file))
  75. def check_against_path(self, path: str) -> None:
  76. with open(path, "rb") as file:
  77. return self.check_against_file(file)
  78. def has_one_of(self, hashes: Dict[str, str]) -> bool:
  79. """Return whether any of the given hashes are allowed."""
  80. for hash_name, hex_digest in hashes.items():
  81. if self.is_hash_allowed(hash_name, hex_digest):
  82. return True
  83. return False
  84. def __bool__(self) -> bool:
  85. """Return whether I know any known-good hashes."""
  86. return bool(self._allowed)
  87. def __eq__(self, other: object) -> bool:
  88. if not isinstance(other, Hashes):
  89. return NotImplemented
  90. return self._allowed == other._allowed
  91. def __hash__(self) -> int:
  92. return hash(
  93. ",".join(
  94. sorted(
  95. ":".join((alg, digest))
  96. for alg, digest_list in self._allowed.items()
  97. for digest in digest_list
  98. )
  99. )
  100. )
  101. class MissingHashes(Hashes):
  102. """A workalike for Hashes used when we're missing a hash for a requirement
  103. It computes the actual hash of the requirement and raises a HashMissing
  104. exception showing it to the user.
  105. """
  106. def __init__(self) -> None:
  107. """Don't offer the ``hashes`` kwarg."""
  108. # Pass our favorite hash in to generate a "gotten hash". With the
  109. # empty list, it will never match, so an error will always raise.
  110. super().__init__(hashes={FAVORITE_HASH: []})
  111. def _raise(self, gots: Dict[str, "_Hash"]) -> "NoReturn":
  112. raise HashMissing(gots[FAVORITE_HASH].hexdigest())