#!/usr/bin/env bash
# scan-tls.sh — probe TLS endpoints for quantum-relevant crypto using openssl.
# Reports negotiated protocol, cipher, certificate signature algorithm, key type,
# and (with OpenSSL 3.5+) whether a PQC/hybrid key-exchange group is offered.
#
# Usage:   ./scan-tls.sh host:port [host:port ...]
# Example: ./scan-tls.sh example.com:443 api.internal:8443
#
# Heuristic inventory aid for PQC readiness — part of the QianHeng PQC docs.
# https://qusecurelabs.com/pqc-docs/discovery.html
set -u
command -v openssl >/dev/null || { echo "openssl not found"; exit 1; }
OSSL_VER=$(openssl version 2>/dev/null)
echo "# scan-tls.sh  (using: $OSSL_VER)"
echo

for ep in "$@"; do
  host="${ep%%:*}"; port="${ep##*:}"; [ "$host" = "$port" ] && port=443
  echo "== $host:$port =="
  out=$(echo | openssl s_client -connect "$host:$port" -servername "$host" -brief 2>&1)
  proto=$(printf '%s\n' "$out" | grep -iE 'Protocol version|Protocol *:' | head -1 | sed 's/^ *//')
  cipher=$(printf '%s\n' "$out" | grep -iE 'Ciphersuite|Cipher *:' | head -1 | sed 's/^ *//')
  group=$(printf '%s\n' "$out" | grep -iE 'Negotiated .*group|Server Temp Key|group:' | head -1 | sed 's/^ *//')
  # certificate signature + key
  cert=$(echo | openssl s_client -connect "$host:$port" -servername "$host" 2>/dev/null \
         | openssl x509 -noout -text 2>/dev/null)
  sigalg=$(printf '%s\n' "$cert" | grep -i 'Signature Algorithm' | head -1 | sed 's/^ *//')
  keyinfo=$(printf '%s\n' "$cert" | grep -iE 'Public Key Algorithm|Public-Key:' | head -2 | sed 's/^ *//' | tr '\n' ' ')
  printf '  %s\n  %s\n  %s\n  %s\n  Key: %s\n' "$proto" "$cipher" "${group:-Group: n/a}" "${sigalg:-Signature: n/a}" "${keyinfo:-n/a}"

  # quantum-risk flag
  flag="HIGH (classical key exchange — Shor-vulnerable)"
  echo "$group $cipher" | grep -qiE 'mlkem|kyber|x25519mlkem|pqc' && flag="LOW (PQC/hybrid key exchange detected)"
  echo "$sigalg" | grep -qiE 'mldsa|ml-dsa|dilithium|sphincs|slh-dsa' && flag="$flag; PQC signature"
  echo "  >> quantum risk: $flag"
  echo
done

echo "# Note: heuristic. 'HIGH' just means a classical (RSA/ECDHE) handshake was negotiated —"
echo "# enabling a hybrid group like X25519MLKEM768 on both ends moves it toward quantum-safe."
