check-hash 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. #!/usr/bin/env bash
  2. set -e
  3. # Helper to check a file matches its known hash
  4. # Call it with:
  5. # $1: the path of the file containing all the the expected hashes
  6. # $2: the full path to the temporary file that was downloaded, and
  7. # that is to be checked
  8. # $3: the final basename of the file, to which it will be ultimately
  9. # saved as, to be able to match it to the corresponding hashes
  10. # in the .hash file
  11. while getopts :q OPT; do
  12. case "${OPT}" in
  13. q) exec >/dev/null;;
  14. \?) exit 1;;
  15. esac
  16. done
  17. shift $((OPTIND-1))
  18. h_file="${1}"
  19. file="${2}"
  20. base="${3}"
  21. # Does the hash-file exist?
  22. if [ -z "${h_file}" -o ! -f "${h_file}" ]; then
  23. exit 0
  24. fi
  25. # Check one hash for a file
  26. # $1: known hash
  27. # $2: file (full path)
  28. check_one_hash() {
  29. _h="${1}"
  30. _known="${2}"
  31. _file="${3}"
  32. # Note: md5 is supported, but undocumented on purpose.
  33. # Note: sha3 is not supported, since there is currently no implementation
  34. # (the NIST has yet to publish the parameters).
  35. case "${_h}" in
  36. md5|sha1) ;;
  37. sha224|sha256|sha384|sha512) ;;
  38. *) # Unknown hash, exit with error
  39. printf "ERROR: unknown hash '%s' for '%s'\n" \
  40. "${_h}" "${base}" >&2
  41. exit 1
  42. ;;
  43. esac
  44. # Do the hashes match?
  45. _hash=$( ${_h}sum "${_file}" |cut -d ' ' -f 1 )
  46. if [ "${_hash}" = "${_known}" ]; then
  47. printf "%s: OK (%s: %s)\n" "${base}" "${_h}" "${_hash}"
  48. return 0
  49. fi
  50. printf "ERROR: %s has wrong %s hash:\n" "${base}" "${_h}" >&2
  51. printf "ERROR: expected: %s\n" "${_known}" >&2
  52. printf "ERROR: got : %s\n" "${_hash}" >&2
  53. printf "ERROR: Incomplete download, or man-in-the-middle (MITM) attack\n" >&2
  54. exit 1
  55. }
  56. # Do we know one or more hashes for that file?
  57. nb_checks=0
  58. while read t h f; do
  59. case "${t}" in
  60. ''|'#'*)
  61. # Skip comments and empty lines
  62. continue
  63. ;;
  64. *)
  65. if [ "${f}" = "${base}" ]; then
  66. check_one_hash "${t}" "${h}" "${file}"
  67. : $((nb_checks++))
  68. fi
  69. ;;
  70. esac
  71. done <"${h_file}"
  72. if [ ${nb_checks} -eq 0 ]; then
  73. if [ -n "${BR2_ENFORCE_CHECK_HASH}" ]; then
  74. printf "ERROR: No hash found for %s\n" "${base}" >&2
  75. exit 1
  76. else
  77. printf "WARNING: No hash found for %s\n" "${base}" >&2
  78. fi
  79. fi