# tor_qemu.sh
# 2020-01-27
# This script securifies anonymity and privacy.
# QEMU (http://qemu.org/) is used for virtualization.
# All outgoing traffic is forwarded through TOR (https://www.torproject.org/).
# TOR has to be running on host OS on port 9050.
# https://www.torproject.org/
# Any changes to the disk image will not be written.
# You can commit changes using QEMU console: "commit all"
# Settings for Mozilla Firefox on guest OS:
# about:config
# network.proxy.socks =
# network.proxy.socks_port = 9050
# network.proxy.socks_remote_dns = true
# network.proxy.type = 1
# The following option requires Samba 3 (QEMU 1.6.1)
# -net user,smb=/home/user/shared

set -e

GID_KVM=$(grep kvm /etc/group | cut -d: -f3)

if [ "$SNAPSHOT" = "OFF" ]; then


# For WinXP:
#QEMU_OPTS="-machine accel=kvm -m 1024 -display sdl,gl=on -vga std -soundhw es1370 -net nic,model=ne2k_pci -net user,smb=/home/$USER/shared $2"

# For Win7:
QEMU_OPTS="-machine accel=kvm -m 1024 -display sdl,gl=on -vga std -soundhw ac97 -net nic,model=rtl8139 -net user,smb=/home/$USER/shared $2"

if [ ! -f "$QEMU_IMG" ]; then
  exit 1;

sudo -v

sudo /sbin/modprobe kvm
sudo /sbin/modprobe kvm_intel

sudo /usr/sbin/iptables -A OUTPUT -o lo -j ACCEPT
sudo /usr/sbin/iptables -t nat -A OUTPUT -o lo -m owner --gid-owner $GID_KVM \
  -p udp --dport 53 -j DNAT --to-destination
sudo /usr/sbin/iptables -A OUTPUT -m owner --gid-owner $GID_KVM -j DROP

# Check /etc/gshadow if a group password is set
sg kvm -c "qemu-system-x86_64 $QEMU_OPTS $SNAPSHOT \"$QEMU_IMG\""

sudo -v

sudo /usr/sbin/iptables -D OUTPUT -m owner --gid-owner $GID_KVM -j DROP
sudo /usr/sbin/iptables -t nat -D OUTPUT -o lo -m owner --gid-owner $GID_KVM \
  -p udp --dport 53 -j DNAT --to-destination
sudo /usr/sbin/iptables -D OUTPUT -o lo -j ACCEPT

sudo -k