#!/bin/bash # gocode.it host integration. Run as root on the host to integrate: # curl -fsSL https://join.auth.gocode.it | sudo bash # Supported: Proxmox VE 7+, Debian 11+, Ubuntu 20.04+, Arista EOS 4.24+ (from the EOS bash shell). # It shows what it will do and asks before changing anything. Full log: /var/log/gocode-join.log # (/mnt/flash/gocode-join.log on EOS), also sent to the log servers when done. # Everything is inside main(), so a partial download runs nothing. JOIN_URL=${GOCODE_JOIN_URL:-https://join.auth.gocode.it} COLLECTORS="iad.auth.gocode.it yyz.auth.gocode.it" # a machine joins under a full name in one of our domains (the same list as join/domains on the auth nodes) DOMAINS="gocode.it sgct.ca xenyth.net xny.onl as835.net" # set when the script comes from the Security App's "Add device" page (https://join.../enrol/): # the admin approves this host on that page and follows the run there GOCODE_TOKEN=${GOCODE_TOKEN:-} enrol() { curl -s --max-time 8 "${@:2}" "$JOIN_URL/enrol/$GOCODE_TOKEN/$1" 2>/dev/null; } VERSION=1 # this machine's own name: the hostname it was given if that is a full name; only a short hostname # is completed by lookup (hostname -f alone would answer with whatever DNS or /etc/hosts calls the # address, e.g. a provider's reverse name) # every address configured on this machine, as "interface=address,..." (the device page shows them) machine_addrs() { ip -o addr show scope global 2>/dev/null | awk '{split($4, a, "/"); print $2 "=" a[1]}' | paste -sd, -; } fqdn() { local h; h=$(hostname); case $h in *.*) echo "$h" ;; *) hostname -f 2>/dev/null || echo "$h" ;; esac; } # ---------- output, log, questions ---------- ts() { date -u +%Y-%m-%dT%H:%M:%SZ; } log() { printf '%s %s\n' "$(ts)" "$*" >>"$LOG"; } say() { printf '%s\n' "$*"; log "$*"; } head1() { printf '\n\033[1m== %s\033[0m\n' "$*"; log "== $*"; } ok() { printf ' \033[32mok\033[0m %s\n' "$*"; log "ok: $*"; } warn() { printf ' \033[33mwarning\033[0m %s\n' "$*"; log "WARNING: $*"; WARNINGS+=("$*"); } die() { printf '\n\033[31mstopped:\033[0m %s\n' "$*"; log "STOPPED: $*"; finish 1; } # run CMD...: command and its output go to the log only run() { log "+ $*" local out rc out=$("$@" 2>&1); rc=$? printf '%s\n' "$out" | sed 's/^/ /' | tee -a "$LOG.run" >>"$LOG" # a failed command's last lines also go where the admin is watching (the Add device page) [ "$rc" = 0 ] || { log " (exit $rc)"; [ -z "$GOCODE_TOKEN" ] || printf '%s\n' "$out" | tail -12 | sed 's/^/ /' | enrol log --data-binary @- >/dev/null; } return "$rc" } ask() { # ask "question" default(y|n) [timeout-seconds] -> 0 for yes local a d=$2 t=() [ -n "${3:-}" ] && t=(-t "$3") if [ -n "${GOCODE_YES:-}" ]; then log "$1 -> yes (GOCODE_YES)"; return 0; fi [ -r /dev/tty ] || die "no terminal for questions (set GOCODE_YES=1 to accept everything)" read -r "${t[@]}" -p "$1 [$([ "$d" = y ] && echo Y/n || echo y/N)] " a ${a:-$d}" case ${a:-$d} in [yY]*) return 0 ;; *) return 1 ;; esac } fetch() { curl -fsS --max-time 30 --retry 2 "$JOIN_URL/$1" -o "$2"; } finish() { # send the integration log to syslog (forwarded once logging is set up), print where it is local rc=$1 n=0 log "finished with exit code $rc, ${#WARNINGS[@]} warning(s)" [ -z "$GOCODE_TOKEN" ] || enrol "done?rc=$rc" -X POST >/dev/null if [ -n "${LOGGER:-}" ]; then while IFS= read -r line; do $LOGGER "[$RUN_ID] $line"; n=$((n + 1)); done <"$LOG.run" $LOGGER "[$RUN_ID] integration $([ "$rc" = 0 ] && echo complete || echo FAILED) on $(hostname): ${#WARNINGS[@]} warning(s), $n log lines" fi printf '\nLog: %s%s\n' "$LOG" "$([ -n "${LOGGER:-}" ] && echo ", sent to syslog (tag gocode-join, run $RUN_ID)")" exit "$rc" } # ---------- admission on the auth nodes ---------- register_host() { # an admin admits this host with their SSH key / YubiKey: ssh register@... admit head1 "Admitting this host on the auth nodes" if [ "$(curl -s -o /dev/null -w '%{http_code}' --max-time 15 "$JOIN_URL/access")" = 200 ]; then ok "already admitted"; return fi local host ips= ip i host=$(fqdn) if [ -n "$GOCODE_TOKEN" ]; then local answer= for i in 4 6; do ip=$(enrol announce -$i --data-urlencode "host=$host" --data-urlencode "os=$PRETTY" --data-urlencode "addrs=$(machine_addrs)") && { answer=$ip; [ "$ip" = ok ] && ips+=" v$i"; } done [ -n "$ips" ] || die "the Add device page did not take this host: ${answer:-no answer (get a new command from the Add device page)}" say " Waiting for an admin to approve this host on the Add device page (10 minutes)..." for i in $(seq 1 200); do case $(enrol state) in approved) break ;; rejected) die "an admin rejected this host" ;; esac sleep 3 done [ "$i" -lt 200 ] || die "not approved within 10 minutes (get a new command from the Add device page)" for i in $(seq 1 60); do [ "$(curl -s -o /dev/null -w '%{http_code}' --max-time 10 "$JOIN_URL/access")" = 200 ] && break sleep 3 done [ "$i" -lt 60 ] || die "approved, but the auth nodes still refuse this host after 3 minutes" ok "approved and admitted; the second log server follows within a minute" return fi for i in 4 6; do ip=$(curl -$i -fsS --max-time 10 "$JOIN_URL/myip" 2>/dev/null) && ips+=" $ip" done [ -n "$ips" ] || die "cannot reach $JOIN_URL" local srv=${JOIN_URL#https://}; srv=${srv%%[:/]*} ADMIT_CMD="ssh register@$srv admit $host$ips" say " This host reaches the auth nodes as:$ips" say " From your laptop (a key with deploy access, or your YubiKey certificate), run:" say "" say " $ADMIT_CMD" say "" say " Waiting for it (10 minutes)..." for i in $(seq 1 200); do [ "$(curl -s -o /dev/null -w '%{http_code}' --max-time 10 "$JOIN_URL/access")" = 200 ] && break sleep 3 done [ "$i" -lt 200 ] || die "not admitted within 10 minutes (run the script again after admitting it)" log "admitted:$ips" ok "admitted:$ips; the second log server follows within a minute" } # ---------- detection ---------- detect() { OS= OSVER= PRETTY= if [ -f /etc/Eos-release ] || [ -x /usr/bin/FastCli ]; then OS=eos OSVER=$(grep -oE '[0-9]+\.[0-9]+\.[0-9]+[A-Z.0-9]*' /etc/Eos-release 2>/dev/null | head -1) [ -n "$OSVER" ] || OSVER=$(FastCli -p 15 -c 'show version' | sed -n 's/^Software image version: *//p') PRETTY="Arista EOS $OSVER" vge "$OSVER" 4.24 || die "EOS $OSVER is older than 4.24" return fi [ -r /etc/os-release ] || die "unknown system (no /etc/os-release)" . /etc/os-release if command -v pveversion >/dev/null; then OS=proxmox OSVER=$(pveversion | sed -n 's|^pve-manager/\([0-9.]*\).*|\1|p') PRETTY="Proxmox VE $OSVER (Debian $VERSION_ID)" vge "$OSVER" 7 || die "Proxmox VE $OSVER is older than 7" elif [ "$ID" = debian ]; then OS=debian OSVER=$VERSION_ID PRETTY="Debian $VERSION_ID" vge "$OSVER" 11 || die "Debian $OSVER is older than 11" elif [ "$ID" = ubuntu ]; then OS=ubuntu OSVER=$VERSION_ID PRETTY="Ubuntu $VERSION_ID" vge "$OSVER" 20.04 || die "Ubuntu $OSVER is older than 20.04" else die "unsupported system: ${PRETTY_NAME:-$ID} (supported: Proxmox VE 7+, Debian 11+, Ubuntu 20.04+, EOS 4.24+)" fi } vge() { [ "$(printf '%s\n%s\n' "$2" "$1" | sort -V | head -1)" = "$2" ]; } # version $1 >= $2 # ====================================================================== # Linux (Debian, Ubuntu, Proxmox VE) # ====================================================================== linux_plan() { cat </dev/null | awk '{print $2}')" 3.5 && apt-cache show rsyslog-openssl >/dev/null 2>&1; then drv=openssl; fi for p in curl ca-certificates sudo rsyslog rsyslog-$drv openssh-server; do dpkg-query -W -f='${Status}' "$p" 2>/dev/null | grep -q 'ok installed' || need+=("$p") done RSYSLOG_DRIVER=$([ $drv = openssl ] && echo ossl || echo gtls) if [ ${#need[@]} = 0 ]; then ok "all present (rsyslog TLS driver: $drv)"; return; fi say " installing: ${need[*]}" # Only these packages (and what they need) are touched: they are downloaded, then handed to dpkg # one by one. `apt-get install` would also finish every other half-installed package on the # machine (a pending kernel, its driver builds, ...), which is not ours to start. local debs=() f for f in $(apt-get install -qq --print-uris --no-install-recommends "${need[@]}" 2>>"$LOG" | awk '{print $2}'); do debs+=("/var/cache/apt/archives/$f") done [ ${#debs[@]} -gt 0 ] || die "apt cannot work out how to install ${need[*]} (see $LOG)" run apt-get install -y -q --download-only --no-install-recommends "${need[@]}" || die "package download failed (see $LOG)" DEBIAN_FRONTEND=noninteractive run dpkg --force-confdef --force-confold -i "${debs[@]}" || true for p in "${need[@]}"; do dpkg-query -W -f='${Status}' "$p" 2>/dev/null | grep -q 'ok installed' || die "package install failed: $p (see $LOG)" done ok "installed ${need[*]} (rsyslog TLS driver: $drv)" } linux_ca() { head1 "FreeIPA CA" install -d -m 755 /etc/gocode fetch ipa-ca.crt /etc/gocode/ipa-ca.crt.new || die "cannot download $JOIN_URL/ipa-ca.crt" openssl x509 -in /etc/gocode/ipa-ca.crt.new -noout -subject >>"$LOG" 2>&1 || die "ipa-ca.crt is not a certificate" mv /etc/gocode/ipa-ca.crt.new /etc/gocode/ipa-ca.crt printf 'JOIN_URL=%s\n' "$JOIN_URL" >/etc/gocode/gocode.conf ok "$(openssl x509 -in /etc/gocode/ipa-ca.crt -noout -subject -fingerprint -sha256 | tr '\n' ' ')" } linux_accounts() { head1 "Accounts (FreeIPA linuxadmins / linuxops)" cat >/usr/local/sbin/gocode-access <<'EOS_ACCESS' #!/bin/bash # Installed by gocode-join. Every 5 minutes (gocode-access.timer): local accounts and SSH keys for # FreeIPA users in linuxadmins (sudo) and linuxops, from $JOIN_URL/access. # Managed accounts are members of group "gocode"; a local account outside it is never touched. # A user that leaves the list is locked (expired), loses its keys and is logged out. set -uo pipefail . /etc/gocode/gocode.conf D=/etc/ssh/gocode note() { logger -t gocode-access -p authpriv.notice "$*"; echo "$*"; } tmp=$(mktemp) && trap 'rm -f "$tmp"' EXIT if ! curl -fsS --max-time 20 "$JOIN_URL/access" -o "$tmp"; then logger -t gocode-access -p authpriv.warning "cannot fetch $JOIN_URL/access, keeping the current accounts" exit 0 fi [ "$(head -1 "$tmp")" = "# gocode-access v1" ] && [ "$(tail -1 "$tmp")" = "# end" ] || { logger -t gocode-access -p authpriv.err "malformed access list, keeping the current accounts"; exit 1; } supported=" $(ssh -Q key | tr '\n' ' ') " name_ok() { [[ $1 =~ ^[a-z_][a-z0-9_.-]{0,31}$ ]]; } key_ok() { [[ $supported == *" $1 "* && $2 =~ ^[A-Za-z0-9+/]+=*$ ]]; } declare -A role uid gecos keys ca= while read -r kind a b c d; do case $kind in ca) key_ok "$a" "$b" && ca+="$a $b $c"$'\n' ;; user) name_ok "$a" && [[ $b =~ ^[0-9]+$ ]] && [[ $c == admin || $c == user ]] && { uid[$a]=$b role[$a]=$c gecos[$a]=${d//[^A-Za-z0-9 ._-]/}; keys[$a]=; } ;; key) [ -n "${role[$a]+x}" ] && key_ok "$b" "$c" && keys[$a]+="$b $c $a"$'\n' ;; esac done < <(grep -v '^#' "$tmp") install -d -m 755 "$D" "$D/keys" [ -n "$ca" ] && { printf '%s' "$ca" >"$D/user_ca.pub.new" && mv "$D/user_ca.pub.new" "$D/user_ca.pub"; } getent group gocode >/dev/null || groupadd -r gocode getent group gocode-admin >/dev/null || groupadd -r gocode-admin in_group() { id -nG "$1" 2>/dev/null | tr ' ' '\n' | grep -qx "$2"; } for u in "${!role[@]}"; do if getent passwd "$u" >/dev/null; then in_group "$u" gocode || { logger -t gocode-access -p authpriv.warning "local account $u exists and is not managed by gocode; skipped"; continue; } else args=(); getent passwd "${uid[$u]}" >/dev/null || args=(-u "${uid[$u]}") useradd -m -s /bin/bash -c "${gecos[$u]:-$u} (FreeIPA)" -G gocode "${args[@]}" "$u" && note "account $u created (${role[$u]})" fi [ "$(getent shadow "$u" | cut -d: -f2)" = "*" ] || usermod -p '*' "$u" # no password: key/certificate only [ "$(getent shadow "$u" | cut -d: -f8)" = "" ] || { chage -E -1 "$u"; note "account $u unlocked"; } if [ "${role[$u]}" = admin ]; then in_group "$u" gocode-admin || { gpasswd -a "$u" gocode-admin >/dev/null; note "$u may use sudo"; } else in_group "$u" gocode-admin && { gpasswd -d "$u" gocode-admin >/dev/null; note "$u may no longer use sudo"; }; fi f="$D/keys/$u" if [ "$(cat "$f" 2>/dev/null)" != "${keys[$u]%$'\n'}" ]; then printf '%s' "${keys[$u]}" >"$f.new" && chmod 644 "$f.new" && mv "$f.new" "$f" note "SSH keys of $u updated ($(grep -c . "$f") key(s))" fi done for u in $(getent group gocode | cut -d: -f4 | tr , ' '); do [ -n "${role[$u]+x}" ] && continue [ "$(getent shadow "$u" | cut -d: -f8)" = "0" ] && continue # already locked chage -E 0 "$u"; rm -f "$D/keys/$u"; gpasswd -d "$u" gocode-admin >/dev/null 2>&1 pkill -KILL -u "$u" 2>/dev/null note "account $u locked and logged out (no longer in FreeIPA linuxadmins/linuxops)" done exit 0 EOS_ACCESS chmod 755 /usr/local/sbin/gocode-access cat >/etc/systemd/system/gocode-access.service <<'EOF' [Unit] Description=gocode.it: sync FreeIPA accounts and SSH keys After=network-online.target Wants=network-online.target [Service] Type=oneshot ExecStart=/usr/local/sbin/gocode-access EOF cat >/etc/systemd/system/gocode-access.timer <<'EOF' [Unit] Description=gocode.it: sync FreeIPA accounts and SSH keys every 5 minutes [Timer] OnBootSec=1min OnUnitActiveSec=5min RandomizedDelaySec=30 [Install] WantedBy=timers.target EOF echo '%gocode-admin ALL=(ALL:ALL) NOPASSWD: ALL' >/etc/sudoers.d/gocode.new visudo -cf /etc/sudoers.d/gocode.new >>"$LOG" 2>&1 || die "sudoers check failed" chmod 440 /etc/sudoers.d/gocode.new && mv /etc/sudoers.d/gocode.new /etc/sudoers.d/gocode run systemctl daemon-reload run /usr/local/sbin/gocode-access || die "first account sync failed (see $LOG)" run systemctl enable --now gocode-access.timer || die "cannot enable gocode-access.timer" local members members=$(getent group gocode | cut -d: -f4) ok "accounts: ${members:-none yet} (sudo: $(getent group gocode-admin | cut -d: -f4))" ok "SSH user CA keys: $(cut -d' ' -f1 /etc/ssh/gocode/user_ca.pub 2>/dev/null | tr '\n' ' ')" } linux_ssh() { head1 "SSH" local d=/etc/ssh/sshd_config.d f=/etc/ssh/sshd_config.d/10-gocode.conf want kex= a install -d -m 755 $d grep -qiE '^\s*Include\s+/etc/ssh/sshd_config.d/\*\.conf' /etc/ssh/sshd_config || { cp -a /etc/ssh/sshd_config /etc/ssh/sshd_config.gocode-bak sed -i '1i Include /etc/ssh/sshd_config.d/*.conf' /etc/ssh/sshd_config say " added the sshd_config.d include to /etc/ssh/sshd_config (backup: sshd_config.gocode-bak)" } [ -f /etc/ssh/ssh_host_ecdsa384_key ] || run ssh-keygen -q -t ecdsa -b 384 -N '' -C "$(fqdn)" -f /etc/ssh/ssh_host_ecdsa384_key # post-quantum hybrids, then P-384, then RSA-class finite-field DH; only what this OpenSSH has want="mlkem768x25519-sha256 sntrup761x25519-sha512 sntrup761x25519-sha512@openssh.com ecdh-sha2-nistp384 diffie-hellman-group16-sha512" for a in $want; do ssh -Q kex | grep -qx "$a" && kex+=${kex:+,}$a; done local hk=() hka=ecdsa-sha2-nistp384 rsabits hk+=(/etc/ssh/ssh_host_ecdsa384_key) [ -f /etc/ssh/ssh_host_rsa_key ] && { hk+=(/etc/ssh/ssh_host_rsa_key); hka+=,rsa-sha2-512,rsa-sha2-256 rsabits=$(ssh-keygen -lf /etc/ssh/ssh_host_rsa_key.pub | awk '{print $1}') [ "${rsabits:-0}" -ge 3072 ] || warn "RSA host key is $rsabits bits (kept: other machines may know it; replace with 3072+ when convenient)"; } [ -f /etc/ssh/ssh_host_ed25519_key ] && { hk+=(/etc/ssh/ssh_host_ed25519_key); hka+=,ssh-ed25519; } # host certificates: step-ca signs this machine's host keys (10 years), so a client that trusts # our host CA is never asked about a fingerprint (laptop setup: the guide) local certs=() got i=0 line if got=$(for a in "${hk[@]}"; do cat "$a.pub"; done | curl -fsS --max-time 90 --data-binary @- "$JOIN_URL/hostcert" 2>>"$LOG"); then while IFS= read -r line; do a=${hk[$i]:-}; i=$((i + 1)) [ -n "$a" ] && [[ $line == *-cert-v01@openssh.com\ * ]] || continue printf '%s\n' "$line" >"$a-cert.pub.new" if ssh-keygen -L -f "$a-cert.pub.new" 2>/dev/null | grep -q 'host certificate' && [ "$(ssh-keygen -lf "$a-cert.pub.new" | awk '{print $2}')" = "$(ssh-keygen -lf "$a.pub" | awk '{print $2}')" ]; then mv "$a-cert.pub.new" "$a-cert.pub"; certs+=("$a-cert.pub") case ${line%% *} in ssh-rsa-cert-*) hka="rsa-sha2-512-cert-v01@openssh.com,rsa-sha2-256-cert-v01@openssh.com,$hka" ;; *) hka="${line%% *},$hka" ;; esac else rm -f "$a-cert.pub.new"; fi done <<<"$got" fi [ ${#certs[@]} -gt 0 ] || warn "no host certificate from the auth nodes: clients will be asked to trust this host's fingerprint" rm -f /etc/ssh/10-gocode.conf.prev; [ -f $f ] && cp -a $f /etc/ssh/10-gocode.conf.prev { echo "# gocode-join: YubiKey login for FreeIPA users (step-ca certificates or keys from FreeIPA)," echo "# accounts and keys kept by gocode-access.timer. Key exchange: post-quantum first, then P-384," echo "# then RSA-class DH. Delete an entry to disable that family." echo "TrustedUserCAKeys /etc/ssh/gocode/user_ca.pub" echo "AuthorizedKeysFile .ssh/authorized_keys .ssh/authorized_keys2 /etc/ssh/gocode/keys/%u" echo "KexAlgorithms $kex" echo "Ciphers chacha20-poly1305@openssh.com,aes256-gcm@openssh.com,aes128-gcm@openssh.com" echo "MACs hmac-sha2-512-etm@openssh.com,hmac-sha2-256-etm@openssh.com" for a in "${hk[@]}"; do echo "HostKey $a"; done for a in "${certs[@]}"; do echo "HostCertificate $a"; done echo "HostKeyAlgorithms $hka" } >$f install -d -m 755 /run/sshd if ! run sshd -t; then rm -f $f; [ -f /etc/ssh/10-gocode.conf.prev ] && mv /etc/ssh/10-gocode.conf.prev $f die "sshd rejected the new settings (see $LOG); nothing changed" fi log "$(cat $f)" ssh_reload || die "sshd reload failed" if ! ssh_selftest; then ssh_revert; die "a test connection to this sshd failed after the change; reverted (see $LOG)" fi ok "kex: $kex" ok "host keys: $(for a in "${hk[@]}"; do ssh-keygen -lf "$a.pub" | awk '{gsub(/[()]/, "", $NF); print $NF "-" $1}'; done | tr '\n' ' ')" [ ${#certs[@]} = 0 ] || ok "host certificates: ${#certs[@]}, valid until $(ssh-keygen -L -f "${certs[0]}" | sed -n 's/.* to \([0-9-]*\)T.*/\1/p')" # remote hosts: keep the change only when the operator confirms a new login works run systemctl reset-failed gocode-ssh-revert.timer gocode-ssh-revert.service run systemd-run --unit gocode-ssh-revert --on-active=300 /bin/sh -c \ "rm -f $f; [ -f /etc/ssh/10-gocode.conf.prev ] && mv /etc/ssh/10-gocode.conf.prev $f; systemctl try-reload-or-restart ssh 2>/dev/null || systemctl try-reload-or-restart sshd; logger -t gocode-join -p authpriv.warning 'SSH change reverted (not confirmed)'" say "" say " Open a NEW ssh session to this host from another terminal now (your usual way)." if ask " Did the new login work? (no answer within 5 minutes = revert)" n 290 && systemctl is-active -q gocode-ssh-revert.timer; then run systemctl stop gocode-ssh-revert.timer rm -f /etc/ssh/10-gocode.conf.prev ok "SSH change kept" else run systemctl stop gocode-ssh-revert.timer ssh_revert warn "SSH change reverted: accounts exist, but YubiKey logins need the SSH step (run the script again)" fi } ssh_reload() { if systemctl cat ssh.service >/dev/null 2>&1; then run systemctl try-reload-or-restart ssh else run systemctl try-reload-or-restart sshd; fi } ssh_revert() { local f=/etc/ssh/sshd_config.d/10-gocode.conf rm -f $f; [ -f /etc/ssh/10-gocode.conf.prev ] && mv /etc/ssh/10-gocode.conf.prev $f ssh_reload; log "SSH change reverted" } ssh_selftest() { # a key exchange with the local sshd must complete (it then refuses the login, which is fine) local port out port=$(sshd -T 2>/dev/null | awk '$1 == "port" {print $2; exit}') out=$(timeout 15 ssh -o BatchMode=yes -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null \ -o PreferredAuthentications=none -o ConnectTimeout=5 -p "${port:-22}" gocode-selftest@127.0.0.1 true 2>&1) log "ssh self-test: $out" grep -q 'Permission denied' <<<"$out" } linux_syslog() { head1 "Syslog to $COLLECTORS" local f=/etc/rsyslog.d/60-gocode.conf c filter install -m 644 /etc/gocode/ipa-ca.crt /etc/rsyslog.d/gocode-ipa-ca.pem # the log servers take TLS 1.3 only; rsyslog's GnuTLS default stops at 1.2 local prio="NORMAL:-VERS-ALL:+VERS-TLS1.3" [ "$RSYSLOG_DRIVER" = ossl ] && prio="MinProtocol=TLSv1.3" filter='$syslogseverity <= 4 or $syslogfacility-text == "auth" or $syslogfacility-text == "authpriv" or $programname startswith "gocode-"' [ "$OS" = proxmox ] && filter+=' or (($programname == "pvedaemon" or $programname == "pveproxy") and $msg contains "auth")' { echo "# gocode-join: important messages (warnings and worse, logins, sudo, this integration) to the" echo "# gocode.it log servers over TLS 1.3, certificate checked against the FreeIPA CA. One disk-assisted" echo "# queue per server, so a server being down neither blocks nor loses messages." echo "# (CA copy in rsyslog.d: Ubuntu's AppArmor profile lets rsyslogd read only there)" echo "global(preserveFQDN=\"on\" defaultNetstreamDriverCAFile=\"/etc/rsyslog.d/gocode-ipa-ca.pem\")" echo "# (rsyslog warns on every connection that this client has no certificate of its own: not sent)" echo "if ($filter) and not (\$programname == \"rsyslogd\" and \$msg contains \"file is not set\") then {" for c in $COLLECTORS; do cat <$f # Debian 12+/Proxmox 8+ hand journald messages to rsyslog only through imjournal or the socket if ! grep -rqsE 'imjournal|imuxsock' /etc/rsyslog.conf /etc/rsyslog.d/; then sed -i '1i module(load="imuxsock")' $f fi run rsyslogd -N1 || { rm -f $f; die "rsyslog rejected the configuration (see $LOG)"; } run systemctl enable rsyslog run systemctl restart rsyslog || die "rsyslog did not restart" LOGGER="logger -t gocode-join -p authpriv.notice" $LOGGER "[$RUN_ID] syslog forwarding to $COLLECTORS set up by gocode-join" local i for c in $COLLECTORS; do for i in $(seq 1 15); do timeout 4 bash -c "exec 3<>/dev/tcp/$c/6514" 2>/dev/null && break; sleep 5; done if [ "$i" -lt 15 ]; then ok "$c:6514 reachable" else warn "$c:6514 not reachable from here (messages queue on disk until it is; firewall?)"; fi done } linux_main() { linux_plan ask "Proceed?" y || { say "Nothing changed."; finish 0; } export DEBIAN_FRONTEND=noninteractive register_host linux_packages linux_ca linux_syslog linux_accounts linux_ssh head1 "Done" say " YubiKey login, once per day on your laptop (see the guide):" say " step ssh certificate \$USER ~/.ssh/id_ed25519_sk.pub --sign --provisioner keycloak --force" say " ssh @$(fqdn)" [ ${#WARNINGS[@]} = 0 ] || { say " Warnings:"; for w in "${WARNINGS[@]}"; do say " - $w"; done; } finish 0 } # ====================================================================== # Arista EOS (run from the EOS bash shell: `bash`, then the curl line) # ====================================================================== # ====================================================================== # Arista EOS (from the EOS bash shell: `bash`, then the curl line; sudo not needed) # Not yet run on a switch. Every change goes through a config session: you see the diff, # nothing is committed or saved without a yes, and a command EOS does not know stops that step. # ====================================================================== cli() { FastCli -p 15 -c "$1" 2>&1; } cli_ok() { ! grep -qE '^% (Invalid|Incomplete|Ambiguous|Error|Unavailable)|not supported' <<<"$1"; } eos_options() { # eos_options "" "": words EOS offers after it (from `?` help) cli "configure session gocode-probe $1 $2 ? abort" | awk '/^ [a-z0-9]/ {print $1}' | grep -v '^<' } eos_plan() { cat </mnt/flash/gocode-user-ca.pub out=$(cli "copy file:/mnt/flash/gocode-ipa-ca.crt certificate:gocode-ipa-ca.crt copy file:/mnt/flash/gocode-user-ca.pub ssh-ca-key:gocode-user-ca.pub") log "$out" cli_ok "$out" || warn "copying the CA files into EOS failed: $out" EOS_CMDS="management security ssl profile gocode-syslog tls versions 1.3 trust certificate gocode-ipa-ca.crt logging trap notifications logging format hostname fqdn " opts=$(eos_options "" "logging ${vrf}host iad.auth.gocode.it 6514 protocol") log "logging protocols offered: $opts" grep -qx tls <<<"$opts" || tls= for c in $COLLECTORS; do if [ -n "$tls" ]; then EOS_CMDS+="logging ${vrf}host $c 6514 protocol tls ssl-profile gocode-syslog " else EOS_CMDS+="logging ${vrf}host $c 514 protocol tcp "; fi done [ -n "$tls" ] || warn "this EOS offers no TLS for log hosts: using plain TCP 514 (only admitted from the lab)" # SSH: user CA keys, key exchange, users EOS_CMDS+="management ssh trusted-ca key public gocode-user-ca.pub " opts=$(eos_options "management ssh" "key-exchange") log "key exchanges offered: $opts" for a in mlkem768x25519-sha256 sntrup761x25519-sha512 sntrup761x25519-sha512@openssh.com ecdh-sha2-nistp384 diffie-hellman-group16-sha512; do grep -qx "$a" <<<"$opts" && kex+=" $a" done if [ -n "$kex" ]; then EOS_CMDS+=" key-exchange$kex "; else warn "could not read this EOS's key-exchange names; SSH key exchange left as it is"; fi EOS_KEX=$kex while read -r kind user uidn role _; do [ "$kind" = net ] || continue [[ $user =~ ^[a-z_][a-z0-9_.-]{0,31}$ ]] || continue case $role in netadmins) role=network-admin ;; netops | netread) role=network-operator ;; *) continue ;; esac if cli "show running-config section username" | grep -q "^username $user " && ! grep -qx "$user" /mnt/flash/gocode-users 2>/dev/null; then warn "local user $user exists and was not made by this script; skipped"; continue fi EOS_CMDS+="username $user privilege 15 role $role secret $(head -c 24 /dev/urandom | base64 | tr -dc A-Za-z0-9) username $user ssh-principal $user " EOS_USERS+=" $user" done /dev/null); do grep -qE "^net $user " /mnt/flash/gocode-access || { EOS_CMDS+="no username $user "; EOS_REMOVED+=" $user"; } done } eos_main() { EOS_VRF=$(ip netns identify $$ 2>/dev/null); EOS_VRF=${EOS_VRF#ns-} eos_plan ask "Prepare the change (nothing is applied yet)?" y || { say "Nothing changed."; finish 0; } LOGGER=eos_log register_host head1 "Building the configuration" eos_config local out out=$(cli "configure session gocode-join $EOS_CMDS show session-config diffs") log "$out" if ! cli_ok "$out"; then cli "configure session gocode-join abort" >/dev/null printf '%s\n' "$out" | grep -E '^%' | head -5 die "EOS rejected a command (see $LOG); nothing applied" fi head1 "Changes" printf '%s\n' "$out" | grep -E '^[-+]' || say " (no differences)" ask "Apply these changes?" y || { cli "configure session gocode-join abort" >/dev/null; say "Aborted, nothing applied."; finish 0; } out=$(cli "configure session gocode-join commit") ; log "$out" cli_ok "$out" || die "commit failed: $out" ok "applied (running-config only)" printf '%s\n' $EOS_USERS >/mnt/flash/gocode-users [ -z "${EOS_REMOVED:-}" ] || ok "removed users no longer in FreeIPA:$EOS_REMOVED" ok "YubiKey users:${EOS_USERS:- none}" say "" say " Open a NEW ssh session to this switch now (your usual way, then a YubiKey certificate)." if ask " Does it work? (yes = write memory; no = keep it unsaved, a reload undoes it)" n; then out=$(cli "copy running-config startup-config"); log "$out" ok "saved" else warn "not saved: the change disappears at the next reload (or run: configure replace startup-config)" fi head1 "Done" [ ${#WARNINGS[@]} = 0 ] || { say " Warnings:"; for w in "${WARNINGS[@]}"; do say " - $w"; done; } finish 0 } eos_log() { # one line to the switch log, which forwards it to the log servers case $1 in *"] "*) return ;; esac # command output: kept in the local log only (FastCli is slow) FastCli -p 15 -c "send log level notifications message gocode-join: ${1//[^[:print:]]/}" >/dev/null 2>&1 } main() { WARNINGS=() RUN_ID=$(date -u +%Y%m%d%H%M%S)-$$ [ "$(id -u)" = 0 ] || [ -x /usr/bin/FastCli ] || { echo "run as root: curl -fsSL $JOIN_URL | sudo bash"; exit 1; } if [ -x /usr/bin/FastCli ]; then LOG=/mnt/flash/gocode-join.log; else LOG=/var/log/gocode-join.log; fi : >"$LOG.run" || { echo "cannot write $LOG"; exit 1; } chmod 600 "$LOG" "$LOG.run" 2>/dev/null # everything logged in this run also goes to $LOG.run, which finish() sends to syslog log() { printf '%s %s\n' "$(ts)" "$*" | tee -a "$LOG.run" >>"$LOG" [ -z "$GOCODE_TOKEN" ] || printf '%s\n' "$*" | enrol log --data-binary @- >/dev/null } log "gocode-join v$VERSION run $RUN_ID from $JOIN_URL, invoked by ${SUDO_USER:-$(logname 2>/dev/null || echo root)}" printf '\033[1mgocode.it host integration\033[0m (v%s)\n' "$VERSION" detect log "detected: $PRETTY" local name d named= name=$(fqdn) for d in $DOMAINS; do [[ ${name,,} == *.$d ]] && named=1; done [ -n "$named" ] || die "this machine is called '$name': it needs a full name in one of ${DOMAINS// /, } first$( [ "$OS" = eos ] || echo " (hostnamectl set-hostname ., and the same name on the 127.0.1.1 line of /etc/hosts)")" case $OS in eos) eos_main ;; *) linux_main ;; esac } main "$@"