Skip to content

Duo Setup Proxmox

Creating Duo Script

Paste the following into a script called duo-setup.sh

#!/usr/bin/env bash
#
# duo-install.sh — Install & configure Duo Unix MFA for SSH on
#                  Debian / Ubuntu / Proxmox VE hosts.
#
# Best-practice changes vs. the original:
#   - strict mode (set -euo pipefail), IFS hardening, restrictive umask
#   - structured logging + timestamped backups of every file we touch
#   - automatic rollback (trap on ERR/INT/TERM) restores backups on failure
#   - idempotent: safe to re-run; PAM stack is only modified once
#   - secrets read from --stdin or --env by default, NOT the command line
#     (positional args still supported but warn about ps(1) leakage)
#   - input validation (ikey format, skey length, host pattern, failmode)
#   - architecture-aware repo line (dpkg --print-architecture)
#   - codename derived from /etc/os-release (no hard-coded "noble")
#   - signing key written to /etc/apt/keyrings (modern Debian convention)
#   - PAM module path discovered via `dpkg -L duo-unix`, not /lib64 (which
#     is the RHEL convention and DOES NOT exist on Debian/Ubuntu — this
#     was a real bug in the original)
#   - sshd_config validated with `sshd -t` BEFORE restart
#   - ssh service unit auto-detected (ssh.service vs sshd.service)
#   - explicit reminder that the Proxmox web UI needs separate MFA setup
#   - Ubuntu codename fallback: if Duo's repo lacks the current codename
#     (e.g. "resolute" for 26.04), falls back to the previous LTS codename
#     ("noble") — Duo packages are binary-compatible across LTS releases.
#
# Usage:
#   sudo ./duo-install.sh --stdin                # secrets piped in / typed
#   sudo DUO_IKEY=... DUO_SKEY=... DUO_API_HOST=... ./duo-install.sh --env
#   sudo ./duo-install.sh <ikey> <skey> <host>   # works, but discouraged
#
# Tested targets: Debian 12/13, Ubuntu 22.04/24.04/26.04, Proxmox VE 8/9.
#

set -euo pipefail
IFS=$'\n\t'
umask 077

readonly SCRIPT_NAME="${0##*/}"
readonly TS="$(date -u +%Y%m%dT%H%M%SZ)"
readonly BAK_SUFFIX=".bak.${TS}"
readonly LOG_TAG="[duo-setup]"

# Defaults (override via flags)
SECRET_SOURCE="args"
FAILMODE="safe"
BYPASS_GROUP=""
IKEY=""
SKEY=""
API_HOST=""
PAM_DUO_PATH=""
IS_PROXMOX=0
ROLLBACK_FILES=()

log()  { printf '%s %s\n' "$LOG_TAG" "$*"; }
warn() { printf '%s WARN: %s\n' "$LOG_TAG" "$*" >&2; }
die()  { printf '%s ERROR: %s\n' "$LOG_TAG" "$*" >&2; exit 1; }

usage() {
  cat <<EOF
Usage: $SCRIPT_NAME [options] [<ikey> <skey> <api_hostname>]

Sources for the three Duo secrets (pick one):
  positional args              quick but visible in ps(1)
  --stdin                      read 3 lines from stdin: ikey, skey, host
  --env                        read DUO_IKEY / DUO_SKEY / DUO_API_HOST

Options:
  --bypass-group "<spec>"      override default Duo 'groups' line in
                               /etc/duo/pam_duo.conf
                               (default: '!root,!dscadmin,*' on Debian/PVE,
                                         '!dscadmin,*'        on Ubuntu)
  --failmode safe|secure       default: safe
  -h, --help                   show this help

This script protects SSH only. The Proxmox web UI uses its own auth
realms — enable TOTP/WebAuthn under Datacenter → Permissions →
Two-Factor in the Proxmox UI to require MFA there as well.
EOF
}

