#!/bin/bash

# Fugly, poor-mans wepattack distributor

NODEDIR="wepnodes/";
ATTACKBIN="./wepattack";
JOHNBIN="./john-1.6.36/run/john";
NWORDSPER="20000";
KEYLOGFILE="./cracked.keys";
WORDLIST="./big-dict";

DUMPFILE=$1;

function NodeMonkey() {
    if [ $# -lt 4 ]; then
        echo "Badly formed node entry: $*";
        return 1;
    fi

    contf=$1;
    shift;
    twords=$1;
    shift;

    if [ -f "$contf.lock" ]; then
        return 1;
    fi

    touch $contf.lock;

    let bwords=$twords-$NWORDSPER;
    echo "NODEMONKEY: Locked node $1, processing words $bwords-$twords.";
    
# do we have to put the binary and the dumps on?
    FILES="";
    if [ "`ssh -i $3 $2@$1 \"if [ -x $ATTACKBIN -a -f $DUMPFILE ]; then echo 1; else echo 0; fi;\"`" != "1" ]; then
#echo "NODEMONKEY: Have to copy files to node...";
        FILES="$ATTACKBIN $DUMPFILE";
    fi
    scp -i $3 $FILES wordlist.chunk $2@$1: >/dev/null 2>/dev/null

    ssh -i $3 $2@$1 nice $ATTACKBIN -w wordlist.chunk -f $DUMPFILE 2>/dev/null | grep "WepKey" >> $KEYLOGFILE

    echo "NODEMONKEY: Node $1 finished chunk, unlocking."
    rm $contf.lock;
};

function JohnTheDispatcher() {
    wordline="x";
    read wordline;
    let nword=0;
    let totalword=0;
    rm wordlist.build;
    while [ "$wordline" != "" ]; do
# Chunk it into files and find a node to send it to
        echo $wordline >> wordlist.build;
        let nword=$nword+1;
        let totalword=$totalword+1;
# If we have enough words, wait until a node is free.
        if [ "$nword" -ge "$NWORDSPER" ]; then
            echo "JohnTheDispatcher: Finished populating chunk list, waiting to dispatch."
            while [ 1 ]; do
                matched=0;
                for nf in `ls $NODEDIR/node-* | grep -v lock`; do
                    if [ ! -f "${nf}.lock" ]; then
                        matched=1;
                        mv wordlist.build wordlist.chunk
                        NodeMonkey ${nf} ${totalword} `cat ${nf}` &
                        break;
                    fi
                done

                if [ "$matched" == "1" ]; then
                    break;
                fi
                sleep 1;
            done;

            let nword=0
        fi
        read wordline;
    done;
}

echo "Generating wordlist and sending it to the dispatcher in $NWORDSPER chunks."
$JOHNBIN -wordlist=$WORDLIST -rules -stdout:13 | JohnTheDispatcher

