{ config, lib, pkgs, ... }: { systemd.services.vps-init = { path = [ pkgs.openssh ]; serviceConfig.Type = "oneshot"; script = '' cd /secrets/awg date +%s > start-time . vps-init.env scp -i /root/.ssh/vps 0.conf $SSHCONN: until cat <<'EOF' | ssh -i /root/.ssh/vps $SSHCONN set -e if [ ! -e ~/vps-init-state ]; then echo 0 > ~/vps-init-state fi case "$(cat ~/vps-init-state)" in 0) cd /etc/ssh FILENAME="$(mktemp)" (echo PasswordAuthentication no; cat sshd_config) > "$FILENAME" mv "$FILENAME" sshd_config fallocate -l 1GiB /var/swapfile chmod 600 /var/swapfile mkswap /var/swapfile echo "/var/swapfile none swap defaults 0 0" >> /etc/fstab export DEBIAN_FRONTEND=noninteractive apt-get update apt-get dist-upgrade -y -o Dpkg::Options::="--force-confold";; 1) cat <<' EOF' >> /etc/sysctl.conf net.ipv6.conf.all.forwarding = 1 net.ipv4.ip_forward = 1 net.ipv4.conf.all.forwarding = 1 EOF for v in 6 ""; do ip''${v}tables -P FORWARD DROP ip''${v}tables -A FORWARD -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT ip''${v}tables -A FORWARD -i awg0 -j ACCEPT ip''${v}tables -t nat -A POSTROUTING -o eth0 -j MASQUERADE done for val in dest6=fc00::2 dest4=10.0.0.2 proto=tcp 25 80 443 32831:22 proto=udp 443; do if [[ "$val" == *=* ]]; then eval "$val" if [[ "$val" == dest6=* ]]; then ip6tables -t nat -A POSTROUTING -s $dest6 -d $dest6 -j MASQUERADE elif [[ "$val" == dest4=* ]]; then iptables -t nat -A POSTROUTING -s $dest4 -d $dest4 -j MASQUERADE fi continue fi if [[ "$val" == *:* ]]; then lport=''${val%:*} rport=''${val#*:} else lport=$val rport=$val fi ip6tables -t nat -A PREROUTING -m addrtype --dst-type LOCAL -p $proto --dport $lport -j DNAT --to-destination [$dest6]:$rport ip6tables -A FORWARD -d $dest6 -p $proto --dport $rport -j ACCEPT iptables -t nat -A PREROUTING -m addrtype --dst-type LOCAL -p $proto --dport $lport -j DNAT --to-destination $dest4:$rport iptables -A FORWARD -d $dest4 -p $proto --dport $rport -j ACCEPT done export DEBIAN_FRONTEND=noninteractive add-apt-repository -y ppa:amnezia/ppa apt-get install -y gnupg2 amneziawg amneziawg-tools iptables-persistent python3-launchpadlib linux-headers-$(uname -r) software-properties-common mv ~/0.conf /etc/amnezia/amneziawg/awg0.conf systemctl enable awg-quick@awg0 apt-get autoremove --purge -y apt-get clean;; 2) exit;; esac echo "$((1+$(cat ~/vps-init-state)))" > ~/vps-init-state reboot exit 1 EOF do sleep 1; done echo Installed in $(($(date +%s)-$(cat start-time)))s rm start-time ''; }; }