hashes.py 4.7 KB

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