zarya/templates/vps-bootstrap.sh

87 lines
2.7 KiB
Bash
Executable file

#!/bin/bash
set -euo pipefail
USER_NAME="${BOOTSTRAP_USER:-atlas}"
PORT="${BOOTSTRAP_PORT:-1488}"
TCP_PORTS="${BOOTSTRAP_TCP_PORTS:-1488 80 443}"
UDP_PORTS="${BOOTSTRAP_UDP_PORTS:-51820}"
UFW_IN="${BOOTSTRAP_UFW_IN:-deny}"
UFW_OUT="${BOOTSTRAP_UFW_OUT:-allow}"
UFW_FWD="${BOOTSTRAP_UFW_FWD:-deny}"
UFW_APP="${BOOTSTRAP_UFW_APP:-skip}"
ENABLE_BBR="${BOOTSTRAP_ENABLE_BBR:-true}"
DISABLE_IPV6="${BOOTSTRAP_DISABLE_IPV6:-true}"
DISABLE_ICMP="${BOOTSTRAP_DISABLE_ICMP:-false}"
id -u "${USER_NAME}" &>/dev/null || useradd -m -s /bin/bash -G sudo "${USER_NAME}"
usermod -p '*' "${USER_NAME}"
mkdir -p "/home/${USER_NAME}/.ssh"
echo "${BOOTSTRAP_PUBKEY_B64}" | base64 -d > "/home/${USER_NAME}/.ssh/authorized_keys"
chmod 700 "/home/${USER_NAME}"
chmod 700 "/home/${USER_NAME}/.ssh"
chmod 600 "/home/${USER_NAME}/.ssh/authorized_keys"
chown -R "${USER_NAME}:${USER_NAME}" "/home/${USER_NAME}/.ssh"
echo "${USER_NAME} ALL=(ALL) NOPASSWD:ALL" > "/etc/sudoers.d/${USER_NAME}"
chmod 440 "/etc/sudoers.d/${USER_NAME}"
if systemctl is-active --quiet ssh.socket 2>/dev/null; then
systemctl disable --now ssh.socket
fi
rm -rf /etc/ssh/sshd_config.d/*.conf
cat << SSHEOF > /etc/ssh/sshd_config
Port ${PORT}
PasswordAuthentication no
KbdInteractiveAuthentication no
PermitRootLogin prohibit-password
PubkeyAuthentication yes
AuthorizedKeysFile .ssh/authorized_keys
UsePAM yes
X11Forwarding no
AcceptEnv LANG LC_*
Subsystem sftp /usr/lib/openssh/sftp-server
SSHEOF
systemctl daemon-reload
systemctl enable --now ssh.service
systemctl restart ssh.service
which ufw >/dev/null 2>&1 || (DEBIAN_FRONTEND=noninteractive apt-get update -y && DEBIAN_FRONTEND=noninteractive apt-get install -y ufw)
ufw --force reset
ufw default ${UFW_IN} incoming
ufw default ${UFW_OUT} outgoing
ufw default ${UFW_FWD} forward
sed -i -E 's/^DEFAULT_APPLICATION_POLICY=.*/DEFAULT_APPLICATION_POLICY="'${UFW_APP}'"/' /etc/default/ufw || true
if [[ "${DISABLE_IPV6}" == "true" ]]; then
sed -i -E 's/^IPV6=.*/IPV6=no/' /etc/default/ufw || true
fi
for p in ${TCP_PORTS}; do
ufw allow "${p}/tcp"
done
for p in ${UDP_PORTS}; do
ufw allow "${p}/udp"
done
ufw --force enable
rm -f /etc/sysctl.d/99-atlas.conf
touch /etc/sysctl.d/99-atlas.conf
if [[ "${ENABLE_BBR}" == "true" ]]; then
printf "net.core.default_qdisc = fq\nnet.ipv4.tcp_congestion_control = bbr\n" >> /etc/sysctl.d/99-atlas.conf
fi
if [[ "${DISABLE_IPV6}" == "true" ]]; then
printf "net.ipv6.conf.all.disable_ipv6 = 1\nnet.ipv6.conf.default.disable_ipv6 = 1\nnet.ipv6.conf.lo.disable_ipv6 = 1\n" >> /etc/sysctl.d/99-atlas.conf
fi
if [[ "${DISABLE_ICMP}" == "true" ]]; then
printf "net.ipv4.icmp_echo_ignore_all = 1\n" >> /etc/sysctl.d/99-atlas.conf
fi
sysctl --system >/dev/null 2>&1 || true