selfprivacy-nixos-infect/nixos-infect

364 lines
10 KiB
Plaintext
Raw Normal View History

2020-12-07 09:09:48 +00:00
#! /usr/bin/env bash
2023-11-18 02:47:34 +00:00
# More info at:
# - https://github.com/elitak/nixos-infect
# - https://git.selfprivacy.org/SelfPrivacy/selfprivacy-nixos-infect
: "${API_TOKEN:?API_TOKEN variable is not set}"
: "${DOMAIN:?DOMAIN variable is not set}"
: "${LUSER:?LUSER variable is not set}"
: "${HOSTNAME:?HOSTNAME variable is not set}"
: "${PROVIDER:?PROVIDER variable is not set}"
: "${DNS_PROVIDER_TYPE:?DNS_PROVIDER_TYPE variable is not set}"
: "${STAGING_ACME:?STAGING_ACME variable is not set}"
: "${CF_TOKEN:?CF_TOKEN variable is not set}"
: "${DB_PASSWORD:?DB_PASSWORD variable is not set}"
: "${ENCODED_PASSWORD:?ENCODED_PASSWORD variable is not set}"
: "${NIX_VERSION:?NIX_VERSION variable is not set}"
: "${NIXOS_CONFIG_NAME:?NIXOS_CONFIG_NAME variable is not set}"
: "${SUDO_USER:?SUDO_USER variable is not set}"
: "${CONFIG_URL:?CONFIG_URL variable is not set}"
readonly LOCAL_FLAKE_DIR="/etc/nixos"
readonly SECRETS_FILEPATH="/etc/selfprivacy/secrets.json"
# Merge original userdata.json with deployment specific fields and print result.
genUserdata() {
local password HASHED_PASSWORD userdata_infect
password=$(printf "%s" "$ENCODED_PASSWORD" | base64 --decode)
HASHED_PASSWORD=$(mkpasswd -m sha-512 "$password")
userdata_infect=$(cat << EOF
{
"dns": {
"provider": "$DNS_PROVIDER_TYPE",
"useStagingACME": "$STAGING_ACME"
},
"server": {
"provider": "$PROVIDER"
},
"domain": "DOMAIN",
"hashedMasterPassword": "$HASHED_PASSWORD",
"hostname": "HOSTNAME",
"username": "$LADMIN"
}
EOF
)
2022-11-16 08:06:15 +00:00
2023-11-18 02:47:34 +00:00
jq -s '.[0] * .[1]' \
"${1:?no userdata.json given to merge with}" <(printf "%s" "$userdata_infect")
}
2020-12-21 13:18:22 +00:00
2023-11-18 02:47:34 +00:00
genSecrets() {
local ESCAPED_PASSWORD
ESCAPED_PASSWORD=$(printf "%s" "$ENCODED_PASSWORD" | base64 --decode | jq -Rs .)
2020-12-07 09:09:48 +00:00
2023-11-18 02:47:34 +00:00
cat << EOF
2021-11-18 17:24:49 +00:00
{
"api": {
"token": "$API_TOKEN",
"skippedMigrations": ["migrate_to_selfprivacy_channel", "mount_volume"]
2021-11-18 17:24:49 +00:00
},
"databasePassword": "$DB_PASSWORD",
2023-11-18 02:47:34 +00:00
"dns": {
"apiKey": "$CF_TOKEN"
2021-11-18 17:24:49 +00:00
},
2023-11-18 02:47:34 +00:00
"modules": {
"nextcloud": {
"adminPassword": $ESCAPED_PASSWORD,
"databasePassword": $ESCAPED_PASSWORD,
}
2021-11-18 17:24:49 +00:00
},
2023-11-18 02:47:34 +00:00
"resticPassword": $ESCAPED_PASSWORD
2021-11-18 17:24:49 +00:00
}
EOF
2023-11-18 02:47:34 +00:00
}
2020-12-07 09:09:48 +00:00
2023-11-18 02:47:34 +00:00
genHardwareConfiguration() {
local bootcfg
if ((isEFI)); then
2021-11-16 07:00:26 +00:00
bootcfg=$(cat << EOF
boot.loader.grub = {
efiSupport = true;
efiInstallAsRemovable = true;
device = "nodev";
2020-12-23 15:52:14 +00:00
};
2023-11-18 02:47:34 +00:00
fileSystems."/boot" = { device = "$ESP"; fsType = "vfat"; };
2020-12-07 09:09:48 +00:00
EOF
2021-11-16 07:00:26 +00:00
)
else
bootcfg=$(cat << EOF
2023-11-18 02:47:34 +00:00
boot.loader.grub.device = "$GRUBDEV";
2021-02-10 09:43:06 +00:00
EOF
2021-11-16 07:00:26 +00:00
)
fi
2021-02-10 09:43:06 +00:00
2023-11-18 02:47:34 +00:00
cat << EOF
2021-11-16 07:00:26 +00:00
{ modulesPath, ... }:
2021-02-10 09:43:06 +00:00
{
2021-11-16 07:00:26 +00:00
imports = [ (modulesPath + "/profiles/qemu-guest.nix") ];
$bootcfg
boot.initrd.kernelModules = [ "nvme" ];
2023-11-18 02:47:34 +00:00
fileSystems."/" = { device = "$ROOTFSDEV"; fsType = "$ROOTFSTYPE"; };
2021-04-09 13:46:32 +00:00
}
2020-12-07 09:09:48 +00:00
EOF
}
2023-11-18 02:47:34 +00:00
setupConf() {
mkdir -p ${LOCAL_FLAKE_DIR}
if ! curl "${CONFIG_URL}" | tar -xz -C ${LOCAL_FLAKE_DIR} --strip-components=1
then
echo "Error downloading/extracting top level flake configuration!"
exit 1
2020-12-07 09:09:48 +00:00
fi
2023-11-18 02:47:34 +00:00
# generate and write hardware-configuration.nix
genHardwareConfiguration > ${LOCAL_FLAKE_DIR}/hardware-configuration.nix
2020-12-07 09:09:48 +00:00
2023-11-18 02:47:34 +00:00
# generate infected userdata based on original
local userdataInfected
userdataInfected="$(genUserdata ${LOCAL_FLAKE_DIR}/userdata.json)"
printf "%s" "$userdataInfected" > ${LOCAL_FLAKE_DIR}/userdata.json
# generate and write secrets
local secrets
secrets="$(genSecrets)"
install -m0600 <(printf "%s" "$secrets") -DT ${SECRETS_FILEPATH}
2020-12-07 09:09:48 +00:00
}
makeSwap() {
# TODO check currently available swapspace first
swapFile=$(mktemp /tmp/nixos-infect.XXXXX.swp)
dd if=/dev/zero "of=$swapFile" bs=1M count=$((1*1024))
chmod 0600 "$swapFile"
mkswap "$swapFile"
swapon -v "$swapFile"
}
removeSwap() {
swapoff -a
rm -vf /tmp/nixos-infect.*.swp
}
2021-11-16 07:00:26 +00:00
findESP() {
2023-11-18 02:47:34 +00:00
local esp
2021-11-16 07:00:26 +00:00
for d in /boot/EFI /boot/efi /boot; do
[[ ! -d "$d" ]] && continue
[[ "$d" == "$(df "$d" --output=target | sed 1d)" ]] \
&& esp="$(df "$d" --output=source | sed 1d)" \
&& break
done
[[ -z "$esp" ]] && { echo "ERROR: No ESP mount point found"; return 1; }
for uuid in /dev/disk/by-uuid/*; do
2023-11-18 02:47:34 +00:00
[[ $(readlink -f "$uuid") == "$esp" ]] && echo "$uuid" && return 0
2021-11-16 07:00:26 +00:00
done
}
2020-12-07 09:09:48 +00:00
prepareEnv() {
2023-11-18 02:47:34 +00:00
isEFI=0
[ -d /sys/firmware/efi ] || isEFI=1
if ((isEFI)); then
ESP="$(findESP)"
2021-11-16 07:00:26 +00:00
else
2023-11-18 02:47:34 +00:00
for GRUBDEV in /dev/vda /dev/sda /dev/nvme0n1; do
[[ -e $GRUBDEV ]] && break;
done
2021-11-16 07:00:26 +00:00
fi
2020-12-07 09:09:48 +00:00
# Retrieve root fs block device
# (get root mount) (get partition or logical volume)
2023-11-18 02:47:34 +00:00
ROOTFSDEV=$(mount | grep "on / type" | awk '{print $1;}')
ROOTFSTYPE=$(df "$ROOTFSDEV" --output=fstype | sed 1d)
2020-12-07 09:09:48 +00:00
# DigitalOcean doesn't seem to set USER while running user data
export USER="root"
export HOME="/root"
# Nix installer tries to use sudo regardless of whether we're already uid 0
#which sudo || { sudo() { eval "$@"; }; export -f sudo; }
# shellcheck disable=SC2174
mkdir -p -m 0755 /nix
}
fakeCurlUsingWget() {
# Use adapted wget if curl is missing
which wget && { \
curl() {
eval "wget $(
(local isStdout=1
for arg in "$@"; do
case "$arg" in
"-o")
echo "-O";
isStdout=0
;;
"-O")
isStdout=0
;;
"-L")
;;
*)
echo "$arg"
;;
esac
done;
[[ $isStdout -eq 1 ]] && echo "-O-"
)| tr '\n' ' '
)"
}; export -f curl; }
}
req() {
type "$1" > /dev/null 2>&1 || which "$1" > /dev/null 2>&1
}
checkEnv() {
2021-11-16 07:00:26 +00:00
[[ "$(whoami)" == "root" ]] || { echo "ERROR: Must run as root"; return 1; }
2020-12-07 09:09:48 +00:00
# Perform some easy fixups before checking
# TODO prevent multiple calls to apt-get update
2021-11-16 07:00:26 +00:00
(which dnf && dnf install -y perl-Digest-SHA) || true # Fedora 24
2020-12-07 09:09:48 +00:00
which xzcat || (which yum && yum install -y xz-utils) \
|| (which apt-get && apt-get update && apt-get install -y xz-utils) \
|| true
which curl || fakeCurlUsingWget \
|| (which apt-get && apt-get update && apt-get install -y curl) \
|| true
2021-11-16 07:00:26 +00:00
req curl || req wget || { echo "ERROR: Missing both curl and wget"; return 1; }
req xzcat || { echo "ERROR: Missing xzcat"; return 1; }
req awk || { echo "ERROR: Missing awk"; return 1; }
req cut || req df || { echo "ERROR: Missing coreutils (cut, df)"; return 1; }
2020-12-07 09:09:48 +00:00
}
2023-11-18 02:47:34 +00:00
# Download and execute the nix installer script.
installNix() {
local nixReleaseBase='https://releases.nixos.org'
local installURL="${nixReleaseBase}/nix/nix-${NIX_VERSION}/install"
local shaURL="${installURL}.sha256"
local sha tmpNixInstall
# temporary destination for install script
tmpNixInstall="$(mktemp -t nix-install-XXXXXXXXXX)"
if [[ ! -f "${tmpNixInstall}" ]]; then
echo "Failed creating a temporary file for Nix install script!"
return 1
fi
echo "Downloading install script from ${installURL}..."
if ! curl "${installURL}" -o "${tmpNixInstall}" &>/dev/null; then
echo "Failure while downloading Nix install script!"
return 1
fi
if ! sha="$(curl "${shaURL}")"; then
echo "Failure while downloading Nix install script sha!"
return 1
fi
echo "Validating Nix install script checksum..."
if ! echo "${sha} ${tmpNixInstall}" | sha256sum -c; then
echo "Checksum validation failed!"
return 1
fi
echo "Running nix installer..."
if $SHELL "${tmpNixInstall}"; then
echo "Nix is installed"
rm "${tmpNixInstall}"
else
echo "Nix installation script failed!"
return 1
fi
}
2020-12-07 09:09:48 +00:00
infect() {
# Add nix build users
# FIXME run only if necessary, rather than defaulting true
2023-11-18 02:47:34 +00:00
# groupadd nixbld -g 30000 || true
# for i in {1..10}; do
# useradd -c "Nix build user $i" -d /var/empty -g nixbld -G nixbld -M -N -r -s "$(which nologin)" "nixbld$i" || true
# done
2020-12-07 09:09:48 +00:00
# TODO use addgroup and adduser as fallbacks
#addgroup nixbld -g 30000 || true
#for i in {1..10}; do adduser -DH -G nixbld nixbld$i || true; done
2023-11-18 02:47:34 +00:00
# install Nix in the current system
# (this should create system nixbld users too)
# curl -L "https://releases.nixos.org/nix/nix-$NIX_VERSION/install" | $SHELL
if ! installNix; then
echo "Nix installation failed!"
exit 1
fi
2020-12-07 09:09:48 +00:00
# shellcheck disable=SC1090
2023-11-18 02:47:34 +00:00
# is it needed?
# source ~/.nix-profile/etc/profile.d/nix.sh
echo "nix build the configuration flake..."
if ! /root/.nix-profile/bin/nix build \
--extra-experimental-features "nix-command flakes" \
--profile /nix/var/nix/profiles/system \
${LOCAL_FLAKE_DIR}/#nixosConfigurations.sp-nixos.config.system.build.toplevel
then
echo "Failed!"
exit 1
fi
2020-12-07 09:09:48 +00:00
2023-11-18 02:47:34 +00:00
echo "activate the built configuration..."
if ! /nix/var/nix/profiles/system/activate; then
echo "Failed!"; exit 1
fi
2020-12-07 09:09:48 +00:00
2023-11-18 02:47:34 +00:00
echo "make configuration switch..."
if /nix/var/nix/profiles/system/bin/switch-to-configuration switch; then
echo "Failed!"; exit 1
fi
2020-12-07 09:09:48 +00:00
2023-11-18 02:47:34 +00:00
# Remove nix installed by the "install" script.
2020-12-07 09:09:48 +00:00
rm -fv /nix/var/nix/profiles/default*
/nix/var/nix/profiles/system/sw/bin/nix-collect-garbage
2023-11-18 02:47:34 +00:00
# Reify resolv.conf (???)
2020-12-07 09:09:48 +00:00
[[ -L /etc/resolv.conf ]] && mv -v /etc/resolv.conf /etc/resolv.conf.lnk && cat /etc/resolv.conf.lnk > /etc/resolv.conf
# Stage the Nix coup d'état
touch /etc/NIXOS
echo etc/nixos > /etc/NIXOS_LUSTRATE
echo etc/resolv.conf >> /etc/NIXOS_LUSTRATE
echo root/.nix-defexpr/channels >> /etc/NIXOS_LUSTRATE
rm -rf /boot.bak
2023-11-18 02:47:34 +00:00
((isEFI)) && umount "$ESP"
2020-12-07 09:09:48 +00:00
mv -v /boot /boot.bak
2023-11-18 02:47:34 +00:00
if ((isEFI)); then
2021-11-16 07:00:26 +00:00
mkdir /boot
2023-11-18 02:47:34 +00:00
mount "$ESP" /boot
2021-11-16 07:00:26 +00:00
find /boot -depth ! -path /boot -exec rm -rf {} +
fi
2023-11-18 02:47:34 +00:00
echo "make configuration boot by default..."
if /nix/var/nix/profiles/system/bin/switch-to-configuration boot; then
echo "Failed!"; exit 1
fi
2020-12-07 09:09:48 +00:00
}
2023-11-18 02:47:34 +00:00
set -o pipefail
set -o nounset
set -o xtrace
set -o errexit
2020-12-07 09:09:48 +00:00
2021-01-05 13:49:35 +00:00
apt update
2023-11-18 02:47:34 +00:00
apt install -y git tar wget curl jq
2021-11-16 07:00:26 +00:00
checkEnv
2020-12-07 09:09:48 +00:00
prepareEnv
makeSwap # smallest (512MB) droplet needs extra memory!
2023-11-18 02:47:34 +00:00
setupConf
2020-12-07 09:09:48 +00:00
infect
removeSwap
if [[ -z "$NO_REBOOT" ]]; then
reboot
fi