#─── arg parsing ──────────────────────────────────────────────────────────────
parse_args() {
  while [[ $# -gt 0 ]]; do
    case "$1" in
      --stdin)        SECRET_SOURCE="stdin"; shift ;;
      --env)          SECRET_SOURCE="env";   shift ;;
      --bypass-group) BYPASS_GROUP="${2:-}"; shift 2 ;;
      --failmode)     FAILMODE="${2:-}";     shift 2 ;;
      -h|--help)      usage; exit 0 ;;
      --) shift; break ;;
      -*) die "Unknown option: $1 (try --help)" ;;
      *)  break ;;
    esac
  done

  case "$SECRET_SOURCE" in
    args)
      [[ $# -eq 3 ]] || { usage >&2; die "Provide <ikey> <skey> <host>, or use --stdin/--env"; }
      IKEY="$1"; SKEY="$2"; API_HOST="$3"
      warn "Secrets passed on the command line are visible in ps(1) and shell history."
      warn "Prefer --stdin or --env for production rollouts."
      ;;
    stdin)
      log "Reading IKEY, SKEY, API_HOST from stdin (one per line)…"
      IFS= read -r IKEY     || die "stdin: missing IKEY"
      IFS= read -r SKEY     || die "stdin: missing SKEY"
      IFS= read -r API_HOST || die "stdin: missing API_HOST"
      ;;
    env)
      IKEY="${DUO_IKEY:-}"
      SKEY="${DUO_SKEY:-}"
      API_HOST="${DUO_API_HOST:-}"
      ;;
  esac
}

#─── validation ───────────────────────────────────────────────────────────────
require_root() {
  [[ $EUID -eq 0 ]] || die "Must be run as root."
}

validate_inputs() {
  [[ "$IKEY"     =~ ^DI[A-Z0-9]{18}$ ]]                         || die "IKEY format invalid (expected 'DI' + 18 uppercase alphanumerics)"
  [[ "${#SKEY}"  -eq 40 && "$SKEY" =~ ^[A-Za-z0-9]+$ ]]         || die "SKEY invalid (expected 40 alphanumerics, got ${#SKEY})"
  [[ "$API_HOST" =~ ^api-[a-z0-9-]+\.duosecurity\.com$ ]]       || die "API_HOST must look like api-xxxxxxxx.duosecurity.com"
  [[ "$FAILMODE" =~ ^(safe|secure)$ ]]                          || die "--failmode must be 'safe' or 'secure'"
}

#─── distro detection ─────────────────────────────────────────────────────────
detect_distro() {
  [[ -r /etc/os-release ]] || die "/etc/os-release missing — unsupported system."
  # shellcheck disable=SC1091
  . /etc/os-release
  DISTRO="${ID:-unknown}"
  CODENAME="${VERSION_CODENAME:-}"
  VERSION_ID_NUM="${VERSION_ID:-}"
  ARCH="$(dpkg --print-architecture 2>/dev/null || echo amd64)"

  if command -v pveversion >/dev/null 2>&1 || [[ -d /etc/pve ]]; then
    IS_PROXMOX=1
    log "Proxmox VE detected: $(pveversion 2>/dev/null | head -1 || echo 'pveversion not callable')"
  fi
  log "Distro: $DISTRO ${VERSION_ID_NUM} (${CODENAME:-?}), arch=$ARCH"
}

#─── Ubuntu codename-to-LTS-fallback map ─────────────────────────────────────
# Duo's third-party repo often lags behind new Ubuntu LTS releases by weeks
# or months. Packages built for a previous LTS are binary-compatible with the
# next one (same libc ABI, same PAM ABI), so falling back is safe.
#
# Map: current codename → previous LTS codename to try if Duo has no Release
# file for the current one yet. Extend this when future LTS releases ship.
declare -A UBUNTU_LTS_FALLBACK=(
  [resolute]=noble       # 26.04 → 24.04
  [noble]=jammy           # 24.04 → 22.04
  [jammy]=focal            # 22.04 → 20.04
)

