#!/bin/bash
#
# verify-mirror.sh - Verifies that our source mirror matches Internet sources
#
# Run this script on a non-torproject.org machine to verify that
# people.torproject.org was not subject to targeted MITM attacks on
# unauthenticated source code.
#
# Usage:
# ./verify-mirror.sh [<dir>]
#
# Verifies the integrity of a remote mirror against a local cache in
# "sources/", or from the Internet.
# 
# If <dir> is specified, change into that directory before performing
# verification.

. ./versions.sh

# Always update our local cache before verifying remote mirror
./fetch-thirdparty.sh $1

if [ -d $1 ]; then
  cd $1
fi

MIRROR_URL=https://people.torproject.org/~mikeperry/mirrors/sources/

# Let's make a verification directory
mkdir verify-sources
cd verify-sources

# Get package files from mirror
for i in ZLIB OPENSSL LIBPNG QT VIDALIA LIBEVENT TOR TOR_ALPHA FIREFOX MOZBUILD TORBUTTON HTTPSE HTTPSE_DEV OBFSPROXY
do
  PACKAGE=${i}"_PACKAGE"
  URL=${MIRROR_URL}${!PACKAGE}
  rm -f ${!PACKAGE}
  wget ${URL} >& /dev/null
  if [ $? -ne 0 ]; then
    echo "$i url ${URL} is broken!"
    exit 1
  fi
done

# Get+verify sigs that exist
# XXX: This doesn't cover everything. See #8525
for i in TORBUTTON FIREFOX LIBEVENT TOR TOR_ALPHA VIDALIA OBFSPROXY OPENSSL
do
  PACKAGE=${i}"_PACKAGE"
  URL=${MIRROR_URL}${!PACKAGE}
  if [ ! -f ${!PACKAGE}".asc" ]; then
    wget ${URL}".asc" >& /dev/null
    if [ $? -ne 0 ]; then
      echo "$i GPG sig url ${URL} is broken!"
      mv ${!PACKAGE} ${!PACKAGE}".nogpg"
      exit 1
    fi
  fi
  gpg ${!PACKAGE}".asc" >& /dev/null
  if [ $? -ne 0 ]; then
    echo "$i GPG signature is broken for ${URL}"
    mv ${!PACKAGE} ${!PACKAGE}".badgpg"
    exit 1
  fi
done

# Check remote sha256sums
rm -f sha256sums.txt
wget $MIRROR_URL"/sha256sums.txt" >& /dev/null
if [ $? -ne 0 ]; then
  echo "SHA256SUMS are absent!!"
  exit 1
fi

sha256sum --quiet -c sha256sums.txt
if [ $? -ne 0 ]; then
  echo "Remote sha256sums don't match data!"
  exit 1
fi

# Make sure our mirror matches
REMOTE_METASUM=`sha256sum sha256sums.txt`

cd ../sources/
LOCAL_METASUM=`sha256sum sha256sums.txt`

if [ "z$REMOTE_METASUM" != "z$LOCAL_METASUM" ]; then
  echo "Remote sha256sums don't match local values!"
  exit 1
fi

cd ..
rm -rf ./verify-sources/

exit 0

