2
1

check-hash 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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 full path to the file to check
  6. # $2: the path of the file containing all the the expected hashes
  7. h_file="${1}"
  8. file="${2}"
  9. # Does the hash-file exist?
  10. if [ ! -f "${h_file}" ]; then
  11. exit 0
  12. fi
  13. # Check one hash for a file
  14. # $1: known hash
  15. # $2: file (full path)
  16. check_one_hash() {
  17. _h="${1}"
  18. _known="${2}"
  19. _file="${3}"
  20. # Note: md5 is supported, but undocumented on purpose.
  21. # Note: sha3 is not supported, since there is currently no implementation
  22. # (the NIST has yet to publish the parameters).
  23. case "${_h}" in
  24. md5|sha1) ;;
  25. sha224|sha256|sha384|sha512) ;;
  26. *) # Unknown hash, exit with error
  27. printf "ERROR: unknown hash '%s' for '%s'\n" \
  28. "${_h}" "${_file##*/}" >&2
  29. exit 1
  30. ;;
  31. esac
  32. # Do the hashes match?
  33. _hash=$( ${_h}sum "${_file}" |cut -d ' ' -f 1 )
  34. if [ "${_hash}" = "${_known}" ]; then
  35. printf "%s: OK (%s: %s)\n" "${_file##*/}" "${_h}" "${_hash}"
  36. return 0
  37. fi
  38. printf "ERROR: %s has wrong %s hash:\n" "${_file##*/}" "${_h}" >&2
  39. printf "ERROR: expected: %s\n" "${_known}" >&2
  40. printf "ERROR: got : %s\n" "${_hash}" >&2
  41. printf "ERROR: Incomplete download, or man-in-the-middle (MITM) attack\n" >&2
  42. exit 1
  43. }
  44. # Do we know one or more hashes for that file?
  45. nb_checks=0
  46. while read t h f; do
  47. case "${t}" in
  48. ''|'#'*)
  49. # Skip comments and empty lines
  50. continue
  51. ;;
  52. *)
  53. if [ "${f}" = "${file##*/}" ]; then
  54. check_one_hash "${t}" "${h}" "${file}"
  55. : $((nb_checks++))
  56. fi
  57. ;;
  58. esac
  59. done <"${h_file}"
  60. if [ ${nb_checks} -eq 0 ]; then
  61. if [ -n "${BR2_ENFORCE_CHECK_HASH}" ]; then
  62. printf "ERROR: No hash found for %s\n" "${file}" >&2
  63. exit 1
  64. else
  65. printf "WARNING: No hash found for %s\n" "${file}" >&2
  66. fi
  67. fi