#!/usr/bin/env bash
# check-optimjack.sh: offline, read-only checker for the Optimizely Web Experimentation "OPTIMJACK" injection
# (16 Nov 2026). Pack 1.0.0 (17 Nov 2026). It never fetches anything, opens no sockets, writes no files and runs no
# other program except grep, sha256sum, wc, find, sort, tr and cut on the files you name. It never prints file content.
#
# Modes (combine freely):
#   --scan PATH        a snippet file you saved yourself, or a directory of them (searched recursively, links not
#                      followed, files over 10 MiB skipped). Repeatable.
#   --ios FILE         iOS or iPadOS inventory CSV, header exactly: device,os_version
#   --extra-hash HEX   an extra SHA-256 (64 hex characters) to treat as an indicator (OPERATOR). Repeatable.
#
# Exit codes (worst wins; precedence 5 > 1 > 3 > 2 > 4 > 0):
#   0 CLEAN              nothing found, every iOS row at or above the fixed versions
#   1 IOC FOUND          a NEWS IOC string or hash, an OPERATOR hash, or the base64 form of the payload domain
#   2 SUSPICIOUS         only search terms the sources advise checking, or OUR HEURISTIC loader patterns
#   3 IOS BELOW FIXED    at least one iOS or iPadOS device below 18.7.3 (18.x) or 26.3 (26.x), or older
#   4 UNKNOWN            a file skipped or unreadable, a folder with no files, or an iOS row that cannot be judged
#   5 USAGE OR READ ERROR
set -u
export LC_ALL=C

FIX_18="18.7.3"
FIX_26="26.3"
MAX_BYTES=10485760
# NEWS IOC strings (The Hacker News, 17 Nov 2026, indicator list; the domain also in BleepingComputer, 16 Nov 2026).
NEWS_IOCS="1688360 136.113.106.136 webshell.lol 5vobauua3ojpklx.icu eil786npto9u5bq.icu"
# NEWS IOC wallet addresses (BleepingComputer, 16 Nov 2026, wallet table).
NEWS_WALLETS="19g9rZcPeiz8rUvyWpTRyXXhPnjsWrc3kW ltc1q3wp7g6ds0ggg6fl6kncpa4sepn0q3qfacgred5 THvs6p56XkUiMkJeSc51cAP64u2RsTYqxa 0xC4026b06D82b0F0B363eda0642D61CfbDc17884e FVtL8NMYS9PA1v3HE67XUGCtGA9JaZUvqav2fU2LrV5n UQAgM1VqSZQiJLSG5w-ovurq5CZdxLEK3_7CMmwALTA5e09p qzkaaf8n6grmpr0d9lx8xutn3r9lk722f566hhpe58 DBEGrxRF7KMSuhTS4c1MFviStU6efdMnu5 2033556a49942224b486e70fa8beeaeae4265dc4b10adffec2326c002d30397b"
# NEWS IOC SHA-256 of track.js (The Hacker News: final and earliest captured versions; not exhaustive).
NEWS_HASHES="f7b84b9a94f749f8ced3f0112d0a66894e8bbc3b4aa5592021d1b8976a9bad40 617df364120adc47fb4f55dcc0c69a9b6c9e108a92c60bc2b64a266254ab02f3"
# OUR PATTERN: base64 of "1688360.cc" at each of the three byte offsets (the press reports a base64 loader variant).
B64_IOCS="MTY4ODM2MC5jY E2ODgzNjAuY2 xNjg4MzYwLmNj"
# Search terms the sources advise checking (common in legitimate code, so SUSPICIOUS only).
SEARCH_TERMS="atob( .icu track.js"
# OUR HEURISTIC loader patterns (extended regex, case-sensitive).
H1='atob\([[:space:]]*["'"'"'][A-Za-z0-9+/]{24,}={0,2}["'"'"'][[:space:]]*\)'
H2='(eval|Function)[[:space:]]*\([[:space:]]*atob\('
H3='\.src[[:space:]]*=[[:space:]]*atob\('
H4='createElement\([[:space:]]*["'"'"']script["'"'"'][[:space:]]*\)'

