cryptopals

Matasano's cryptopals challenges (cryptopals.com).
git clone git://git.jtobin.io/cryptopals.git
Log | Files | Refs | README | LICENSE

crackhmac.sh (1571B)


      1 #!/usr/bin/env bash
      2 
      3 fil=$1
      4 
      5 # use these if one needs to resume a broken loop
      6 lidx=$2  # byte idx to start at
      7 llas=$3  # time the last comparison took
      8 lgot=$4  # MAC we've guessed thus far
      9 
     10 if [[ -z "$fil" ]]; then
     11   echo "no file specified. bailing out.."
     12   exit 1
     13 fi
     14 
     15 if [[ -z "$lidx" ]]; then
     16   lidx=0
     17   llas=0.049
     18   lgot=""
     19 fi
     20 
     21 sup=$((39 - $lidx))
     22 sig="$lgot""$(printf '0%.0s' $(seq 0 $sup))"
     23 
     24 hos="localhost:3000"
     25 got="$lgot"
     26 
     27 attempt() {
     28   local res=$(curl -o /dev/null --silent -Iw "%{http_code}\n" "$1")
     29   echo "$res"
     30 }
     31 
     32 weld() {
     33   echo "$hos""/hmac?safe=false&file=""$fil""&signature=""$1"
     34 }
     35 
     36 las="$llas"
     37 
     38 for j in $(seq $lidx 2 38); do
     39   etc="${sig:$((j+2))}"
     40 
     41   echo "present MAC guess: $sig"
     42   echo "working on next byte (hexstring index $j).."
     43 
     44   for b in {0..255}; do
     45     byt=$(printf "%02x" $b)
     46 
     47     can="$got""$byt""$etc"
     48     url=$(weld $can)
     49 
     50     org=$(date +%s.%N)
     51     try=$(attempt $url)
     52     end=$(date +%s.%N)
     53 
     54     tim=$(echo "$end - $org" | bc -l)
     55     dif=$(echo "$tim - $las" | bc -l)
     56 
     57     if (($try == 500)); then
     58       lon=$(echo "$dif > 0.05" | bc -l)
     59       if (( $lon == 1 )); then
     60         got="$got""$byt"
     61         sig="$got""$etc"
     62         las=$tim
     63         echo "found byte $byt"
     64         break
     65       elif (($b == 255)); then
     66         echo "couldn't find byte value. bailing out.."
     67         echo "got: $got"
     68         echo "tim: $tim"
     69         exit 1
     70       fi
     71     elif (($try == 200)); then
     72       echo "succeeded"
     73       echo "file: $fil"
     74       echo "hmac: $sig"
     75       exit 0
     76     else
     77       echo "something really weird happened.."
     78     fi
     79   done
     80 done
     81