#!/bin/sh
# Bay Geeks Post-Quantum Check for Mac and Linux (free, one computer). Version 1.
#
# What it does: reads this computer's encryption settings, writes a report
# to your Desktop (or home folder) and opens it. It only reads settings. It
# changes nothing, installs nothing, needs no administrator password, and
# sends nothing anywhere: no network connections at all. Private keys are
# never read.
#
# How to run, in Terminal:
#   sh ~/Downloads/bay-geeks-pq-check-v1.sh
#
# Bay Geeks, LLC, St. Petersburg, Florida. 727-579-4335. baygeeks.com
# Source of truth: rmm/crypto/self-check/ in the Bay Geeks repo; the
# published copy is a versioned file (-v1, -v2 ...), never overwritten.
# Plain POSIX sh: macOS ships bash 3.2 and Debian runs dash.

VERSION=1
NO_OPEN=0
OUT_DIR=""
while [ $# -gt 0 ]; do
  case "$1" in
    --no-open) NO_OPEN=1 ;;
    --out) shift; OUT_DIR="$1" ;;
  esac
  shift
done

US=$(printf '\037')
ROWS=$(mktemp "${TMPDIR:-/tmp}/bgpq.XXXXXX") || exit 1
trap 'rm -f "$ROWS"' EXIT INT TERM

# row STATUS WHAT FOUND WHY [FIX]
# status: fix-now | pq-exposed | pq-later | pq-ready | ok | info
row() { printf '%s\037%s\037%s\037%s\037%s\n' "$1" "$2" "$3" "$4" "${5:-}" >> "$ROWS"; }
have() { command -v "$1" >/dev/null 2>&1; }
major() { printf '%s' "$1" | sed 's/^[^0-9]*//; s/[^0-9].*//'; }
ge() { [ -n "$1" ] && [ "$1" -ge "$2" ] 2>/dev/null; }

echo "Bay Geeks Post-Quantum Check: reading this computer's settings (nothing is changed or sent)..."

OS=$(uname -s)
if [ "$OS" = Darwin ]; then
  NAME=$(scutil --get ComputerName 2>/dev/null || hostname)
  MACVER=$(sw_vers -productVersion 2>/dev/null)
  OSNAME="macOS $MACVER"
else
  NAME=$(hostname 2>/dev/null || uname -n)
  OSNAME=$(. /etc/os-release 2>/dev/null; printf '%s' "${PRETTY_NAME:-Linux}")
fi

# ------------------------------------------------------------------ macOS
if [ "$OS" = Darwin ]; then
  M=$(major "$MACVER")
  if ge "$M" 26; then
    row pq-ready "Apple's secure connections (Safari, Mail, most apps)" "$OSNAME" \
      "macOS Tahoe 26 and later set up connections with post-quantum (hybrid ML-KEM) protection by default with servers that support it."
    if [ "$(defaults read com.apple.network.tls AllowPQTLSFallback 2>/dev/null)" = 1 ]; then
      row info "Post-quantum fallback setting" "AllowPQTLSFallback on" \
        "Someone turned on Apple's temporary compatibility setting for old servers. Apple says it will be removed in a future version." \
        "Turn it off once the old server it was for has been updated."
    fi
  else
    row pq-exposed "Apple's secure connections (Safari, Mail, most apps)" "$OSNAME" \
      "This version of macOS sets up connections without post-quantum protection. Apple added it, on by default, in macOS Tahoe 26." \
      "Update to macOS Tahoe 26 or later if this Mac supports it."
  fi

  FV=$(fdesetup status 2>/dev/null | head -1)
  case "$FV" in
    *"is On"*) row ok "Disk encryption (FileVault)" "$FV" "Encrypted with AES, which holds up against quantum computers." ;;
    *"is Off"*) row fix-now "Disk encryption (FileVault)" "$FV" \
      "This Mac's disk is not encrypted. If it is lost or stolen, anyone can read the files on it. No quantum computer needed." \
      "Turn on FileVault in System Settings, Privacy and Security, and keep the recovery key somewhere safe, away from this Mac." ;;
    *) row info "Disk encryption (FileVault)" "${FV:-could not be read}" "FileVault is changing state or could not be read; check System Settings, Privacy and Security." ;;
  esac

  WIFI=$(system_profiler SPAirPortDataType 2>/dev/null | awk '/Current Network Information:/{f=1;next} f&&/Security:/{sub(/.*Security: */,"");print;exit}')
