#!/usr/bin/env bash
# Ceidwad Hidl HTTPS chain check for macOS and Linux (the bash twin of Invoke-HidlCheck.ps1).
#
# For each host: TCP 443 (through $https_proxy if set), TLS handshake with SNI via
# `openssl s_client`, record the chain the device was given, close. No HTTP request is
# sent to the website and no page is read. Nothing is sent to Ceidwad.
#
# The chain is "public_ca" if it verifies against the bundled public roots
# (data/public-roots.pem.txt). Otherwise, if it ends at a root this device trusts that is
# not public, or at a self-signed root the server sent, it is "not_public_ca":
# usually HTTPS inspection; it may also be a public root that Hidl's list does not hold.
# If the root cannot be found, "unknown_issuer".
#
# Output: hidl-chain-<date>.json (schema/chain-result.schema.json) and a short summary.
# The file holds no device name, user name or IP address. It does hold the names written
# inside the certificates it saw. If your filter re-signs sites, its certificate may carry your
# school's or trust's name, an internal server name or the filter maker's name, and any site you
# add with --host is recorded as you typed it. Treat the file as school information and keep it
# on the device or inside your school.
#
# Usage: hidl-chain.sh [--host HOST]... [--no-default-hosts] [--no-category-sites]
#                      [--no-proxy] [--out DIR] [--timeout SECONDS]
set -u

HIDL_VERSION="0.1.0"
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
DATA="$HERE/data"
PUBLIC_PEM="${HIDL_CHAIN_PUBLIC_PEM:-$DATA/public-roots.pem.txt}"
PUBLIC_JSON="$DATA/public-roots.json"
HOSTS_JSON="$DATA/default-hosts.json"
OPENSSL="${OPENSSL:-openssl}"
# Test hooks: HIDL_CHAIN_SCLIENT replaces `openssl s_client` (called with the host name);
# HIDL_CHAIN_SYSTEM_CAFILE replaces the system trust store.
SCLIENT="${HIDL_CHAIN_SCLIENT:-}"
SYSTEM_CAFILE="${HIDL_CHAIN_SYSTEM_CAFILE:-}"

json_str() {
  # JSON string literal, or null for an empty value.
  if [ -z "${1:-}" ]; then printf 'null'; return; fi
  printf '"%s"' "$(printf '%s' "$1" | tr -d '\000-\037' | sed -e 's/\\/\\\\/g' -e 's/"/\\"/g')"
}

clean_host() {
  # Bare lower-case host name, or nothing if it is not one.
  local h
  h="$(printf '%s' "$1" | tr 'A-Z' 'a-z' | sed -e 's#^[a-z][a-z0-9+.-]*://##' -e 's#[/?\#].*$##' -e 's#:443$##')"
  if printf '%s' "$h" | grep -Eq '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?(\.[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$' && [ ${#h} -le 253 ]; then
    printf '%s' "$h"
  fi
}

default_hosts() {
  # Prints "host<TAB>category" per default host. $1 = 1 to drop category sites.
  awk -v nocat="$1" '
    /"host":/     { gsub(/.*"host": *"|".*/, ""); host=$0 }
    /"category":/ { c=$0; if (c ~ /null/) cat=""; else { gsub(/.*"category": *"|".*/, "", c); cat=c }
                    if (host != "" && (nocat != "1" || cat == "help_site" || cat == "control")) print host "\t" cat
                    host="" }' "$HOSTS_JSON"
}

roots_meta() {
  # generated date and count from public-roots.json
  local gen count
  gen="$(grep -m1 '"generated"' "$PUBLIC_JSON" | sed -e 's/.*"generated": *"//' -e 's/".*//')"
  count="$(grep -m1 '"count"' "$PUBLIC_JSON" | sed -e 's/[^0-9]//g')"
  printf '%s\t%s' "$gen" "$count"
}

has_opt() { "$OPENSSL" "$1" -help 2>&1 | grep -q -- "$2"; }

x509_field() {
  # x509_field FILE subject|issuer|sha1|sha256|enddate
  local f="$1" v
  case "$2" in
    subject) v="$("$OPENSSL" x509 -in "$f" -noout -subject -nameopt RFC2253 2>/dev/null || "$OPENSSL" x509 -in "$f" -noout -subject)"; v="${v#subject=}";;
    issuer)  v="$("$OPENSSL" x509 -in "$f" -noout -issuer -nameopt RFC2253 2>/dev/null || "$OPENSSL" x509 -in "$f" -noout -issuer)"; v="${v#issuer=}";;
    sha1)    v="$("$OPENSSL" x509 -in "$f" -noout -fingerprint -sha1)"; v="$(printf '%s' "${v#*=}" | tr -d ':' | tr 'a-f' 'A-F')";;
    sha256)  v="$("$OPENSSL" x509 -in "$f" -noout -fingerprint -sha256)"; v="$(printf '%s' "${v#*=}" | tr -d ':' | tr 'a-f' 'A-F')";;
    enddate) v="$(iso_enddate "$f")";;
  esac
  printf '%s' "$v" | sed -e 's/^ *//' -e 's/ *$//'
}