#─── helper: test whether Duo's repo has a Release file for a given dist ──────
duo_repo_has_dist() {
  local repo_dir="$1" dist="$2" key="$3"
  local url="https://pkg.duosecurity.com/${repo_dir}/dists/${dist}/Release"
  # Quiet HEAD request — returns 0 if the file exists, non-zero otherwise.
  curl -fsSL --head --max-time 10 \
    -H "Accept: application/octet-stream" \
    "$url" >/dev/null 2>&1
}

#─── repo configuration ───────────────────────────────────────────────────────
configure_repo() {
  local repo_dir="" repo_dist=""
  case "$DISTRO" in
    ubuntu)
      repo_dir="Ubuntu"
      repo_dist="${CODENAME:-noble}"
      ;;
    debian)
      repo_dir="Debian"
      case "${VERSION_ID_NUM%%.*}" in
        11) repo_dist="bullseye" ;;
        12) repo_dist="bookworm" ;;
        13) repo_dist="trixie"   ;;
        *)  die "Unsupported Debian version: ${VERSION_ID_NUM}" ;;
      esac
      ;;
    *)
      die "Unsupported distribution: $DISTRO"
      ;;
  esac

  log "Installing repo prerequisites…"
  export DEBIAN_FRONTEND=noninteractive

  # If a previous run left a Duo sources file pointing at a codename that
  # doesn't exist (e.g. "resolute"), apt-get update will fail before we
  # ever reach the fallback logic.  Temporarily disable it.
  local stale_list=/etc/apt/sources.list.d/duosecurity.list
  local stale_disabled=""
  if [[ -f "$stale_list" ]]; then
    stale_disabled="${stale_list}.disabled.$$"
    mv "$stale_list" "$stale_disabled"
    log "Temporarily disabled stale $stale_list"
  fi

  apt-get update -qq
  apt-get install -y -qq gnupg curl ca-certificates >/dev/null

  # Restore the stale file so the idempotency check further down can see it
  if [[ -n "$stale_disabled" && -f "$stale_disabled" ]]; then
    mv "$stale_disabled" "$stale_list"
  fi

  install -d -m 0755 /etc/apt/keyrings
  local key=/etc/apt/keyrings/duo.gpg
  log "Importing Duo signing key → $key"
  curl -fsSL https://duo.com/DUO-GPG-PUBLIC-KEY.asc \
    | gpg --dearmor --yes -o "$key"
  chmod 0644 "$key"

  # ── Ubuntu codename fallback ───────────────────────────────────────────
  # If Duo's repo doesn't carry the current Ubuntu codename yet, walk back
  # through the LTS fallback chain until we find one that exists.
  if [[ "$DISTRO" == "ubuntu" ]]; then
    local original_dist="$repo_dist"
    if ! duo_repo_has_dist "$repo_dir" "$repo_dist" "$key"; then
      warn "Duo repo has no Release file for '${repo_dist}'."
      local fallback="${UBUNTU_LTS_FALLBACK[$repo_dist]:-}"
      while [[ -n "$fallback" ]]; do
        log "Trying fallback codename '${fallback}'…"
        if duo_repo_has_dist "$repo_dir" "$fallback" "$key"; then
          repo_dist="$fallback"
          log "Using Duo packages from '${repo_dist}' (compatible with ${original_dist})."
          break
        fi
        warn "Duo repo also missing '${fallback}'."
        fallback="${UBUNTU_LTS_FALLBACK[$fallback]:-}"
      done
      if [[ "$repo_dist" == "$original_dist" ]]; then
        die "No usable Duo repo found for ${original_dist} or any fallback codename."
      fi
    else
      log "Duo repo confirmed for '${repo_dist}'."
    fi
  fi

  local list=/etc/apt/sources.list.d/duosecurity.list
  local new_line="deb [arch=${ARCH} signed-by=${key}] https://pkg.duosecurity.com/${repo_dir} ${repo_dist} main"
  if [[ -f $list ]] && grep -qxF "$new_line" "$list"; then
    log "Duo apt source already configured."
  else
    [[ -f $list ]] && cp -a "$list" "${list}${BAK_SUFFIX}" && ROLLBACK_FILES+=("${list}:${list}${BAK_SUFFIX}")
    log "Writing $list"
    printf '%s\n' "$new_line" > "$list"
  fi

  # Default bypass group spec, now that we know the distro
  if [[ -z "$BYPASS_GROUP" ]]; then
    if [[ "$DISTRO" == ubuntu ]]; then
      BYPASS_GROUP="!dscadmin,*"
    else
      BYPASS_GROUP="!root,!dscadmin,*"
    fi
  fi
}