usage() {
  echo 'Usage: check-optimjack.sh [--scan PATH ...] [--ios FILE] [--extra-hash HEX ...], or Check-Optimjack.ps1 [-Scan PATH,...] [-Ios FILE] [-ExtraHash HEX,...]'
  echo 'Offline and read-only. Exit codes: 0 CLEAN, 1 IOC FOUND, 2 SUSPICIOUS, 3 IOS BELOW FIXED, 4 UNKNOWN, 5 USAGE OR READ ERROR.'
}
die() { echo "ERROR: $*"; exit 5; }
clean_path() { printf '%s' "$1" | tr -c '[:print:]' '?'; }
safe_name() { if [[ "$1" =~ ^[A-Za-z0-9._-]{1,64}$ ]]; then printf '%s' "$1"; else printf '(name withheld: unexpected characters)'; fi; }
trim() { local s=$1; s="${s#"${s%%[![:space:]]*}"}"; s="${s%"${s##*[![:space:]]}"}"; printf '%s' "$s"; }
rank() { case $1 in 1) echo 6;; 3) echo 5;; 2) echo 4;; 4) echo 3;; 0) echo 1;; *) echo 0;; esac; }
worse() { if [ "$(rank "$1")" -ge "$(rank "$2")" ]; then echo "$1"; else echo "$2"; fi; }

SCANS=(); IOS=""; EXTRA=()
while [ $# -gt 0 ]; do
  case $1 in
    --scan) [ $# -ge 2 ] || die "--scan needs a path"; SCANS+=("$2"); shift 2;;
    --ios) [ $# -ge 2 ] || die "--ios needs a file"; IOS=$2; shift 2;;
    --extra-hash) [ $# -ge 2 ] || die "--extra-hash needs a value"
      [[ "$2" =~ ^[0-9A-Fa-f]{64}$ ]] || die "extra hash must be 64 hex characters"
      EXTRA+=("$(printf '%s' "$2" | tr 'A-F' 'a-f')"); shift 2;;
    -h|--help) usage; exit 5;;
    *) die "unknown option: $(clean_path "$1")";;
  esac