iso_enddate() {
  local raw
  raw="$("$OPENSSL" x509 -in "$1" -noout -enddate -dateopt iso_8601 2>/dev/null)"
  if [ -n "$raw" ]; then
    raw="${raw#notAfter=}"; printf '%s' "$raw" | sed -e 's/ /T/' -e 's/Z$//' -e 's/$/Z/'; return
  fi
  raw="$("$OPENSSL" x509 -in "$1" -noout -enddate)"; raw="${raw#notAfter=}"
  date -u -d "$raw" '+%Y-%m-%dT%H:%M:%SZ' 2>/dev/null \
    || date -u -j -f '%b %e %T %Y %Z' "$raw" '+%Y-%m-%dT%H:%M:%SZ' 2>/dev/null \
    || printf ''
}

cert_json() {
  # cert_json FILE POSITION
  local subj iss
  subj="$(x509_field "$1" subject)"; iss="$(x509_field "$1" issuer)"
  printf '{"position":"%s","subject":%s,"issuer":%s,"sha1":%s,"sha256":%s,"notAfter":%s,"selfSigned":%s}' \
    "$2" "$(json_str "$subj")" "$(json_str "$iss")" "$(json_str "$(x509_field "$1" sha1)")" \
    "$(json_str "$(x509_field "$1" sha256)")" "$(json_str "$(x509_field "$1" enddate)")" \
    "$([ "$subj" = "$iss" ] && echo true || echo false)"
}

index_public_roots() {
  # Splits the public PEM bundle into $1/root-N.pem and writes $1/index ("subject<TAB>file").
  local dir="$1"
  awk -v d="$dir" '/BEGIN CERTIFICATE/{n++; f=d "/root-" n ".pem"} f{print > f} /END CERTIFICATE/{close(f); f=""}' "$PUBLIC_PEM"
  : > "$dir/index"
  for f in "$dir"/root-*.pem; do
    [ -f "$f" ] && printf '%s\t%s\n' "$(x509_field "$f" subject)" "$f" >> "$dir/index"
  done
}

run_sclient() {
  # run_sclient HOST OUTFILE TIMEOUT PROXY -> 0 ok, 124 timeout
  local host="$1" out="$2" t="$3" proxy="$4" pid w rc
  if [ -n "$SCLIENT" ]; then
    "$SCLIENT" "$host" > "$out" 2>&1 < /dev/null &
  elif [ -n "$proxy" ]; then
    # Proxy sign-in from the proxy URL, if any; the password goes through the environment,
    # never the command line.
    local creds="" user="" auth=()
    creds="${https_proxy:-${HTTPS_PROXY:-}}"; creds="${creds#*://}"
    case "$creds" in *@*) creds="${creds%%@*}"; user="${creds%%:*}";; *) creds="";; esac
    if [ -n "$user" ] && has_opt s_client '-proxy_user'; then
      auth=(-proxy_user "$user" -proxy_pass env:HIDL_PROXY_PASS)
      export HIDL_PROXY_PASS="${creds#*:}"
    fi
    "$OPENSSL" s_client -connect "$host:443" -servername "$host" -showcerts -proxy "$proxy" "${auth[@]+"${auth[@]}"}" > "$out" 2>&1 < /dev/null &
  else
    "$OPENSSL" s_client -connect "$host:443" -servername "$host" -showcerts > "$out" 2>&1 < /dev/null &
  fi
  pid=$!
  ( sleep "$t"; kill "$pid" 2>/dev/null && touch "$out.timeout" ) > /dev/null 2>&1 &
  w=$!
  wait "$pid"; rc=$?
  if [ "$rc" -gt 128 ]; then wait "$w" 2>/dev/null; else kill "$w" 2>/dev/null; wait "$w" 2>/dev/null; fi
  if [ -f "$out.timeout" ]; then rm -f "$out.timeout"; return 124; fi
  return "$rc"
}

