audit-backup-credentials.sh 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. #!/usr/bin/env bash
  2. # Audit a database backup (snapshot, WAL segment, or LMDB file) for
  3. # PLAINTEXT credentials.
  4. #
  5. # WHY THIS EXISTS, AND IT IS NOT THE OBVIOUS SCRIPT. The obvious version is
  6. # `grep -F` for a few credential names, and on these files it returns 0 for
  7. # EVERYTHING - including strings that are certainly present. Measured
  8. # 2026-10-19: `grep -c -F novitax` answered 0 on a WAL segment where
  9. # `strings -a | grep -c -F novitax` answered 5957, because the files carry
  10. # custom framing (CALWAL01 / CALSNAP1) with embedded NULs, so grep will not
  11. # surface text past them.
  12. #
  13. # WHY A CLEAN RESULT ON A *SNAPSHOT* IS WEAKER THAN THIS SCRIPT ORIGINALLY
  14. # CLAIMED. The header used to say the files "are not compressed; gzip still
  15. # halves them". That inference was wrong: the database owner confirmed
  16. # 2026-10-22 that the snapshot writer compresses with LZ4 whenever
  17. # `compression` is on, which is the DEFAULT, and gzip shrinking an LZ4 file
  18. # further is expected rather than evidence of anything. `strings -a` still
  19. # surfaces plaintext there, but for a different reason - LZ4 output is mostly
  20. # literal runs, so plaintext survives in FRAGMENTS.
  21. #
  22. # The consequence is an ASYMMETRY, and only one direction counts on a
  23. # snapshot: a HIT is real evidence of exposure, a MISS is NOT evidence of
  24. # safety. A long token - an API key, a 28-character document id - can be
  25. # split across an LZ4 match reference, so it is never shown whole and the
  26. # absence means "not found in the literal runs" rather than "not there".
  27. # So read a clean SNAPSHOT verdict as "nothing surfaced", never as "nothing
  28. # is there", and prefer a WAL segment or an LMDB file when an absence has to
  29. # carry weight - those are not written through the compressing path.
  30. #
  31. # The positive control below is still load-bearing: without it the check
  32. # cannot report at all. It simply does not upgrade a snapshot miss into an
  33. # absence, which is why the verdicts are PRESENT / REVIEW / EXPOSED rather
  34. # than a boolean.
  35. #
  36. # That makes the obvious script a check that CANNOT FAIL: it reports a clean
  37. # bill of health on a credential audit while being incapable of reporting an
  38. # exposure. A clean report is the most dangerous possible output for this
  39. # check, so every absence here is gated behind a POSITIVE CONTROL: unless a
  40. # string known to be in the file is found, the script refuses to draw any
  41. # conclusion and says so.
  42. #
  43. # The patterns are DERIVED FROM THE SOURCE that defines the credentials
  44. # rather than listed here, so the list cannot drift from the thing it checks.
  45. # (Suggested by a consumer who found the same shape in their own bundle
  46. # audit, where one pattern happened to be present and was an ACCIDENTAL
  47. # positive control - accidental being the problem.)
  48. #
  49. # Never prints a credential value. Counts and masked shapes only.
  50. set -uo pipefail
  51. # NOTE: never `strings ... | grep -q` in this script. `grep -q` exits on the
  52. # FIRST match, which SIGPIPEs `strings`, and under `pipefail` that makes the
  53. # whole pipeline non-zero - so a control that MATCHED reports as failed. That
  54. # bug made every real file report CANNOT DETERMINE on the first run of this
  55. # script. Use `grep -c` (which consumes all input) and compare the count.
  56. SRC_DIR="${SRC_DIR:-$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)/src}"
  57. die() { printf 'audit: %s\n' "$*" >&2; exit 2; }
  58. [ $# -ge 1 ] || die "usage: $0 <backup-file-or-directory>..."
  59. # --- derive the patterns from the stores that define the credentials --------
  60. derive_patterns() {
  61. # Credential-bearing collection names, from the collection constants.
  62. grep -rhno 'vectorapi_\(keys\|settings\|secrets\)' "$SRC_DIR" 2>/dev/null \
  63. | cut -d: -f2- | sort -u
  64. # Credential VALUE field names, from the stores' own serialisation.
  65. grep -rhno '"\(openai_api_key\|api_key\|apiKey\|password\|secret\|token\|credentials\)"' \
  66. "$SRC_DIR" 2>/dev/null | cut -d: -f2- | tr -d '"' | sort -u
  67. }
  68. mapfile -t PATTERNS < <(derive_patterns)
  69. [ "${#PATTERNS[@]}" -gt 0 ] || die "derived NO patterns from $SRC_DIR - refusing to report anything"
  70. rc=0
  71. printf 'audit: %d pattern(s) derived from %s\n\n' "${#PATTERNS[@]}" "$SRC_DIR"
  72. audit_one() {
  73. local f="$1"
  74. printf '=== %s ===\n' "$f"
  75. # One `strings` pass per file, reused for every pattern. These files run to
  76. # hundreds of MB and re-reading per pattern made the audit minutes long.
  77. local tok
  78. tok=$(mktemp) || die "mktemp failed"
  79. strings -a "$f" 2>/dev/null > "$tok"
  80. # --- the positive control, before any absence is believed ---------------
  81. # The file's own magic is a string we KNOW is at offset 0. If `strings`
  82. # cannot surface that, it cannot surface anything, and no zero below means
  83. # a thing.
  84. local magic
  85. magic=$(head -c 8 "$f" 2>/dev/null | tr -dc 'A-Za-z0-9')
  86. if [ "${#magic}" -lt 4 ]; then
  87. printf ' CONTROL: INCONCLUSIVE - no printable magic; falling back to token yield\n'
  88. local tokens
  89. tokens=$(head -2000 "$tok" | wc -l)
  90. if [ "$tokens" -lt 10 ]; then
  91. printf ' RESULT: CANNOT DETERMINE - only %d printable token(s). NO ABSENCE BELOW MEANS ANYTHING.\n\n' "$tokens"
  92. rc=3; rm -f "$tok"; return
  93. fi
  94. printf ' CONTROL: PASS via token yield (%d tokens)\n' "$tokens"
  95. elif [ "$(grep -c -F "$magic" "$tok")" -eq 0 ]; then
  96. printf ' RESULT: CANNOT DETERMINE - the control string %s is in the file but not findable.\n' "$magic"
  97. printf ' NO ABSENCE BELOW MEANS ANYTHING. Do not read this as clean.\n\n'
  98. rc=3; rm -f "$tok"; return
  99. else
  100. printf ' CONTROL: PASS - %s findable, so this file IS searchable\n' "$magic"
  101. fi
  102. # --- positive evidence of encryption ------------------------------------
  103. local enc encj
  104. enc=$(grep -c -F '$ENC$' "$tok")
  105. encj=$(grep -c -F '$ENCJ$' "$tok")
  106. printf ' ciphertext markers: $ENC$=%s $ENCJ$=%s\n' "$enc" "$encj"
  107. # --- the actual question -------------------------------------------------
  108. local found=0 p n
  109. for p in "${PATTERNS[@]}"; do
  110. n=$(grep -c -F "$p" "$tok")
  111. [ "$n" -gt 0 ] && { printf ' PRESENT: %-22s %s hit(s)\n' "$p" "$n"; found=1; }
  112. done
  113. # A key-SHAPED token is the thing that matters, not a field name: a field
  114. # name can appear in tenant content. Anchored at a token start, because
  115. # `sk-` occurs mid-blob in ciphertext by chance (seen 2026-10-19).
  116. local shaped
  117. shaped=$(grep -c -E '(^|[^A-Za-z0-9_-])sk-[A-Za-z0-9_-]{20,}' "$tok")
  118. if [ "$shaped" -gt 0 ]; then
  119. printf ' *** EXPOSED: %s key-shaped token(s) (sk- at a token start, 20+ chars)\n' "$shaped"
  120. rc=1
  121. elif [ "$found" -eq 0 ]; then
  122. printf ' RESULT: CLEAN - control passed and no credential pattern present\n'
  123. else
  124. printf ' RESULT: REVIEW - credential field/collection names present but no key-shaped token\n'
  125. [ "$rc" -eq 0 ] && rc=4
  126. fi
  127. rm -f "$tok"
  128. printf '\n'
  129. }
  130. for target in "$@"; do
  131. [ -e "$target" ] || die "no such path: $target (refusing to report clean for a path that does not exist)"
  132. if [ -d "$target" ]; then
  133. while IFS= read -r -d '' f; do audit_one "$f"; done \
  134. < <(find "$target" -type f ! -name 'SHA256SUMS' ! -name '*.md' ! -name '*.txt' -print0)
  135. else
  136. audit_one "$target"
  137. fi
  138. done
  139. case $rc in
  140. 0) printf 'audit: CLEAN (every file had a passing control)\n' ;;
  141. 1) printf 'audit: EXPOSED - plaintext key-shaped material found\n' ;;
  142. 3) printf 'audit: INCONCLUSIVE for at least one file - absences there mean nothing\n' ;;
  143. 4) printf 'audit: REVIEW needed\n' ;;
  144. esac
  145. exit $rc