fi

# ------------------------------------------------------------------ Linux
if [ "$OS" = Linux ]; then
  SRC=$(findmnt -no SOURCE / 2>/dev/null | sed 's/\[.*//')
  case "$SRC" in
    /dev/*)
      if lsblk -s -rno TYPE "$SRC" 2>/dev/null | grep -qx crypt; then
        row ok "Disk encryption" "system disk encrypted (LUKS)" "Encrypted with AES, which holds up against quantum computers."
      else
        row fix-now "Disk encryption" "system disk not encrypted" \
          "If this computer is lost or stolen, anyone can read the files on it. No quantum computer needed." \
          "Full-disk encryption (LUKS) is usually set when the system is installed; plan it for the next reinstall, or encrypt the folders that hold business files."
      fi ;;
    *) row info "Disk encryption" "${SRC:-unknown} on /" "Could not tell whether the system disk is encrypted (for example ZFS or a container)." ;;
  esac

  if have openssl; then
    OV=$(openssl version 2>/dev/null)
    OMAJ=$(printf '%s' "$OV" | awk '{print $2}' | cut -d. -f1)
    OMIN=$(printf '%s' "$OV" | awk '{print $2}' | cut -d. -f2 | sed 's/[^0-9].*//')
    case "$OV" in
      OpenSSL*)
        if ge "$OMAJ" 4 || { [ "$OMAJ" = 3 ] && ge "$OMIN" 5; }; then
          row pq-ready "System encryption library (OpenSSL)" "$OV" \
            "OpenSSL 3.5 and later offer post-quantum (hybrid ML-KEM) key exchange by default, for programs that use the system's settings."
        else
          row pq-exposed "System encryption library (OpenSSL)" "$OV" \
            "This OpenSSL has no post-quantum key exchange. Programs that use it set up connections the classical way." \
            "It arrives with your distribution's next major release (OpenSSL 3.5 or later)."
        fi ;;
      *) row info "System encryption library" "$OV" "Not OpenSSL; not graded." ;;
    esac
  fi

  if have nmcli; then
    WIFI=$(nmcli -t -f ACTIVE,SECURITY dev wifi list --rescan no 2>/dev/null | grep '^yes:' | head -1 | cut -d: -f2)
    if nmcli -t -f ACTIVE dev wifi list --rescan no 2>/dev/null | grep -q '^yes' && [ -z "$WIFI" ]; then WIFI="Open (none)"; fi
  fi

  if [ -e /etc/ssh/sshd_config ] && pgrep -x sshd >/dev/null 2>&1; then
    for k in /etc/ssh/ssh_host_*_key.pub; do
      [ -e "$k" ] || continue
      row pq-later "SSH server host key" "$(basename "$k") ($(cut -d' ' -f1 "$k"))" \
        "This computer accepts SSH connections. Its identity key could be forged by a future quantum computer; post-quantum host keys are not in general use yet." "Nothing yet."
    done
  fi
fi