proxy_for() {
  # The proxy from https_proxy / HTTPS_PROXY as host:port, unless no_proxy matches.
  local host="$1" p np entry
  p="${https_proxy:-${HTTPS_PROXY:-}}"
  [ -z "$p" ] && return 0
  np="${no_proxy:-${NO_PROXY:-}}"
  for entry in $(printf '%s' "$np" | tr ',' ' '); do
    entry="${entry#.}"; entry="${entry#\*.}"
    case "$host" in "$entry"|*".$entry") return 0;; esac
  done
  p="${p#*://}"; p="${p##*@}"; p="${p%%/*}"
  printf '%s' "$p"
}

check_host() {
  # check_host HOST CATEGORY TIMEOUT NOPROXY WORKDIR -> prints one result JSON object
  local host="$1" cat="$2" t="$3" noproxy="$4" work="$5"
  local dir="$work/$host" out proxy="" via="direct" rc status="ok" err="" proto="" cipher=""
  mkdir -p "$dir"; out="$dir/sclient.txt"
  if [ "$noproxy" != 1 ]; then proxy="$(proxy_for "$host")"; fi
  if [ -n "$proxy" ] && [ -z "$SCLIENT" ] && ! has_opt s_client '-proxy'; then proxy=""; fi
  [ -n "$proxy" ] && via="proxy"
  run_sclient "$host" "$out" "$t" "$proxy"; rc=$?

  awk -v d="$dir" '/BEGIN CERTIFICATE/{n++; f=d "/c" (n-1) ".pem"} f{print > f} /END CERTIFICATE/{close(f); f=""}' "$out"
  local n=0; while [ -f "$dir/c$n.pem" ]; do n=$((n+1)); done

  if [ "$n" -eq 0 ]; then
    if [ "$rc" -eq 124 ]; then status="timeout"; err="No answer within the time limit."
    elif grep -Eqi 'getaddrinfo|Name or service not known|nodename nor servname|could not resolve' "$out"; then status="no_connection"; err="The name did not resolve (the filter may block it by DNS)."
    elif grep -Eqi 'CONNECT failed|proxy' "$out"; then status="no_connection"; err="The device proxy refused the connection (it may need a sign-in)."
    elif grep -Eqi 'connect:errno|Connection refused|connect error|Network is unreachable|BIO_connect' "$out"; then status="no_connection"; err="The connection was refused or reset."
    else status="tls_failed"; err="The secure connection could not be set up."; fi
    printf '{"host":%s,"port":443,"category":%s,"via":"%s","status":"%s","tls":null,"chain":[],"verdict":"not_tested","inspected":null,"issuerHint":null,"error":%s}' \
      "$(json_str "$host")" "$(json_str "$cat")" "$via" "$status" "$(json_str "$err")"
    return
  fi

  proto="$(grep -m1 -E '^ *Protocol *:' "$out" | sed -e 's/.*: *//')"
  [ -z "$proto" ] && proto="$(grep -m1 -E '^New, ' "$out" | sed -e 's/^New, //' -e 's/,.*//')"
  cipher="$(grep -m1 -E 'Cipher is ' "$out" | sed -e 's/.*Cipher is //')"
  [ -z "$cipher" ] && cipher="$(grep -m1 -E '^ *Cipher *:' "$out" | sed -e 's/.*: *//')"

  # Chain records for the certificates the server sent.
  local chain="" i pos last top top_subj top_iss
  last=$((n-1)); top="$dir/c$last.pem"
  : > "$dir/untrusted.pem"
  i=0
  while [ "$i" -lt "$n" ]; do
    pos="intermediate"; [ "$i" -eq 0 ] && pos="leaf"
    top_subj="$(x509_field "$dir/c$i.pem" subject)"; top_iss="$(x509_field "$dir/c$i.pem" issuer)"
    [ "$i" -eq "$last" ] && [ "$i" -gt 0 ] && [ "$top_subj" = "$top_iss" ] && pos="root"
    [ "$i" -gt 0 ] && cat "$dir/c$i.pem" >> "$dir/untrusted.pem"
    chain="$chain${chain:+,}$(cert_json "$dir/c$i.pem" "$pos")"
    i=$((i+1))
  done
  top_subj="$(x509_field "$top" subject)"; top_iss="$(x509_field "$top" issuer)"

  local notime="" verdict inspected hint root_file
  local -a untrusted=() sysargs=()
  local -a nodefault=()
  has_opt verify '-no_check_time' && notime="-no_check_time"
  # openssl verify also loads the system store unless told not to; the device trusts the
  # filter's root, so the public check must use the bundled roots only.
  has_opt verify '-no-CApath' && nodefault+=(-no-CApath)
  has_opt verify '-no-CAstore' && nodefault+=(-no-CAstore)
  [ "$n" -gt 1 ] && untrusted=(-untrusted "$dir/untrusted.pem")
  # shellcheck disable=SC2086
  if "$OPENSSL" verify $notime "${nodefault[@]+"${nodefault[@]}"}" -CAfile "$PUBLIC_PEM" "${untrusted[@]+"${untrusted[@]}"}" "$dir/c0.pem" > /dev/null 2>&1; then
    verdict="public_ca"; inspected=false; hint="$top_iss"
    if [ "$top_subj" != "$top_iss" ]; then
      root_file="$(awk -F '\t' -v s="$top_iss" '$1 == s { print $2; exit }' "$work/roots/index")"
      if [ -n "$root_file" ]; then chain="$chain,$(cert_json "$root_file" root)"; fi
    else
      hint="$top_subj"
    fi
  elif [ "$n" -gt 1 ] && [ "$top_subj" = "$top_iss" ]; then
    verdict="not_public_ca"; inspected=true; hint="$top_subj"
  else
    [ -n "$SYSTEM_CAFILE" ] && sysargs=(-CAfile "$SYSTEM_CAFILE")
    # shellcheck disable=SC2086
    if "$OPENSSL" verify $notime "${sysargs[@]+"${sysargs[@]}"}" "${untrusted[@]+"${untrusted[@]}"}" "$dir/c0.pem" > /dev/null 2>&1; then
      verdict="not_public_ca"; inspected=true; hint="$top_iss"
    else
      verdict="unknown_issuer"; inspected=null; hint="$top_iss"
    fi
  fi

  printf '{"host":%s,"port":443,"category":%s,"via":"%s","status":"ok","tls":{"protocol":%s,"cipher":%s},"chain":[%s],"verdict":"%s","inspected":%s,"issuerHint":%s,"error":null}' \
    "$(json_str "$host")" "$(json_str "$cat")" "$via" "$(json_str "$proto")" "$(json_str "$cipher")" \
    "$chain" "$verdict" "$inspected" "$(json_str "$hint")"
}

