# Hash file generator for WordPress Exploit Scanner
# Author: @ffflorian

#!/usr/bin/env sh

TOOLS="md5sum wget unzip sed"
LATEST="https://wordpress.org/latest.zip"
FILE="latest.zip"

for TOOL in $TOOLS; do
    if ! command -v $TOOL > /dev/null; then
        echo "$TOOL not found. Can't continue."
        exit 1
    fi
done

read_zip() {
    WORK_DIR=$(mktemp -d)
    VERSION_FILE="$WORK_DIR/wordpress/wp-includes/version.php"
    echo "Extracting and hashing files ..."
    unzip -q $FILE -d $WORK_DIR
    if (grep $VERSION_FILE -e "\$wp_version = '" -q); then
        VERSION=$(sed -n "s/.*\$wp_version = '\([^\']*\)';/\1/p" "$VERSION_FILE")
    else
        echo "Could not read WordPress version."
        read -r -p "Please enter the version number: " VERSION
    fi
    OUTPUT_FILE="$(pwd)/hashes-$VERSION.php"
    printf "<?php\n\$filehashes = array(\n" > "$OUTPUT_FILE"
    find $WORK_DIR \
        -type f \
        -not -path "*wp-content/plugins/*" \
        -not -path "*wp-content/themes/*" \
        -exec md5sum {} \; | \
        sed -rn "s#([a-f0-9]{32}) +$WORK_DIR/wordpress/(.*)#'\2' => '\1',#p" >> "$OUTPUT_FILE"
    printf ");" >> "$OUTPUT_FILE"
    rm -rf $WORK_DIR
    echo "All done!"
}

download_latest() {
    read -r -p "Download $FILE from the WordPress servers? [Y/n] " RESPONSE
    case $RESPONSE in
        [nN][oO]|[nN] )
            echo "No checksums generated."
            exit 1
        ;;
    esac

    echo "Downloading $FILE ..."
    rm -f "$FILE"
    wget "$LATEST"
    check_file
}

check_file() {
    echo "Checking hashsum for $FILE ..."
    if [ -r "$FILE" ]; then
        FILE_MD5=($(md5sum $FILE))
        LATEST_MD5=$(wget -qO- "$LATEST.md5")
        if md5sum -c <<<"$LATEST_MD5 $FILE" --quiet; then
            read_zip
        else
            echo "$FILE doesn't match the official WordPress hashsum ($FILE_MD5 != $LATEST_MD5)."
            download_latest
        fi
    else
        echo "$FILE not found."
        download_latest
    fi
}

check_file

exit