done
[ ${#SCANS[@]} -gt 0 ] || [ -n "$IOS" ] || { usage; exit 5; }
for p in "${SCANS[@]}"; do [ -e "$p" ] || die "scan path not found: $(clean_path "$p")"; done
if [ -n "$IOS" ]; then { [ -f "$IOS" ] && [ -r "$IOS" ]; } || die "iOS CSV not readable: $(clean_path "$IOS")"; fi

# scan_file PATH: prints findings, returns 0, 1, 2 or 4.
scan_file() {
  local f=$1 shown n h ioc=0 sus=0 out="" k
  shown=$(clean_path "$f")
  if [ -L "$f" ] || [ ! -f "$f" ]; then echo "SCAN $shown: SKIPPED (not a regular file)"; return 4; fi
  if [ ! -r "$f" ]; then echo "SCAN $shown: SKIPPED (unreadable)"; return 4; fi
  n=$(wc -c < "$f" 2>/dev/null) || { echo "SCAN $shown: SKIPPED (unreadable)"; return 4; }
  if [ "$n" -gt "$MAX_BYTES" ]; then echo "SCAN $shown: SKIPPED (larger than 10 MiB)"; return 4; fi
  h=$(sha256sum -- "$f" 2>/dev/null | cut -d' ' -f1) || h=""
  [ -n "$h" ] || { echo "SCAN $shown: SKIPPED (unreadable)"; return 4; }
  for k in $NEWS_HASHES; do [ "$h" = "$k" ] && { out+="  [NEWS IOC SHA-256 $k of track.js (The Hacker News)] whole file"$'\n'; ioc=1; }; done
  for k in "${EXTRA[@]}"; do [ "$h" = "$k" ] && { out+="  [OPERATOR SHA-256 $k] whole file"$'\n'; ioc=1; }; done
  for k in $NEWS_IOCS; do n=$(grep -a -c -i -F -e "$k" -- "$f"); [ "$n" -gt 0 ] && { out+="  [NEWS IOC $k (The Hacker News)] $n line(s)"$'\n'; ioc=1; }; done
  for k in $NEWS_WALLETS; do n=$(grep -a -c -i -F -e "$k" -- "$f"); [ "$n" -gt 0 ] && { out+="  [NEWS IOC wallet $k (BleepingComputer)] $n line(s)"$'\n'; ioc=1; }; done
  for k in $B64_IOCS; do n=$(grep -a -c -F -e "$k" -- "$f"); [ "$n" -gt 0 ] && { out+="  [OUR PATTERN base64 of 1688360.cc: $k] $n line(s)"$'\n'; ioc=1; }; done
  for k in $SEARCH_TERMS; do n=$(grep -a -c -i -F -e "$k" -- "$f"); [ "$n" -gt 0 ] && { out+="  [SEARCH TERM $k (advised by the sources; also common in legitimate code)] $n line(s)"$'\n'; sus=1; }; done
  n=$(grep -a -c -E -e "$H1" -- "$f"); [ "$n" -gt 0 ] && { out+="  [OUR HEURISTIC H1 atob() of a long base64 literal] $n line(s)"$'\n'; sus=1; }
  n=$(grep -a -c -E -e "$H2" -- "$f"); [ "$n" -gt 0 ] && { out+="  [OUR HEURISTIC H2 eval or Function of atob()] $n line(s)"$'\n'; sus=1; }
  n=$(grep -a -c -E -e "$H3" -- "$f"); [ "$n" -gt 0 ] && { out+="  [OUR HEURISTIC H3 script src set from atob()] $n line(s)"$'\n'; sus=1; }
  if grep -a -q -E -e "$H4" -- "$f" && grep -a -q -F -e 'atob(' -- "$f"; then out+="  [OUR HEURISTIC H4 script element created in a file that also calls atob()] whole file"$'\n'; sus=1; fi
  if [ "$ioc" = 1 ]; then echo "SCAN $shown: IOC FOUND (sha256 $h)"; printf '%s' "$out"; return 1; fi
  if [ "$sus" = 1 ]; then echo "SCAN $shown: SUSPICIOUS (sha256 $h)"; printf '%s' "$out"; return 2; fi
  echo "SCAN $shown: CLEAN (sha256 $h)"; return 0
}

# ver_cmp A B: prints -1, 0 or 1 (three numeric parts, missing parts are 0).
ver_cmp() {
  local IFS=. i x y; local -a a b
  read -r -a a <<< "$1"; read -r -a b <<< "$2"
  for i in 0 1 2; do x=$((10#${a[i]:-0})); y=$((10#${b[i]:-0}))
    if [ "$x" -lt "$y" ]; then echo -1; return; fi
    if [ "$x" -gt "$y" ]; then echo 1; return; fi
  done; echo 0
}

# ios_row VERSION: prints verdict text, returns 0, 3 or 4.
ios_row() {
  local v=$1 maj note=""
  maj=$((10#${v%%.*}))
  if [ "$maj" -ge 13 ] && [ "$(ver_cmp "$v" 17.2.1)" -le 0 ]; then note=" In the reported Coruna range (iOS 13.0 to 17.2.1)."; fi
  if [ "$(ver_cmp "$v" 18.4)" -ge 0 ] && [ "$(ver_cmp "$v" 18.7)" -le 0 ]; then note=" In the reported DarkSword range (iOS 18.4 to 18.7)."; fi
  if [ "$maj" = 18 ] && [ "$(ver_cmp "$v" 18.7)" -lt 0 ]; then note+=" iOS 18.6 or earlier also got the Coruna iframe that reloads the page every 60 seconds (17:13 to 17:57 UTC, 16 Nov)."; fi
  if [ "$maj" -le 17 ]; then echo "below the fixed versions: no 17.x or older release is named as fixed; move to 18.7.3 or later, or 26.3 or later.$note"; return 3; fi
  if [ "$maj" = 18 ]; then
    if [ "$(ver_cmp "$v" "$FIX_18")" -lt 0 ]; then echo "below $FIX_18.$note"; return 3; fi
    echo "at or above $FIX_18."; return 0
  fi
  if [ "$maj" -ge 19 ] && [ "$maj" -le 25 ]; then echo "no such iOS release (Apple went from 18 to 26)."; return 4; fi
  if [ "$maj" = 26 ]; then
    if [ "$(ver_cmp "$v" "$FIX_26")" -lt 0 ]; then echo "below $FIX_26. For iOS 26 the press reports a chain that only collected device details."; return 3; fi
    echo "at or above $FIX_26."; return 0
  fi
  if [ "$maj" = 27 ]; then echo "iOS 27, later than both fixed versions. OUR ASSUMPTION [UNVERIFIED]: iOS 27 keeps those fixes."; return 0; fi
  echo "major version $maj is not a released iOS version (latest Apple release checked: iOS 27.2.1)."; return 4
}

check_ios() {
  local f=$1 line lnum=0 hdr_seen=0 dev ver rest commas rc=0 r below=0 ok=0 unk=0 rows=0 text shown
  while IFS= read -r line || [ -n "$line" ]; do
    lnum=$((lnum+1))
    line=${line%$'\r'}
    if [ "$hdr_seen" = 0 ]; then
      line=${line#$'\xef\xbb\xbf'}
      [ "$line" = "device,os_version" ] || die "iOS CSV header must be exactly: device,os_version"
      hdr_seen=1; continue
    fi
    [ -z "$(trim "$line")" ] && continue
    case $(trim "$line") in \#*) continue;; esac
    rows=$((rows+1))
    commas=${line//[!,]/}
    if [ "${#commas}" != 1 ]; then echo "IOS UNKNOWN: row $lnum: expected 2 fields"; unk=$((unk+1)); continue; fi
    dev=$(trim "${line%%,*}"); rest=${line#*,}; ver=$(trim "$rest")
    shown=$(safe_name "$dev")
    if [[ ! "$ver" =~ ^[0-9]{1,3}(\.[0-9]{1,3}){0,2}$ ]]; then echo "IOS UNKNOWN: row $lnum $shown: version not recognised"; unk=$((unk+1)); continue; fi
    text=$(ios_row "$ver"); r=$?
    case $r in
      0) echo "IOS AT OR ABOVE FIXED: row $lnum $shown $ver: $text"; ok=$((ok+1));;
      3) echo "IOS BELOW FIXED: row $lnum $shown $ver: $text Update it now."; below=$((below+1));;
      *) echo "IOS UNKNOWN: row $lnum $shown $ver: $text"; unk=$((unk+1));;
    esac
  done < "$f"
  [ "$hdr_seen" = 1 ] || die "iOS CSV header must be exactly: device,os_version"
  [ "$rows" -gt 0 ] || die "iOS CSV has no rows"
  echo "IOS: $rows row(s) read: $below below the fixed versions, $ok at or above, $unk unknown. Fixed versions: iOS $FIX_18 (18.x) and $FIX_26 (26.x), as reported from the exploit kit's own comments (The Hacker News); Apple released 18.7.3 on 12 Dec 2025 and 26.3 on 11 Feb 2026."
  if [ "$below" -gt 0 ]; then rc=3; elif [ "$unk" -gt 0 ]; then rc=4; else rc=0; fi
  return $rc
}

final=0; nfiles=0
for p in "${SCANS[@]}"; do
  if [ -d "$p" ] && [ ! -L "$p" ]; then
    root=$p; while [ "${#root}" -gt 1 ] && [ "${root%/}" != "$root" ]; do root=${root%/}; done
    found=0
    while IFS= read -r -d '' f; do
      found=1; nfiles=$((nfiles+1)); scan_file "$f"; final=$(worse "$final" $?)
    done < <(find "$root" -type f -print0 2>/dev/null | sort -z)
    if [ "$found" = 0 ]; then echo "SCAN $(clean_path "$root"): UNKNOWN (no regular files found)"; final=$(worse "$final" 4); fi
  else
    nfiles=$((nfiles+1)); scan_file "$p"; final=$(worse "$final" $?)
  fi
done
if [ -n "$IOS" ]; then check_ios "$IOS"; final=$(worse "$final" $?); fi
[ ${#SCANS[@]} -gt 0 ] && echo "SCANNED: $nfiles file(s). A clean result covers only the copies you saved: a snippet that is clean now may still have served the code on 16 Nov 2026."
case $final in
  0) echo "RESULT: CLEAN (exit 0)";; 1) echo "RESULT: IOC FOUND (exit 1)";; 2) echo "RESULT: SUSPICIOUS (exit 2)";;
  3) echo "RESULT: IOS BELOW FIXED (exit 3)";; 4) echo "RESULT: UNKNOWN (exit 4)";;
esac
exit "$final"