main() {
  local hosts=() nodefault=0 nocat=0 noproxy=0 outdir="$PWD" timeout=10
  while [ $# -gt 0 ]; do
    case "$1" in
      --host|-H) shift; IFS=',' read -r -a parts <<< "${1:-}"; hosts+=("${parts[@]+"${parts[@]}"}");;
      --no-default-hosts) nodefault=1;;
      --no-category-sites) nocat=1;;
      --no-proxy) noproxy=1;;
      --out) shift; outdir="${1:-.}";;
      --timeout) shift; timeout="${1:-10}";;
      -h|--help) sed -n '2,20p' "${BASH_SOURCE[0]}" | sed 's/^# \{0,1\}//'; return 0;;
      *) echo "Unknown option: $1" >&2; return 2;;
    esac
    shift
  done
  command -v "$OPENSSL" > /dev/null 2>&1 || { echo "openssl is needed and was not found." >&2; return 1; }

  local work list h c clean parts
  HIDL_CHAIN_WORK="$(mktemp -d "${TMPDIR:-/tmp}/hidl-chain.XXXXXX")"; work="$HIDL_CHAIN_WORK"
  trap 'rm -rf "$HIDL_CHAIN_WORK"' EXIT
  list="$work/targets"; : > "$list"
  [ "$nodefault" = 1 ] || default_hosts "$nocat" > "$list"
  for h in "${hosts[@]+"${hosts[@]}"}"; do
    clean="$(clean_host "$h")"
    if [ -z "$clean" ]; then echo "Skipped '$h': not a host name." >&2; continue; fi
    awk -F '\t' -v h="$clean" '$1 == h { found=1 } END { exit !found }' "$list" || printf '%s\t\n' "$clean" >> "$list"
  done
  local total; total="$(wc -l < "$list" | tr -d ' ')"
  [ "$total" -gt 0 ] || { echo "No hosts to check." >&2; return 1; }

  mkdir -p "$work/roots"; index_public_roots "$work/roots"

  echo "Ceidwad Hidl chain check $HIDL_VERSION"
  echo "This opens a secure connection to $total websites and reads only the certificate each one presents. No page is loaded."
  echo "Your school's monitoring may log the site names, so tell your DSL before you run it. Nothing is sent to Ceidwad."
  echo

  local results="" i=0 r
  while IFS="$(printf '\t')" read -r h c; do
    i=$((i+1)); printf '\r  %s of %s: %-50s' "$i" "$total" "$h" >&2
    r="$(check_host "$h" "$c" "$timeout" "$noproxy" "$work")"
    results="$results${results:+,}$r"
  done < "$list"
  printf '\r%-70s\r' '' >&2

  local meta gen count platform="other" runtime
  meta="$(roots_meta)"; gen="${meta%%	*}"; count="${meta##*	}"
  case "$(uname -s)" in Darwin) platform="macos";; Linux) platform="linux";; esac
  runtime="$("$OPENSSL" version 2>/dev/null | head -n1)"
  mkdir -p "$outdir"
  local file="$outdir/hidl-chain-$(date +%Y-%m-%d).json"
  [ -e "$file" ] && file="$outdir/hidl-chain-$(date +%Y-%m-%d-%H%M%S).json"
  printf '{"schema":"hidl.chain-result/1","tool":{"name":"hidl-chain.sh","version":"%s","runtime":%s},"generatedAt":"%s","platform":"%s","publicRoots":{"generated":%s,"count":%s,"sources":[]},"results":[%s]}\n' \
    "$HIDL_VERSION" "$(json_str "$runtime")" "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$platform" "$(json_str "$gen")" "${count:-0}" "$results" > "$file"

  local pub insp unk none
  pub="$(grep -o '"verdict":"public_ca"' "$file" | wc -l | tr -d ' ')"
  insp="$(grep -o '"verdict":"not_public_ca"' "$file" | wc -l | tr -d ' ')"
  unk="$(grep -o '"verdict":"unknown_issuer"' "$file" | wc -l | tr -d ' ')"
  none="$(grep -o '"verdict":"not_tested"' "$file" | wc -l | tr -d ' ')"
  echo "Checked $total websites."
  echo "  Public certificate authority: $pub"
  echo "  Not in Hidl's public list (usually inspection): $insp"
  echo "  Root not found: $unk"
  echo "  No secure connection: $none"
  if [ "$insp" -gt 0 ]; then
    echo
    echo "Connections whose root is not in Hidl's public list were signed by:"
    printf '%s' "$results" | grep -o '"verdict":"not_public_ca","inspected":true,"issuerHint":"[^"]*"' \
      | sed -e 's/.*"issuerHint":"//' -e 's/"$//' | sort | uniq -c | sed 's/^ */  /'
    echo "This is usually your filter's own certificate (HTTPS inspection). It can also be a private CA or a public root that Hidl's list does not hold."
  fi
  echo
  echo "Saved: $file"
  echo "The file holds no device name, user name or IP address. It does hold the names written inside the certificates it saw, which may include your school's or trust's name, an internal server name or the filter maker's name, and any site you added with --host as you typed it. Treat it as school information and keep it on this device or inside your school."
}

if [ "${HIDL_CHAIN_LIB:-0}" != 1 ]; then main "$@"; fi
