This repository has been archived on 2026-09-16. You can view files and clone it, but cannot push or open issues or pull requests.
win-diagnostics-analysis/tools/analyse.sh

26 lines
2.5 KiB
Bash
Executable File

#!/usr/bin/env bash
set -euo pipefail
root=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd -P)
fail(){ echo "error: $*" >&2; exit 1; }; usage(){ echo "Usage: $0 INPUT --evidence-root DIR --output FILE --reference-time TIME --producer-version VERSION [--force]" >&2; exit 2; }
sha256_file(){ if command -v sha256sum >/dev/null 2>&1; then sha256sum "$1"|awk '{print $1}'; elif command -v sha256 >/dev/null 2>&1; then sha256 -q "$1"; else openssl dgst -sha256 "$1"|awk '{print $NF}'; fi; }
input=${1:-}; [[ -n "$input" ]] || usage; shift
evidence_root= output= reference_time= producer_version= force=false
while (($#)); do case $1 in --evidence-root) evidence_root=$2;shift 2;;--output) output=$2;shift 2;;--reference-time) reference_time=$2;shift 2;;--producer-version) producer_version=$2;shift 2;;--force) force=true;shift;;*) usage;;esac;done
for value in "$evidence_root" "$output" "$reference_time" "$producer_version"; do [[ -n "$value" ]]||usage; done
[[ ! -L "$input" ]] || fail "input symlinks are not supported"
input=$(realpath "$input"); evidence_root=$(realpath "$evidence_root")
output_parent=$(dirname "$output"); mkdir -p "$output_parent"; output=$(cd "$output_parent" && pwd -P)/$(basename "$output")
[[ "$input" == "$evidence_root"/* ]] || fail "input must be inside --evidence-root"
[[ "$input" != "$output" ]] || fail "input and output paths must differ"
[[ ! -e "$output" || "$force" == true ]] || fail "$output: output exists; use --force to replace it"
artifact=${input#"$evidence_root/"}; hash=$(sha256_file "$input")
temporary=$(mktemp "$(dirname "$output")/.${output##*/}.XXXXXXXX")
stage=$(mktemp -d "${TMPDIR:-/tmp}/win-diagnostics.XXXXXXXX"); trap 'rm -f "$temporary"; rm -rf "$stage"' EXIT
cp "$input" "$stage/capture.json"; cp "$root/rules/event-rules.json" "$stage/event-rules.json"; cp "$root/rules/watchlist.json" "$stage/watchlist.json"; cp "$root/tools/analyse.typ" "$stage/analyse.typ"
typst query --root "$stage" --input capture=capture.json --input rules=event-rules.json --input watchlist=watchlist.json \
--input "artifact=$artifact" --input "artifact-hash=$hash" --input "reference-time=$reference_time" --input "producer-version=$producer_version" \
"$stage/analyse.typ" '<diagnostic>' --field value --one >"$temporary" 2>/dev/null || fail "analysis failed"
"$root/tools/validate.sh" "$temporary" --evidence-root "$evidence_root" || fail "generated diagnostic is invalid"
if [[ "$force" == true ]]; then mv -f "$temporary" "$output"; else ln "$temporary" "$output"; fi
echo "Wrote validated diagnostic v1: $output"