# -------------------------------------------------------------- Browsers
browser() { # name version minimum policy_off
  M=$(major "$2")
  if [ "$4" = 1 ]; then
    row pq-exposed "Web browser" "$1 $2" "A policy on this computer switches the browser's post-quantum protection off." \
      "Remove the PostQuantumKeyAgreementEnabled policy, unless your IT provider set it for a specific reason."
  elif ge "$M" "$3"; then
    row pq-ready "Web browser" "$1 $2" "Uses post-quantum (hybrid ML-KEM) protection by default with websites that support it (version $3 and later)."
  else
    row pq-exposed "Web browser" "$1 $2" "Too old for post-quantum protection, and missing other security fixes." "Update the browser."
  fi
}
if [ "$OS" = Darwin ]; then
  for spec in "Google Chrome|131|com.google.Chrome" "Microsoft Edge|131|com.microsoft.Edge" "Firefox|132|org.mozilla.firefox"; do
    app=${spec%%|*}; rest=${spec#*|}; min=${rest%%|*}; dom=${rest#*|}
    for dir in /Applications "$HOME/Applications"; do
      plist="$dir/$app.app/Contents/Info"
      [ -e "$plist.plist" ] || continue
      v=$(defaults read "$plist" CFBundleShortVersionString 2>/dev/null)
      [ -n "$v" ] || break
      off=0
      [ "$(defaults read "/Library/Managed Preferences/$dom" PostQuantumKeyAgreementEnabled 2>/dev/null)" = 0 ] && off=1
      browser "$app" "$v" "$min" "$off"
      break
    done
  done
else
  for spec in "google-chrome|Google Chrome|131" "chromium|Chromium|131" "chromium-browser|Chromium|131" "microsoft-edge|Microsoft Edge|131" "firefox|Firefox|132"; do
    cmd=${spec%%|*}; rest=${spec#*|}; label=${rest%%|*}; min=${rest#*|}
    have "$cmd" || continue
    v=$("$cmd" --version 2>/dev/null | grep -o '[0-9][0-9.]*' | head -1)
    [ -n "$v" ] || continue
    off=0
    for pol in /etc/opt/chrome/policies/managed /etc/chromium/policies/managed /etc/opt/edge/policies/managed; do
      grep -qs '"PostQuantumKeyAgreementEnabled"[[:space:]]*:[[:space:]]*false' "$pol"/*.json 2>/dev/null && [ "$min" = 131 ] && off=1
    done
    browser "$label" "$v" "$min" "$off"
  done
fi

# ------------------------------------------------------------------ Wi-Fi
if [ -n "${WIFI:-}" ]; then
  case "$WIFI" in
    *WEP*|*TKIP*|Open*|None*|none*)
      row fix-now "Wi-Fi connection" "$WIFI" "This Wi-Fi network uses no encryption or a broken one." \
        "Set the router to WPA2 (AES) or WPA3, or avoid this network for work." ;;
    *) row ok "Wi-Fi connection" "$WIFI" "Wi-Fi encryption uses AES, which holds up. A weak Wi-Fi password is the usual risk, not the encryption." ;;
  esac
fi

# -------------------------------------------------------------------- SSH
if have ssh; then
  SV=$(ssh -V 2>&1 | head -1)
  if ssh -Q kex 2>/dev/null | grep -Eq 'mlkem|sntrup'; then
    row pq-ready "SSH (remote command line)" "$SV" "Offers post-quantum key exchange to servers that support it."
  else
    row pq-exposed "SSH (remote command line)" "$SV" "This SSH version has no post-quantum key exchange." "Update OpenSSH with your system updates."
  fi
fi
for k in "$HOME"/.ssh/*.pub; do
  [ -e "$k" ] || continue
  t=$(cut -d' ' -f1 "$k"); b=$(ssh-keygen -lf "$k" 2>/dev/null | awk '{print $1}')
  case "$t" in
    ssh-dss) row fix-now "SSH key" "$(basename "$k") (DSA)" "DSA keys are retired and refused by current servers." \
      "Make a new Ed25519 key and replace this one on the servers that use it." ;;
    ssh-rsa) if [ -n "$b" ] && [ "$b" -lt 2048 ] 2>/dev/null; then
        row fix-now "SSH key" "$(basename "$k") (RSA $b-bit)" "RSA keys under 2048 bits are weak today." "Make a new Ed25519 key and replace this one."
      else
        row pq-later "SSH key" "$(basename "$k") (RSA ${b:-?}-bit)" "A signature key a future quantum computer could forge. Post-quantum SSH keys are not in general use yet." "Nothing yet."
      fi ;;
    *) row pq-later "SSH key" "$(basename "$k") ($t)" "A signature key a future quantum computer could forge. Post-quantum SSH keys are not in general use yet." "Nothing yet." ;;
  esac
done

row info "Operating system" "$OSNAME" "The system this check ran on."

# ================================================================= Report
esc() { printf '%s' "$1" | sed -e 's/&/\&amp;/g' -e 's/</\&lt;/g' -e 's/>/\&gt;/g' -e "s/'/\&#39;/g" -e 's/"/\&quot;/g'; }
count() { grep -c "^$1$US" "$ROWS"; }
short() { case "$1" in fix-now) echo "Fix now";; pq-exposed) echo "Readable later";; pq-later) echo "Waits on vendors";; pq-ready) echo "Already post-quantum";; ok) echo "Holds up";; *) echo "Also checked";; esac; }
color() { case "$1" in fix-now) echo "var(--red)";; pq-exposed) echo "var(--amber)";; pq-ready) echo "var(--green)";; ok) echo "var(--teal)";; *) echo "var(--grey)";; esac; }
explain() { case "$1" in
  fix-now) echo "Weak against today's attackers, no quantum computer needed. Fix these first; they are usually the cheapest.";;
  pq-exposed) echo "Safe today, but set up without post-quantum protection. Someone who records this traffic now could decrypt it once a large quantum computer exists (NIST calls this \"harvest now, decrypt later\"). It matters most for information that must stay private for years.";;
  pq-later) echo "Keys and certificates that prove identity. The industry has not moved these to post-quantum yet, so there is nothing to buy or change today.";;
  pq-ready) echo "Already using post-quantum (hybrid ML-KEM) protection.";;
  ok) echo "Encryption that holds up against quantum computers.";;
  *) echo "Context for the results above.";;
esac; }

if [ -z "$OUT_DIR" ]; then
  if [ -d "$HOME/Desktop" ]; then OUT_DIR="$HOME/Desktop"; else OUT_DIR="$HOME"; fi
fi
SAFE=$(printf '%s' "$NAME" | tr -c 'A-Za-z0-9._-' '-')
FILE="$OUT_DIR/Post-Quantum-Check-$SAFE-$(date +%Y-%m-%d).html"
DATE=$(date '+%B %d, %Y' | sed 's/ 0/ /')
UTM="utm_source=pq-check&amp;utm_medium=report&amp;utm_campaign=post-quantum-check"

{
cat <<'EOF'
<!doctype html><html lang='en'><head><meta charset='utf-8'><meta name='viewport' content='width=device-width,initial-scale=1'>
<style>
:root{--navy:#10293d;--brass:#b87a2b;--ink:#1d2730;--muted:#5b6670;--line:#dfe3e6;--soft:#f4f6f7;--red:#a8322d;--amber:#a86a12;--grey:#5b6670;--green:#2f7a4a;--teal:#2a6f86}
*{box-sizing:border-box}body{margin:0;background:#fff;color:var(--ink);font:15px/1.55 system-ui,-apple-system,"Segoe UI",sans-serif}
.wrap{max-width:900px;margin:0 auto;padding:0 20px 48px}
header{background:var(--navy);color:#fff;padding:28px 0 24px;border-bottom:4px solid var(--brass)}header .wrap{padding-bottom:0}
.eyebrow{color:#e0b46e;letter-spacing:.12em;text-transform:uppercase;font-size:12px;font-weight:600}
h1{margin:6px 0 4px;font-size:30px;line-height:1.15}header p{margin:0;color:#c9d3db}
h2{font-size:20px;margin:34px 0 8px;color:var(--navy)}h3{margin:0 0 6px;font-size:17px;color:var(--navy)}
.tiles{display:grid;grid-template-columns:repeat(5,1fr);gap:10px;margin:22px 0 6px}
.tile{border:1px solid var(--line);border-top:4px solid var(--c);border-radius:6px;padding:12px 10px}
.tile b{display:block;font-size:28px;line-height:1;color:var(--c)}.tile span{font-size:12.5px;color:var(--muted)}
.sec{border-left:4px solid var(--c);padding:2px 0 0 14px;margin-top:30px}.sec>p{color:var(--muted);margin:2px 0 12px}
table{width:100%;border-collapse:collapse;font-size:14px}th,td{text-align:left;vertical-align:top;padding:8px;border-bottom:1px solid var(--line)}
th{font-size:12px;text-transform:uppercase;letter-spacing:.05em;color:var(--muted);background:var(--soft)}.tw{overflow-x:auto}
code{font-family:ui-monospace,Consolas,monospace;font-size:13px;word-break:break-word}
.box{background:var(--soft);border:1px solid var(--line);border-radius:6px;padding:16px 18px;margin-top:30px}
.box.cta{background:#fff;border:2px solid var(--brass)}.box ul{margin:6px 0 10px;padding-left:20px}
.btn{display:inline-block;background:var(--navy);color:#fff;text-decoration:none;padding:9px 16px;border-radius:5px;font-weight:600;margin:4px 8px 4px 0}
.btn.alt{background:#fff;color:var(--navy);border:1px solid var(--navy)}
.note{font-size:12.5px;color:var(--muted);margin-top:28px;border-top:1px solid var(--line);padding-top:12px}
@media (max-width:700px){.tiles{grid-template-columns:repeat(2,1fr)}h1{font-size:24px}}
@media print{header{-webkit-print-color-adjust:exact;print-color-adjust:exact}.sec{break-inside:avoid-page}}
</style>
EOF
printf "<title>Post-Quantum Check: %s</title></head><body>\n" "$(esc "$NAME")"
printf "<header><div class='wrap'><div class='eyebrow'>Bay Geeks &middot; Free Post-Quantum Check</div><h1>Post-Quantum Check: this computer</h1><p>%s &middot; %s &middot; checked %s</p></div></header><div class='wrap'>\n" "$(esc "$NAME")" "$(esc "$OSNAME")" "$(esc "$DATE")"
echo "<h2>What this is</h2><p>A list of the encryption this one computer uses, sorted by what it means for you: what is weak today, what is not yet protected against future quantum computers, what waits on vendors, and what is already upgraded. Each item says what to do.</p><div class='tiles'>"
for s in fix-now pq-exposed pq-later pq-ready ok; do
  printf "<div class='tile' style='--c:%s'><b>%s</b><span>%s</span></div>" "$(color $s)" "$(count $s)" "$(short $s)"
done
echo "</div>"
for s in fix-now pq-exposed pq-later pq-ready ok info; do
  n=$(count $s); [ "$n" -gt 0 ] || continue
  if [ $s = info ]; then title="Also checked"; else title="$(short $s) ($n)"; fi
  printf "<div class='sec' style='--c:%s'><h2 style='margin-top:0'>%s</h2><p>%s</p><div class='tw'><table><thead><tr><th>What</th><th>Found</th><th>Why it matters</th><th>What to do</th></tr></thead><tbody>\n" \
    "$(color $s)" "$title" "$(esc "$(explain $s)")"
  grep "^$s$US" "$ROWS" | while IFS="$US" read -r st what found why fix; do
    [ -n "$fix" ] || fix="Nothing."
    printf "<tr><td><b>%s</b></td><td><code>%s</code></td><td>%s</td><td>%s</td></tr>\n" "$(esc "$what")" "$(esc "$found")" "$(esc "$why")" "$(esc "$fix")"
  done
  echo "</tbody></table></div></div>"
done
cat <<EOF
<div class='box cta'><h3>This checked one computer. Your office is more than that.</h3>
<p style='margin:0'>It did not check the rest of the places your encryption lives:</p>
<ul><li>your firewall, router and VPN</li><li>your other computers and any server</li><li>Wi-Fi access points, network storage and printers</li><li>your website and your email</li></ul>
<p>Every paid <b>Bay Geeks Business Risk Assessment</b> includes the full Post-Quantum Cryptography report for all of those, alongside accounts, email, backups and the network: <b>\$495 flat for up to 10 computers</b>, credited toward a Bay Geeks maintenance plan if you start one within 30 days of the walkthrough.</p>
<a class='btn' href='https://baygeeks.com/business-risk-assessment/?$UTM'>About the assessment</a><a class='btn alt' href='https://baygeeks.com/post-quantum-cryptography/?$UTM'>Read the post-quantum guide</a>
<p style='margin:10px 0 0'>Questions about a result? Call Bay Geeks at <a href='tel:+17275794335'>727-579-4335</a>.</p></div>
<p class='note'>This check ran entirely on this computer. It read settings only, changed nothing, and sent nothing to Bay Geeks or anyone else. Results describe this computer on the date above. Background: NIST FIPS 203, 204 and 205 (August 2024); NIST IR 8547, Transition to Post-Quantum Cryptography Standards (October 2026); Apple, Prepare your network for quantum-secure encryption in TLS. Bay Geeks Post-Quantum Check for Mac and Linux, version $VERSION. Not a certification or a legal opinion.</p>
</div></body></html>
EOF
} > "$FILE"

SUM=""
for s in fix-now pq-exposed pq-later pq-ready ok; do SUM="$SUM$(short $s): $(count $s), "; done
echo "Done. ${SUM%, }"
echo "Report saved to: $FILE"
if [ "$NO_OPEN" = 0 ]; then
  if [ "$OS" = Darwin ]; then open "$FILE"
  elif have xdg-open; then xdg-open "$FILE" >/dev/null 2>&1 &
  fi
fi