#─── package install ──────────────────────────────────────────────────────────
install_duo_unix() {
  log "Installing duo-unix…"
  export DEBIAN_FRONTEND=noninteractive
  apt-get update -qq
  apt-get install -y -qq duo-unix >/dev/null

  PAM_DUO_PATH="$(dpkg -L duo-unix 2>/dev/null | grep -E '/pam_duo\.so$' | head -n1 || true)"
  [[ -n "$PAM_DUO_PATH" && -f "$PAM_DUO_PATH" ]] \
    || die "pam_duo.so not found after install — package broken or arch mismatch?"
  log "pam_duo.so located at $PAM_DUO_PATH"
}

#─── /etc/duo/pam_duo.conf ────────────────────────────────────────────────────
write_pam_duo_conf() {
  local conf=/etc/duo/pam_duo.conf
  install -d -m 0700 -o root -g root /etc/duo

  if [[ -f "$conf" ]]; then
    cp -a "$conf" "${conf}${BAK_SUFFIX}"
    ROLLBACK_FILES+=("${conf}:${conf}${BAK_SUFFIX}")
  fi

  log "Writing $conf (mode 0600 root:root)…"
  umask 077
  cat > "$conf" <<EOF
; Duo Unix integration — managed by ${SCRIPT_NAME} (${TS})
[duo]
ikey     = ${IKEY}
skey     = ${SKEY}
host     = ${API_HOST}
failmode = ${FAILMODE}
groups   = ${BYPASS_GROUP}
autopush = yes
prompts  = 1
EOF
  chown root:root "$conf"
  chmod 0600 "$conf"
}

#─── /etc/ssh/sshd_config ─────────────────────────────────────────────────────
set_sshd_kv() {
  # Replace the (possibly-commented) directive in-place, or append.
  local cfg="$1" key="$2" val="$3"
  if grep -qE "^[[:space:]]*#?[[:space:]]*${key}([[:space:]]|$)" "$cfg"; then
    sed -i -E "s@^[[:space:]]*#?[[:space:]]*${key}([[:space:]]+.*|$).*@${key} ${val}@" "$cfg"
  else
    printf '%s %s\n' "$key" "$val" >> "$cfg"
  fi
}

configure_sshd() {
  local cfg=/etc/ssh/sshd_config
  cp -a "$cfg" "${cfg}${BAK_SUFFIX}"
  ROLLBACK_FILES+=("${cfg}:${cfg}${BAK_SUFFIX}")

  log "Hardening sshd_config (UsePAM, KbdInteractive, UseDNS, PasswordAuth)…"
  set_sshd_kv "$cfg" UsePAM yes
  set_sshd_kv "$cfg" KbdInteractiveAuthentication yes
  set_sshd_kv "$cfg" UseDNS no
  set_sshd_kv "$cfg" PasswordAuthentication no

  log "Validating sshd_config with \`sshd -t\`…"
  local err
  err="$(sshd -t 2>&1)" || die "sshd_config invalid:"$'\n'"$err"
}

#─── /etc/pam.d/sshd ──────────────────────────────────────────────────────────
configure_pam_sshd() {
  local pam=/etc/pam.d/sshd
  cp -a "$pam" "${pam}${BAK_SUFFIX}"
  ROLLBACK_FILES+=("${pam}:${pam}${BAK_SUFFIX}")

  if grep -qE "pam_duo\.so" "$pam"; then
    log "pam_duo already present in $pam — leaving stack unchanged (idempotent)."
    return 0
  fi
  if ! grep -qE '^[[:space:]]*@include[[:space:]]+common-auth' "$pam"; then
    die "Could not find '@include common-auth' anchor in $pam — manual review required."
  fi

  log "Inserting pam_duo after @include common-auth in $pam…"
  awk -v pam_path="$PAM_DUO_PATH" '
    BEGIN { inserted = 0 }
    /^[[:space:]]*@include[[:space:]]+common-auth/ && !inserted {
      print
      print ""
      print "# Duo MFA — required after primary password auth."
      print "# pam_duo will return SUCCESS for users matched by the negated"
      print "# entries in /etc/duo/pam_duo.conf '\''groups'\'' (e.g. dscadmin)."
      print "auth    required    " pam_path
      inserted = 1
      next
    }
    { print }
  ' "${pam}${BAK_SUFFIX}" > "$pam"
  chmod 0644 "$pam"
}

#─── ssh service ──────────────────────────────────────────────────────────────
restart_ssh() {
  local svc
  for s in ssh sshd; do
    if systemctl list-unit-files "${s}.service" >/dev/null 2>&1; then
      svc="$s"; break
    fi
  done
  svc="${svc:-ssh}"
  log "Reloading systemd and restarting ${svc}.service…"
  systemctl daemon-reload
  systemctl restart "${svc}.service"
  systemctl is-active --quiet "${svc}.service" \
    || die "${svc}.service is not active after restart — check 'journalctl -u ${svc}'"
}

#─── rollback on error ────────────────────────────────────────────────────────
rollback() {
  local rc=$?
  trap - ERR INT TERM
  if (( rc != 0 )) && (( ${#ROLLBACK_FILES[@]} > 0 )); then
    warn "Failure detected (rc=$rc). Restoring ${#ROLLBACK_FILES[@]} backup(s)…"
    local entry target backup
    for entry in "${ROLLBACK_FILES[@]}"; do
      target="${entry%%:*}"
      backup="${entry#*:}"
      if [[ -f "$backup" ]]; then
        cp -a "$backup" "$target" && warn "  restored $target ← $backup"
      fi
    done
    warn "Backups left in place for inspection. Run 'systemctl restart ssh' if SSH config was touched."
  fi
  exit "$rc"
}

#─── main ─────────────────────────────────────────────────────────────────────
main() {
  parse_args "$@"
  require_root
  validate_inputs
  trap rollback ERR INT TERM
  detect_distro
  configure_repo
  install_duo_unix
  write_pam_duo_conf
  configure_sshd
  configure_pam_sshd
  restart_ssh
  trap - ERR INT TERM

  local duo_ver
  duo_ver="$(dpkg-query -W -f='${Version}' duo-unix 2>/dev/null || echo '?')"

  cat <<EOF

──────────────────────────────────────────────────────────────────────
Duo Unix installation complete.
  duo-unix version : ${duo_ver}
  pam_duo module   : ${PAM_DUO_PATH}
  failmode         : ${FAILMODE}
  bypass groups    : ${BYPASS_GROUP}
  backups suffix   : ${BAK_SUFFIX}
EOF

  if (( IS_PROXMOX )); then
    cat <<'EOF'

NOTE: This script protects SSH only. The Proxmox web UI uses its own
auth realms — enable TOTP/WebAuthn under
  Datacenter → Permissions → Two-Factor
in the Proxmox UI to require MFA there as well.
EOF
  fi

  cat <<EOF

KEEP THIS SHELL OPEN. Open a NEW terminal and verify SSH login + Duo
prompt before disconnecting this one. To revert if anything is wrong:

  cp /etc/pam.d/sshd${BAK_SUFFIX}        /etc/pam.d/sshd
  cp /etc/ssh/sshd_config${BAK_SUFFIX}   /etc/ssh/sshd_config
  systemctl restart ssh

──────────────────────────────────────────────────────────────────────
EOF
}

main "$@"

Make the script Executable

chmod +x duo-setup.sh

Running the script

Run the script with the following flag:

./duo-setup.sh --stdin

Log onto the duo admin portal and go to the application called OCS Infrastructure

Copy and paste the keys in order each on a new line: - ikey - skey - api