Menu Close

Post-quantum SSH key exchange with Jamf Pro

A Jamf Pro Extension Attribute and remediation script duo

Background

As of 03-Dec-2026, macOS 27.2.1 (26B131) ships OpenSSH_10.5p1, LibreSSL 3.3.6, which supports the post-quantum hybrid key exchanges mlkem768x25519-sha256 and sntrup761x25519-sha512@openssh.com.

/etc/ssh/ssh_config.d/100-macos.conf includes /etc/ssh/crypto.conf (a symlink to crypto/apple.conf) inside Host *, which sets KexAlgorithms ^ecdh-sha2-nistp256: “Default algorithms favoring higher-performance FIPS algorithms.” The ^ moves the classical ecdh-sha2-nistp256 to the front; almost every server accepts it, so the hybrids almost never get used.

With WarnWeakCrypto on by default, ssh then prints ** WARNING: connection is not using a post-quantum key exchange algorithm. OpenSSH names the risk “store now, decrypt later”: an attacker can collect encrypted SSH sessions now and decrypt them later, once a quantum computer can break the key agreement.

Remediation

Here’s a Jamf Pro Extension Attribute to identify Macs where ssh offers a classical key exchange first and a remediation script to append a managed block to the end of the user’s ~/.ssh/config, which puts the post-quantum hybrids first.

As always, caveat emptor.

Jamf Pro Extension Attribute

Results (Data Type: String)

  • Compliant (<algo>): the first effective key exchange is a post-quantum hybrid
  • Non-Compliant (<algo>): the first effective key exchange is classical (e.g., ecdh-sha2-nistp256)
  • Not Supported: older OpenSSH without the hybrids; the remediation leaves these Macs alone, because an unknown algorithm name is a fatal ssh config error
  • No User: neither a console user nor a usable lastUserName
  • Unknown: /usr/bin/ssh missing, an invalid home directory, or ssh -G failed or timed out

Both scripts judge the result by running ssh -G pq-kex-probe.invalid as the target user, so Include, Match and Host * resolve exactly as ssh resolves them. The reserved .invalid TLD matches no Host pattern except a catch-all.

#!/bin/zsh --no-rcs

####################################################################################################
#
# SSH PQ Kex Status
#
#   Purpose: Reports whether OpenSSH offers a post-quantum hybrid key exchange first for the target
#            user (the console user; when nobody is logged in, the loginwindow lastUserName)
#
#   Jamf Pro Extension Attribute Data Type: String
#
#   Results: Compliant (<algo>)      First effective key exchange is a post-quantum hybrid
#            Non-Compliant (<algo>)  First effective key exchange is classical (e.g., Apple's
#                                    default ecdh-sha2-nistp256)
#            Not Supported           Not Compliant, and "ssh -Q kex" lacks mlkem768x25519-sha256 or
#                                    sntrup761x25519-sha512@openssh.com (older OpenSSH), so the
#                                    remediation can't add its block
#            No User                 Neither a console user nor a usable lastUserName
#            Unknown                 /usr/bin/ssh missing, home directory invalid, no work
#                                    directory, or "ssh -G" failed or timed out
#
#   Notes:   - Evaluates "ssh -G pq-kex-probe.invalid" as the target user, so ~/.ssh/config,
#              Include, Match and Host * resolve exactly as ssh resolves them
#            - Target-user resolution and key-exchange evaluation copied from
#              Remediate-SSH-PQ-Kex.zsh (0.0.3); writes only to a mktemp -d work directory, removed
#              on exit
#            - ssh silently skips a ~/.ssh/config it can't open (e.g., root-owned with mode 600), so
#              the result is the system default (Non-Compliant); one owned by another account, or
#              writable by group or others, makes ssh fail ("Bad owner or permissions"): Unknown
#            - A "Match exec" command in the user's config runs as the user at every inventory,
#              including at the login window (lastUserName)
#            - Runtime: well under 1 second; at most about 11 seconds when "ssh -G" hangs or is
#              stopped (runAsTimeoutSeconds, plus up to 1 second)
#
####################################################################################################
#
# HISTORY
#
# Version 0.0.1, 03-Dec-2026, Dan K. Snelson (@dan-snelson)
#   Original version
#
# Version 0.0.2, 03-Dec-2026, Dan K. Snelson (@dan-snelson)
#   - "ssh -G" runs under the remediation's process-tree watchdog and writes to a root-only work
#     directory, so a process the user stops can no longer hang inventory
#   - The effective key exchange is evaluated before "ssh -Q kex": an older OpenSSH that already
#     offers a hybrid first reports Compliant, not Not Supported
#
# Version 0.0.3, 03-Dec-2026, Dan K. Snelson (@dan-snelson)
#   - The watchdog uses a wall-clock deadline (SECONDS) instead of counting polls, so a 10-second
#     limit no longer stretches to about 12.6 seconds
#   - Notes: how ssh treats an unreadable or foreign-owned ~/.ssh/config; "Match exec" at every
#     inventory; runtime
#
####################################################################################################



####################################################################################################
#
# Variables
#
####################################################################################################

export PATH=/usr/bin:/bin:/usr/sbin:/sbin

# Jamf Pro reads only stdout; discard all stderr
exec 2>/dev/null

sshBinary="/usr/bin/ssh"

# Probe host for "ssh -G": the reserved .invalid TLD matches no Host pattern except a catch-all
# (e.g., "Host *"); Match blocks (e.g., exec, localnetwork, user) are still evaluated
probeHost="pq-kex-probe.invalid"

# Seconds (wall clock, plus up to 1) before a command run as the target user (e.g., "ssh -G" with a
# hung "Match exec") is killed with every process it started; macOS has no timeout command
runAsTimeoutSeconds="10"

# A first effective key exchange from this list is Compliant
pqHybridKex=(
    mlkem768x25519-sha256
    sntrup761x25519-sha512
    sntrup761x25519-sha512@openssh.com
    mlkem768nistp256-sha256
)

# "ssh -Q kex" must list both, or the remediation's managed block would be a fatal ssh config error
requiredKex=(
    mlkem768x25519-sha256
    sntrup761x25519-sha512@openssh.com
)



####################################################################################################
#
# Functions
#
####################################################################################################

# Emit exactly one Jamf Pro Extension Attribute result, then stop.
function printResult() {
    /usr/bin/printf '<result>%s</result>\n' "${1}"
    exit 0
}



# Remove the work directory
function cleanUp() {
    [[ -n "${workDir}" && -d "${workDir}" ]] && /bin/rm -Rf "${workDir}"
}



# True when an account name (Parameter 1) is no real user's session: empty, a system session or a
# name unsafe in a path
function isRejectedUser() {
    case "${1}" in
        "" | root | loginwindow | _mbsetupuser | */* | -* ) return 0 ;;
    esac
    return 1
}



# Target user: the console user; when nobody is logged in, the loginwindow lastUserName (which
# must also be a local account); returns 1 when both fail
# Sets: targetUser, userSource (console | lastUserName), runAsPrefix
function resolveTargetUser() {

    local consoleUser lastUser

    targetUser=""
    userSource=""
    runAsPrefix=()

    consoleUser=$( /usr/bin/stat -f %Su /dev/console 2>/dev/null )

    if ! isRejectedUser "${consoleUser}"; then
        targetUser="${consoleUser}"
        userSource="console"
    else
        lastUser=$( defaults read /Library/Preferences/com.apple.loginwindow.plist lastUserName 2>/dev/null )
        if ! isRejectedUser "${lastUser}" && /usr/bin/dscl . -read "/Users/${lastUser}" > /dev/null 2>&1; then
            targetUser="${lastUser}"
            userSource="lastUserName"
        else
            return 1
        fi
    fi

    # Already the target user (e.g., a non-root local test): run directly; otherwise sudo, which
    # never prompts (-n) and sets HOME to the target's home (-H) for any "Match exec" command (ssh
    # itself reads ~/.ssh/config from the account's home directory, not HOME)
    if [[ "$( /usr/bin/id -un )" != "${targetUser}" ]]; then
        runAsPrefix=( /usr/bin/sudo -n -u "${targetUser}" -H )
    fi

}



# Target user's home directory from Directory Services (falling back to ~user expansion); returns 1
# unless it is an existing directory
# Sets: targetHome, sshDir, sshConfig
function resolveTargetHome() {

    # dscl prints "NFSHomeDirectory: /Users/name", or wraps a value with spaces onto the next line
    targetHome=$( /usr/bin/dscl . -read "/Users/${targetUser}" NFSHomeDirectory 2>/dev/null \
        | /usr/bin/awk 'NR == 1 { sub(/^NFSHomeDirectory:[ ]*/, ""); if (length($0)) { print; exit }; next }
                        { sub(/^[ ]+/, ""); print; exit }' )

    # ${~...} expands ~user; an unknown user is a fatal expansion error, so contain it in a subshell
    if [[ -z "${targetHome}" ]]; then
        targetHome=$( { print -r -- ${~:-~${targetUser}} } 2>/dev/null )
    fi

    [[ "${targetHome}" == /* && -d "${targetHome}" ]] || return 1

    sshDir="${targetHome}/.ssh"
    sshConfig="${sshDir}/config"

}



# Stop a process (Parameter 1), kill its descendants (e.g., sudo's ssh and its "Match exec"
# command), then kill it
function killProcessTree() {

    local parentPID="${1}"
    local childPID

    kill -STOP "${parentPID}" 2>/dev/null

    for childPID in $( /usr/bin/pgrep -P "${parentPID}" ); do
        killProcessTree "${childPID}"
    done

    kill -KILL "${parentPID}" 2>/dev/null

}



# Run a command (all Parameters) as the target user under a watchdog; returns its exit status, or
# 124 after killing it and every process it started once runAsTimeoutSeconds pass
#   - The target user can stop (SIGSTOP) any process running as them, and "$( )" or a pipe waits
#     for every process holding it open, so callers redirect stdout to a file in the root-only work
#     directory instead
#   - The limit is a wall-clock deadline: counting 0.1-second polls ran about 25% long, because each
#     poll forks /bin/sleep; SECONDS counts whole seconds, so "+ 1" makes the limit at least
#     runAsTimeoutSeconds and at most 1 second more
# Requires: resolveTargetUser, killProcessTree
function runAsTargetUser() {

    local childPID
    local deadline=$(( SECONDS + runAsTimeoutSeconds + 1 ))

    "${runAsPrefix[@]}" "$@" &
    childPID=$!

    while kill -0 "${childPID}" 2>/dev/null; do
        if (( SECONDS >= deadline )); then
            killProcessTree "${childPID}"
            return 124
        fi
        /bin/sleep 0.1
    done

    wait "${childPID}"

}



# First effective key exchange for the target user, as ssh itself resolves it ("ssh -G" reads
# ~/.ssh/config, Include, Match and Host *, then the system defaults), under runAsTargetUser's
# watchdog; ssh writes to a file in the root-only work directory
# Sets: firstKex, kexState (ok | failed | timeout); returns 1 unless ok
# Requires: workDir
function effectiveKex() {

    local kexFile="${workDir}/ssh-G.out"
    local kexRC kexLine

    firstKex=""

    runAsTargetUser "${sshBinary}" -G "${probeHost}" < /dev/null > "${kexFile}" 2>/dev/null
    kexRC=$?

    if (( kexRC == 124 )); then
        kexState="timeout"
        return 1
    elif (( kexRC != 0 )); then
        kexState="failed"
        return 1
    fi

    # "kexalgorithms a,b,c": keep the first comma field
    kexLine=$( /usr/bin/awk '$1 == "kexalgorithms" { print $2; exit }' "${kexFile}" )
    firstKex="${kexLine%%,*}"

    if [[ ! "${firstKex}" =~ ^[A-Za-z0-9@._+-]+$ ]]; then
        firstKex=""
        kexState="failed"
        return 1
    fi

    kexState="ok"

}



# True when this OpenSSH supports every required hybrid ("ssh -Q kex")
function pqSupported() {

    local supportedKex requiredAlgorithm

    supportedKex=$( "${sshBinary}" -Q kex 2>/dev/null ) || return 1

    for requiredAlgorithm in "${requiredKex[@]}"; do
        print -r -- "${supportedKex}" | /usr/bin/grep -qxF -- "${requiredAlgorithm}" || return 1
    done

}



# True when a key exchange (Parameter 1) is a post-quantum hybrid
function isPqHybrid() {
    # (Ie): index of an exact match, or 0
    (( ${pqHybridKex[(Ie)${1}]} ))
}



####################################################################################################
#
# Status Check
#
####################################################################################################

resolveTargetUser || printResult "No User"

[[ -x "${sshBinary}" ]] || printResult "Unknown"

resolveTargetHome || printResult "Unknown"

# Root-only work directory for "ssh -G" output, removed on exit
trap cleanUp EXIT
workDir=$( /usr/bin/mktemp -d -t "SSH-PQ-Kex-Status" ) || printResult "Unknown"
/bin/chmod 700 "${workDir}" || printResult "Unknown"

effectiveKex || printResult "Unknown"

isPqHybrid "${firstKex}" && printResult "Compliant (${firstKex})"

pqSupported || printResult "Not Supported"

printResult "Non-Compliant (${firstKex})"

Jamf Pro Remediation Script

What changes for users

The remediation appends a managed Host * block to the end of the user’s ~/.ssh/config, between # BEGIN Prefer post-quantum hybrid key exchange (managed by Jamf Pro) and its matching # END marker. It holds one line: KexAlgorithms ^mlkem768x25519-sha256,sntrup761x25519-sha512@openssh.com

ssh reads ~/.ssh/config before /etc/ssh/ssh_config, and the first value it obtains wins, so the block overrides Apple’s crypto.conf. A block at the top of the file would also override every per-host KexAlgorithms further down (e.g., a legacy +diffie-hellman-group14-sha1 pin for an old server); at the end, it still comes before /etc/ssh/ssh_config, and a per-host KexAlgorithms above it keeps winning for that host.

The ^ only moves the hybrids to the front, so servers that support one now negotiate it. The classical algorithms stay in the list, so servers without the hybrids still connect (and ssh still warns about them). Nothing changes on any server.

Before any write, the script takes a backup (config.bak.<timestamp>, mode 600) and keeps it. To undo, delete the managed block; if the block is all the file holds, delete ~/.ssh/config.

How it stays safe

  • Runs as a Jamf Pro policy script, as root, with no Script Parameters; exit codes are in the script header
  • The target user is the console user; when nobody is logged in, it’s loginwindow’s lastUserName
  • Every read and write inside the user’s home runs as the user (sudo -n -u <user> -H)
  • Root never changes ownership or mode through a path the user controls; a hard link or a swapped symlink could otherwise point root at any root-owned file
  • Every command run as the user is under a watchdog; after 10 seconds (plus up to 1), it kills the whole process tree, so a hung or stopped Match exec can’t stall a policy or inventory
  • Output comes back through files in a root-only work directory, never through a pipe the user could hold open
  • A config that already fails ssh -G is left alone, a write that breaks ssh -G is rolled back, and at most 1 MiB of the config is read

Tested

Run as root on two Macs: the EA reported Non-Compliant, the remediation exited 0, then the EA reported Compliant. A second remediation run made no change and exited 0. These edge cases passed:

  • Root-owned ~/.ssh (handed to the user)
  • Root-owned config with mode 644 (rewritten)
  • Root-owned config with mode 600 (exit 1, “fix manually”)
  • Config owned by another account (rewritten)
  • Hung and SIGSTOPped Match exec (timed out at about 11 seconds, no orphaned processes)
  • A hard-link canary pointed at a root-owned file (it stayed root:wheel)

The login-window (lastUserName) path has not been tested yet.

#!/bin/zsh --no-rcs
# shellcheck shell=bash

####################################################################################################
#
# Remediate SSH Post-Quantum Kex
#
#   Purpose: Makes OpenSSH offer the post-quantum hybrid key exchanges first for the target user
#            by appending a managed "Host *" block to the END of ~/.ssh/config:
#
#              # BEGIN Prefer post-quantum hybrid key exchange (managed by Jamf Pro)
#              Host *
#                  KexAlgorithms ^mlkem768x25519-sha256,sntrup761x25519-sha512@openssh.com
#              # END Prefer post-quantum hybrid key exchange (managed by Jamf Pro)
#
#   Usage:   Jamf Pro: Policy script; runs as root; no Script Parameters
#
#            Local:    sudo zsh Remediate-SSH-PQ-Kex.zsh
#
#   Exit:    0 = compliant (already, or after the write), nothing to do (no user) or not supported
#            1 = failure: not root; a symlink (unless already compliant); a config that already
#                fails "ssh -G", is unreadable or is over 1 MiB; a write failure (rolled back once
#                the file was replaced); a shadowed block; or a broken config that was rolled back
#
#   Notes:
#   - Apple's /etc/ssh/crypto.conf (a symlink to crypto/apple.conf) sets
#     "KexAlgorithms ^ecdh-sha2-nistp256", included inside "Host *" by
#     /etc/ssh/ssh_config.d/100-macos.conf, so ssh offers the classical ecdh-sha2-nistp256 first
#   - ~/.ssh/config is read before /etc/ssh/ssh_config and OpenSSH keeps the first value it reads,
#     so the user's file wins over Apple's crypto.conf
#   - The block goes at the END of the file: a top-level line (or a block at the top) would also
#     override every per-host KexAlgorithms later in the file (e.g., a legacy
#     "+diffie-hellman-group14-sha1" pin for an old server); at the end it still precedes
#     /etc/ssh/ssh_config
#   - Target user: the console user; when nobody is logged in, the loginwindow lastUserName
#   - Verdicts come from "ssh -G pq-kex-probe.invalid" run as the target user, so Include, Match and
#     Host * resolve exactly as ssh resolves them; the .invalid TLD matches no Host pattern except a
#     catch-all, but Match blocks (e.g., exec, localnetwork, user) are still evaluated
#   - Older OpenSSH without the hybrids is left alone: an unknown algorithm name is a fatal ssh
#     config error
#   - Every read and write inside the user's home runs as the target user (sudo -u) under a
#     watchdog that kills the whole process tree; output comes back through files in a root-only
#     work directory, never through a pipe the user could hold open
#   - Root never changes ownership or mode through a path the user controls (a hard link or a
#     swapped symlink could point it at any root-owned file): modes are set as the target user; a
#     ~/.ssh owned by someone else is given to the user from inside it, once "pwd -P" confirms it;
#     a ~/.ssh/config owned by someone else is rewritten by the target user
#   - ssh silently skips a ~/.ssh/config it can't open, so a root-owned config with mode 600 passes
#     the pre-check, then fails the read as the target user (exit 1; fix it manually); one owned
#     by another account, or writable by group or others, makes "ssh -G" fail ("Bad owner or
#     permissions"), and the target user rewrites it
#   - An already-compliant user is left alone, unless a managed block has to move back to the end
#     (e.g., the user appended a Host block after it) or ~/.ssh/config needs a new owner
#   - Backups (config.bak.<timestamp>, mode 600) are made only before a write and are kept
#   - Runtime: about 1 second; each command run as the target user is killed after
#     runAsTimeoutSeconds (10), plus up to 1 second
#   - Out of scope: other local accounts; a per-host KexAlgorithms the user set on purpose
#
####################################################################################################
#
# HISTORY
#
# Version 0.0.1, 03-Dec-2026, Dan K. Snelson (@dan-snelson)
#   - Original version
#
# Version 0.0.2, 03-Dec-2026, Dan K. Snelson (@dan-snelson)
#   - Root no longer changes ownership or mode through a path the user controls: modes are set as
#     the target user; ~/.ssh is given to the user only from inside it; a ~/.ssh/config owned by
#     someone else is rewritten by the user
#   - Every command run as the target user is under a process-tree watchdog, with output returned
#     through root-only files, so a process the user stops can no longer hang the policy
#   - ~/.ssh/config is read with a 1 MiB cap
#   - A config that already fails "ssh -G" is left alone (no write, rollback or new backup)
#   - Already-compliant runs now fix the mode of ~/.ssh and move a managed block back to the end of
#     the file; an already-compliant symlinked ~/.ssh or ~/.ssh/config exits 0
#   - Markers match with leading or trailing whitespace; a replaced but unverified write is rolled
#     back; logged config lines can no longer add log entries
#
# Version 0.0.3, 03-Dec-2026, Dan K. Snelson (@dan-snelson)
#   - The watchdog uses a wall-clock deadline (SECONDS) instead of counting polls, so a 10-second
#     limit no longer stretches to about 12.6 seconds
#   - Backups are mode 600 (cp -p kept a foreign-owned original's 644)
#   - Clearer log wording when an existing managed block is already current
#   - Notes: how ssh treats an unreadable or foreign-owned ~/.ssh/config; backups; runtime
#
####################################################################################################



####################################################################################################
#
# Global Variables
#
####################################################################################################

export PATH=/usr/bin:/bin:/usr/sbin:/sbin

# Script Version
scriptVersion="0.0.3"

# Client-side Log
scriptLog="/var/log/org.churchofjesuschrist.log"

# Elapsed Time
SECONDS="0"



# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Organization Variables
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

# Script Human-readabale Name
humanReadableScriptName="Remediate SSH Post-Quantum Kex"

# Organization's Script Name
organizationScriptName="RSPK"



# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# SSH Variables (shared with SSH-PQ-Kex-Status.zsh; keep in sync)
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

sshBinary="/usr/bin/ssh"

# Probe host for "ssh -G": the reserved .invalid TLD matches no Host pattern except a catch-all
# (e.g., "Host *"); Match blocks (e.g., exec, localnetwork, user) are still evaluated
probeHost="pq-kex-probe.invalid"

# Seconds (wall clock, plus up to 1) before a command run as the target user (e.g., "ssh -G" with a
# hung "Match exec") is killed with every process it started; macOS has no timeout command
runAsTimeoutSeconds="10"

# A first effective key exchange from this list is Compliant
pqHybridKex=(
    mlkem768x25519-sha256
    sntrup761x25519-sha512
    sntrup761x25519-sha512@openssh.com
    mlkem768nistp256-sha256
)

# "ssh -Q kex" must list both, or the managed block would be a fatal ssh config error
requiredKex=(
    mlkem768x25519-sha256
    sntrup761x25519-sha512@openssh.com
)



# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Managed Block Variables
# (markers are matched as whole lines, ignoring leading and trailing whitespace, so an otherwise
# edited marker is treated as user content)
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

managedBlockBegin="# BEGIN Prefer post-quantum hybrid key exchange (managed by Jamf Pro)"
managedBlockEnd="# END Prefer post-quantum hybrid key exchange (managed by Jamf Pro)"
managedKexAlgorithms="^mlkem768x25519-sha256,sntrup761x25519-sha512@openssh.com"

# Largest ~/.ssh/config read (bytes); a larger file is left alone
maxConfigBytes="1048576"



####################################################################################################
#
# Functions
#
####################################################################################################

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Client-side Logging
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

function updateScriptLog() {
    if [[ -w "${scriptLog}" ]]; then
        echo "${organizationScriptName} ($scriptVersion): $( date +%Y-%m-%d\ %H:%M:%S ) - ${1}" | tee -a "${scriptLog}"
    else
        echo "${organizationScriptName} ($scriptVersion): $( date +%Y-%m-%d\ %H:%M:%S ) - ${1}"
    fi
}

function preFlight() {
    updateScriptLog "[PRE-FLIGHT]      ${1}"
}

function logComment() {
    updateScriptLog "                  ${1}"
}

function notice() {
    updateScriptLog "[NOTICE]          ${1}"
}

function info() {
    updateScriptLog "[INFO]            ${1}"
}

function errorOut(){
    updateScriptLog "[ERROR]           ${1}"
}

function warning() {
    updateScriptLog "[WARNING]         ${1}"
    let errorCount++
}

function fatal() {
    updateScriptLog "[FATAL ERROR]     ${1}"
    exit 1
}

function quitOut(){
    updateScriptLog "[QUIT]            ${1}"
}



# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Exit with code (Parameter 1) and summary (Parameter 2)
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

function exitWith() {
    info "Elapsed Time: $(printf '%dh:%dm:%ds\n' $((SECONDS/3600)) $((SECONDS%3600/60)) $((SECONDS%60)))"
    quitOut "${2} (exit ${1})"
    exit "${1}"
}



# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Shared with SSH-PQ-Kex-Status.zsh (keep in sync): isRejectedUser, resolveTargetUser,
# resolveTargetHome, killProcessTree, runAsTargetUser, effectiveKex, pqSupported, isPqHybrid
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# True when an account name (Parameter 1) is no real user's session: empty, a system session or a
# name unsafe in a path
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

function isRejectedUser() {
    case "${1}" in
        "" | root | loginwindow | _mbsetupuser | */* | -* ) return 0 ;;
    esac
    return 1
}



# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Target user: the console user; when nobody is logged in, the loginwindow lastUserName (which
# must also be a local account); returns 1 when both fail
# Sets: targetUser, userSource (console | lastUserName), runAsPrefix
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

function resolveTargetUser() {

    local consoleUser lastUser

    targetUser=""
    userSource=""
    runAsPrefix=()

    consoleUser=$( /usr/bin/stat -f %Su /dev/console 2>/dev/null )

    if ! isRejectedUser "${consoleUser}"; then
        targetUser="${consoleUser}"
        userSource="console"
    else
        lastUser=$( defaults read /Library/Preferences/com.apple.loginwindow.plist lastUserName 2>/dev/null )
        if ! isRejectedUser "${lastUser}" && /usr/bin/dscl . -read "/Users/${lastUser}" > /dev/null 2>&1; then
            targetUser="${lastUser}"
            userSource="lastUserName"
        else
            return 1
        fi
    fi

    # Already the target user (e.g., a non-root local test): run directly; otherwise sudo, which
    # never prompts (-n) and sets HOME to the target's home (-H) for any "Match exec" command (ssh
    # itself reads ~/.ssh/config from the account's home directory, not HOME)
    if [[ "$( /usr/bin/id -un )" != "${targetUser}" ]]; then
        runAsPrefix=( /usr/bin/sudo -n -u "${targetUser}" -H )
    fi

}



# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Target user's home directory from Directory Services (falling back to ~user expansion); returns 1
# unless it is an existing directory
# Sets: targetHome, sshDir, sshConfig
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

function resolveTargetHome() {

    # dscl prints "NFSHomeDirectory: /Users/name", or wraps a value with spaces onto the next line
    targetHome=$( /usr/bin/dscl . -read "/Users/${targetUser}" NFSHomeDirectory 2>/dev/null \
        | /usr/bin/awk 'NR == 1 { sub(/^NFSHomeDirectory:[ ]*/, ""); if (length($0)) { print; exit }; next }
                        { sub(/^[ ]+/, ""); print; exit }' )

    # ${~...} expands ~user; an unknown user is a fatal expansion error, so contain it in a subshell
    if [[ -z "${targetHome}" ]]; then
        targetHome=$( { print -r -- ${~:-~${targetUser}} } 2>/dev/null )
    fi

    [[ "${targetHome}" == /* && -d "${targetHome}" ]] || return 1

    sshDir="${targetHome}/.ssh"
    sshConfig="${sshDir}/config"

}



# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Stop a process (Parameter 1), kill its descendants (e.g., sudo's ssh and its "Match exec"
# command), then kill it
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

function killProcessTree() {

    local parentPID="${1}"
    local childPID

    kill -STOP "${parentPID}" 2>/dev/null

    for childPID in $( /usr/bin/pgrep -P "${parentPID}" ); do
        killProcessTree "${childPID}"
    done

    kill -KILL "${parentPID}" 2>/dev/null

}



# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Run a command (all Parameters) as the target user under a watchdog; returns its exit status, or
# 124 after killing it and every process it started once runAsTimeoutSeconds pass
#   - The target user can stop (SIGSTOP) any process running as them, and "$( )" or a pipe waits
#     for every process holding it open, so callers redirect stdout to a file in the root-only work
#     directory instead
#   - The limit is a wall-clock deadline: counting 0.1-second polls ran about 25% long, because each
#     poll forks /bin/sleep; SECONDS counts whole seconds, so "+ 1" makes the limit at least
#     runAsTimeoutSeconds and at most 1 second more
# Requires: resolveTargetUser, killProcessTree
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

function runAsTargetUser() {

    local childPID
    local deadline=$(( SECONDS + runAsTimeoutSeconds + 1 ))

    "${runAsPrefix[@]}" "$@" &
    childPID=$!

    while kill -0 "${childPID}" 2>/dev/null; do
        if (( SECONDS >= deadline )); then
            killProcessTree "${childPID}"
            return 124
        fi
        /bin/sleep 0.1
    done

    wait "${childPID}"

}



# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# First effective key exchange for the target user, as ssh itself resolves it ("ssh -G" reads
# ~/.ssh/config, Include, Match and Host *, then the system defaults), under runAsTargetUser's
# watchdog; ssh writes to a file in the root-only work directory
# Sets: firstKex, kexState (ok | failed | timeout); returns 1 unless ok
# Requires: workDir
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

function effectiveKex() {

    local kexFile="${workDir}/ssh-G.out"
    local kexRC kexLine

    firstKex=""

    runAsTargetUser "${sshBinary}" -G "${probeHost}" < /dev/null > "${kexFile}" 2>/dev/null
    kexRC=$?

    if (( kexRC == 124 )); then
        kexState="timeout"
        return 1
    elif (( kexRC != 0 )); then
        kexState="failed"
        return 1
    fi

    # "kexalgorithms a,b,c": keep the first comma field
    kexLine=$( /usr/bin/awk '$1 == "kexalgorithms" { print $2; exit }' "${kexFile}" )
    firstKex="${kexLine%%,*}"

    if [[ ! "${firstKex}" =~ ^[A-Za-z0-9@._+-]+$ ]]; then
        firstKex=""
        kexState="failed"
        return 1
    fi

    kexState="ok"

}



# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# True when this OpenSSH supports every required hybrid ("ssh -Q kex")
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

function pqSupported() {

    local supportedKex requiredAlgorithm

    supportedKex=$( "${sshBinary}" -Q kex 2>/dev/null ) || return 1

    for requiredAlgorithm in "${requiredKex[@]}"; do
        print -r -- "${supportedKex}" | /usr/bin/grep -qxF -- "${requiredAlgorithm}" || return 1
    done

}



# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# True when a key exchange (Parameter 1) is a post-quantum hybrid
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

function isPqHybrid() {
    # (Ie): index of an exact match, or 0
    (( ${pqHybridKex[(Ie)${1}]} ))
}



# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Remove work directory and any staged config
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

function cleanUp() {
    [[ -n "${workDir}" && -d "${workDir}" ]] && rm -Rf "${workDir}"
    [[ -n "${stagedFile}" ]] && runAsTargetUser /bin/rm -f "${stagedFile}"
}



# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Content transform: write a config (Parameter 1; a missing file counts as empty) to an output file
# (Parameter 2) with any managed block removed and a fresh one appended at the end
#   - Every other line is kept, including CRLF line endings; a marker line may carry leading or
#     trailing whitespace or a CR
#   - A BEGIN marker without a matching END marker is kept as user content, never deleted to EOF
#   - Trailing blank (whitespace-only) lines are dropped and a missing final newline is added; one
#     blank line then separates the content from the block (written with LF line endings); with no
#     content, the block alone is written
#   - Blank lines around a block removed from mid-file are kept
#   - Running it on its own output changes nothing
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

function composeManagedConfig() {

    local sourceFile="${1}"
    local outputFile="${2}"

    [[ -f "${sourceFile}" ]] || sourceFile="/dev/null"

    # LC_ALL=C: compare and copy bytes, whatever the encoding
    LC_ALL=C /usr/bin/awk \
        -v blockBegin="${managedBlockBegin}" \
        -v blockEnd="${managedBlockEnd}" \
        -v kexAlgorithms="${managedKexAlgorithms}" '

        # Print a line, holding back blank lines until a non-blank line follows them
        function emit(line,    i) {
            if (line ~ /^[ \t\r]*$/) {
                heldBlanks[++heldCount] = line
                return
            }
            for (i = 1; i <= heldCount; i++) print heldBlanks[i]
            heldCount = 0
            print line
            hasContent = 1
        }

        # Keep the lines of a candidate block that never reached its END marker
        function releaseBlock(    i) {
            for (i = 1; i <= blockCount; i++) emit(blockLines[i])
            blockCount = 0
            inBlock = 0
        }

        {
            marker = $0
            sub(/^[ \t]+/, "", marker)
            sub(/[ \t\r]+$/, "", marker)

            if (marker == blockBegin) {
                # A second BEGIN means the first one was never closed
                if (inBlock) releaseBlock()
                inBlock = 1
                blockLines[++blockCount] = $0
                next
            }

            if (inBlock) {
                if (marker == blockEnd) {
                    blockCount = 0
                    inBlock = 0
                } else {
                    blockLines[++blockCount] = $0
                }
                next
            }

            emit($0)
        }

        END {
            if (inBlock) releaseBlock()
            if (hasContent) print ""
            print blockBegin
            print "Host *"
            print "    KexAlgorithms " kexAlgorithms
            print blockEnd
        }

    ' "${sourceFile}" > "${outputFile}"

}



# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# True when a file (Parameter 1) holds a managed BEGIN marker, matched as composeManagedConfig
# matches it
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

function hasManagedBlock() {

    LC_ALL=C /usr/bin/awk -v blockBegin="${managedBlockBegin}" '
        {
            sub(/^[ \t]+/, "")
            sub(/[ \t\r]+$/, "")
            if ($0 == blockBegin) { found = 1; exit }
        }
        END { exit !found }
    ' "${1}"

}



# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Log a path's (Parameter 1) mode and owner before (Parameter 2) and after (Parameter 3)
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

function logOwnership() {
    if [[ "${2}" != "${3}" ]]; then
        logComment "${1}: ${2} -> ${3}"
    else
        logComment "${1}: ${3} (unchanged)"
    fi
}



# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Make sshDir owned by the target user with mode 700. Root never acts on a path the user controls
# (a hard link or a swapped symlink could point it at any root-owned file): it changes the owner
# only from inside the directory ("."), once "pwd -P" confirms it is the real ~/.ssh; the target
# user sets the mode
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

function secureSshDir() {

    local before after

    before=$( stat -f '%Sp %Su:%Sg' "${sshDir}" )

    if [[ "$( stat -f %Su "${sshDir}" )" != "${targetUser}" ]]; then
        if ! ( cd -P -- "${sshDir}" 2>/dev/null \
            && [[ "$( pwd -P )" == "${targetHome:A}/.ssh" ]] \
            && chown "${targetUser}:${targetGroup}" . ); then
            errorOut "Unable to give ${sshDir} to ${targetUser}"
            return 1
        fi
    fi

    if ! runAsTargetUser /bin/chmod 700 "${sshDir}" < /dev/null; then
        errorOut "Unable to set mode 700 on ${sshDir} as ${targetUser}"
        return 1
    fi

    after=$( stat -f '%Sp %Su:%Sg' "${sshDir}" )
    logOwnership "${sshDir}" "${before}" "${after}"

}



# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Mode 600 on sshConfig, set as the target user when they own it; returns 2 when someone else owns
# it (root never changes the owner of a file the user could swap for a hard link to a root-owned
# file; the caller has the target user rewrite it instead)
# Sets: configOwner
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

function secureSshConfig() {

    local before after

    before=$( stat -f '%Sp %Su:%Sg' "${sshConfig}" )
    configOwner=$( stat -f %Su "${sshConfig}" )

    if [[ "${configOwner}" != "${targetUser}" ]]; then
        logComment "${sshConfig}: ${before} (${targetUser} must rewrite it)"
        return 2
    fi

    if [[ "$( stat -f %Lp "${sshConfig}" )" != "600" ]]; then
        if ! runAsTargetUser /bin/chmod 600 "${sshConfig}" < /dev/null; then
            errorOut "Unable to set mode 600 on ${sshConfig} as ${targetUser}"
            return 1
        fi
    fi

    after=$( stat -f '%Sp %Su:%Sg' "${sshConfig}" )
    logOwnership "${sshConfig}" "${before}" "${after}"

}



# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Timestamped, verified backup of sshConfig, made as the target user; never overwrites
#   - "cp -p" as the user keeps the original's mode (e.g., 644 on a foreign-owned config) but can't
#     keep another owner, so the backup is then set to mode 600
# Sets: backupFile
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

function backupConfig() {

    backupFile="${sshConfig}.bak.$( date +%Y%m%d-%H%M%S )"

    if [[ -e "${backupFile}" || -L "${backupFile}" ]]; then
        errorOut "Backup ${backupFile} already exists; refusing to overwrite"
        backupFile=""
        return 1
    fi

    if ! runAsTargetUser /bin/cp -p "${sshConfig}" "${backupFile}" \
        || ! runAsTargetUser /usr/bin/cmp -s "${sshConfig}" "${backupFile}" \
        || ! runAsTargetUser /bin/chmod 600 "${backupFile}"; then
        errorOut "Unable to create verified backup ${backupFile}"
        backupFile=""
        return 1
    fi

    logComment "Backup: ${backupFile}"

}



# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Atomically replace sshConfig with a root-owned file (Parameter 1), as the target user: stream it
# into a mktemp file in sshDir (same filesystem; mktemp creates it 0600 and owned by the user),
# verify it, then rename it over sshConfig
# Sets: configReplaced (yes once sshConfig has been replaced, so the caller knows to roll back)
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

function writeConfig() {

    local sourceFile="${1}"
    local stagedPathFile="${workDir}/staged.path"

    configReplaced="no"

    # The staged path comes back through a root-only file, never "$( )" (see runAsTargetUser)
    runAsTargetUser /usr/bin/mktemp "${sshDir}/.config.XXXXXX" < /dev/null > "${stagedPathFile}"
    stagedFile=$( < "${stagedPathFile}" )
    if [[ "${stagedFile}" != "${sshDir}"/.config.?????? || ! -f "${stagedFile}" || -L "${stagedFile}" ]]; then
        errorOut "Unable to create a staging file in ${sshDir}"
        stagedFile=""
        return 1
    fi

    if ! runAsTargetUser /usr/bin/tee "${stagedFile}" < "${sourceFile}" > /dev/null \
        || ! runAsTargetUser /usr/bin/cmp -s - "${stagedFile}" < "${sourceFile}"; then
        errorOut "Unable to stage the new content in ${stagedFile}"
        return 1
    fi

    if ! runAsTargetUser /bin/mv -f "${stagedFile}" "${sshConfig}" < /dev/null; then
        errorOut "Unable to rename ${stagedFile} over ${sshConfig}"
        return 1
    fi

    stagedFile=""
    configReplaced="yes"

    if ! runAsTargetUser /usr/bin/cmp -s - "${sshConfig}" < "${sourceFile}"; then
        errorOut "${sshConfig} does not match the new content after the write"
        return 1
    fi

    logComment "Wrote ${sshConfig}"

}



# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Undo the write: restore backupFile, or remove the new sshConfig when there was no original
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

function rollBack() {

    if [[ -n "${backupFile}" ]]; then
        warning "Rolling back ${sshConfig} from ${backupFile}"
        if runAsTargetUser /bin/cp -p "${backupFile}" "${sshConfig}" \
            && runAsTargetUser /usr/bin/cmp -s "${backupFile}" "${sshConfig}"; then
            logComment "Rolled back; ${sshConfig} matches ${backupFile}"
        else
            errorOut "ROLLBACK FAILED; restore manually as ${targetUser}: cp -p '${backupFile}' '${sshConfig}'"
        fi
    else
        warning "Removing new ${sshConfig} (no original existed)"
        if runAsTargetUser /bin/rm -f "${sshConfig}"; then
            logComment "Removed ${sshConfig}"
        else
            errorOut "ROLLBACK FAILED; remove manually as ${targetUser}: rm '${sshConfig}'"
        fi
    fi

}



####################################################################################################
#
# Pre-flight Checks
#
####################################################################################################

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Pre-flight Check: Client-side Logging
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

if [[ ! -f "${scriptLog}" && $(id -u) -eq 0 ]]; then
    touch "${scriptLog}"
    if [[ -f "${scriptLog}" ]]; then
        preFlight "Created specified scriptLog: ${scriptLog}"
    else
        fatal "Unable to create specified scriptLog '${scriptLog}'; exiting."
    fi
elif [[ -w "${scriptLog}" ]]; then
    preFlight "Specified scriptLog '${scriptLog}' exists; writing log entries to it"
else
    preFlight "Specified scriptLog '${scriptLog}' not writable; logging to stdout only"
fi



# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Pre-flight Check: Logging Preamble
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

preFlight "\n\n###\n# $humanReadableScriptName (${scriptVersion})\n###\n"
preFlight "Initiating …"
preFlight "macOS $( sw_vers -productVersion ) ($( sw_vers -buildVersion ))"



# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Pre-flight Check: Confirm script is running as root
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

if [[ $(id -u) -ne 0 ]]; then
    fatal "This script must be run as root; exiting."
fi



# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Pre-flight Check: Target User (console user; else loginwindow lastUserName)
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

if ! resolveTargetUser; then
    preFlight "No console user and no usable lastUserName"
    exitWith 0 "No target user; nothing to do"
fi

preFlight "Target User: ${targetUser} (${userSource})"

# Primary group for chown
targetGroup=$( id -gn "${targetUser}" 2>/dev/null )
[[ -n "${targetGroup}" ]] || fatal "Unable to determine the primary group of '${targetUser}'; exiting."



# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Pre-flight Check: ssh and Home Directory
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

[[ -x "${sshBinary}" ]] || fatal "${sshBinary} not found; exiting."
preFlight "$( "${sshBinary}" -V 2>&1 )"

resolveTargetHome || fatal "Home directory of '${targetUser}' is missing or invalid; exiting."
preFlight "Home Directory: ${targetHome}"



# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Pre-flight Check: Post-quantum Hybrid Support
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

if ! pqSupported; then
    warning "'${sshBinary} -Q kex' lacks ${(j:, :)requiredKex}; writing the block would break ssh"
    exitWith 0 "Not Supported; no changes made"
fi



# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Pre-flight Check: Work Directory
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

workDir=$( mktemp -d -t "${organizationScriptName}" ) || fatal "Unable to create work directory; exiting."
trap cleanUp EXIT
chmod 700 "${workDir}" || fatal "Unable to secure work directory; exiting."



# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Pre-flight Check: Complete
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

preFlight "Complete!"



####################################################################################################
#
# Program
#
####################################################################################################

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Safety: a symlinked ~/.ssh or ~/.ssh/config (e.g., into a dotfiles repo) is never followed or
# written; any other non-directory ~/.ssh or non-file config stops the script
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

notice "Safety checks"

linkedPath=""

if [[ -L "${sshDir}" ]]; then
    linkedPath="${sshDir}"
elif [[ -e "${sshDir}" && ! -d "${sshDir}" ]]; then
    errorOut "${sshDir} exists but is not a directory"
    exitWith 1 "Unexpected ${sshDir}; no changes made"
elif [[ -L "${sshConfig}" ]]; then
    linkedPath="${sshConfig}"
elif [[ -e "${sshConfig}" && ! -f "${sshConfig}" ]]; then
    errorOut "${sshConfig} exists but is not a regular file"
    exitWith 1 "Unexpected ${sshConfig}; no changes made"
fi

if [[ -n "${linkedPath}" ]]; then
    logComment "${linkedPath} is a symlink; it is never changed"
else
    logComment "No symlinks; ${sshConfig} is $( [[ -f "${sshConfig}" ]] && echo "a regular file" || echo "absent" )"
fi



# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Ownership and mode of what already exists, before ssh reads it (a config with loose permissions
# makes "ssh -G" fail); a config owned by someone else is rewritten by the target user below
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

notice "Ownership and mode"

needsRewrite="no"
configOwner=""

if [[ "${linkedPath}" != "${sshDir}" && -d "${sshDir}" ]]; then
    secureSshDir || exitWith 1 "Unable to correct ownership or mode of ${sshDir}"
fi

if [[ -z "${linkedPath}" && -f "${sshConfig}" ]]; then
    secureSshConfig
    case $? in
        0 ) ;;
        2 ) needsRewrite="yes" ;;
        * ) exitWith 1 "Unable to correct the mode of ${sshConfig}" ;;
    esac
fi



# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Pre-check: effective key exchange before any content change; a config that already fails is left
# alone, unless the target user must rewrite it anyway
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

notice "Pre-check: 'ssh -G ${probeHost}' as ${targetUser}"

if effectiveKex; then
    kexBefore="${firstKex}"
    logComment "First key exchange: ${kexBefore}"
elif [[ "${needsRewrite}" == "yes" ]]; then
    kexBefore="unknown (${kexState})"
    warning "Unable to evaluate the effective key exchange (${kexState}); continuing, because ${targetUser} must rewrite ${sshConfig}"
else
    errorOut "'ssh -G ${probeHost}' as ${targetUser}: ${kexState}"
    exitWith 1 "Unable to evaluate the current ssh config (${kexState}); no changes made"
fi

alreadyCompliant="no"
[[ "${kexState}" == "ok" ]] && isPqHybrid "${firstKex}" && alreadyCompliant="yes"



# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Symlinked ~/.ssh or ~/.ssh/config: compliant is a no-op; otherwise refuse
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

if [[ -n "${linkedPath}" ]]; then
    if [[ "${alreadyCompliant}" == "yes" ]]; then
        exitWith 0 "Compliant (${kexBefore}); symlinked ${linkedPath} left alone"
    fi
    errorOut "${linkedPath} is a symlink"
    exitWith 1 "Refusing to follow a symlink; no changes made"
fi



# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Read the current content as the target user (at most maxConfigBytes) into the root-only work
# directory
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

notice "Build new ${sshConfig}"

currentConfig="${workDir}/config.current"
newConfig="${workDir}/config.new"
managedPresent="no"

if [[ -f "${sshConfig}" ]]; then
    configExisted="yes"
    if ! runAsTargetUser /usr/bin/head -c "$(( maxConfigBytes + 1 ))" "${sshConfig}" < /dev/null > "${currentConfig}"; then
        exitWith 1 "Unable to read ${sshConfig} as ${targetUser} (owner: ${configOwner:-unknown}); fix it manually; no changes made"
    fi
    if (( $( stat -f %z "${currentConfig}" ) > maxConfigBytes )); then
        exitWith 1 "${sshConfig} is larger than ${maxConfigBytes} bytes; no changes made"
    fi
    if hasManagedBlock "${currentConfig}"; then
        managedPresent="yes"
        logComment "Existing managed block found; checking that it is current and last in the file"
    fi
else
    configExisted="no"
    : > "${currentConfig}"
fi



# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Already compliant through the system default or the user's own setting: nothing to manage
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

if [[ "${alreadyCompliant}" == "yes" && "${managedPresent}" == "no" && "${needsRewrite}" == "no" ]]; then
    exitWith 0 "Compliant (${kexBefore}); no change needed"
fi



# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Build the new content in the root-only work directory; a managed block that is not last (e.g.,
# the user appended a Host block after it) moves back to the end, so it never overrides a later
# per-host KexAlgorithms
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

if [[ "${configExisted}" == "no" ]]; then
    logComment "${sshConfig} absent; it will hold the managed block alone"
fi

composeManagedConfig "${currentConfig}" "${newConfig}" || exitWith 1 "Unable to build new content; no changes made"
[[ -s "${newConfig}" ]] || exitWith 1 "New content is empty; no changes made"

if [[ "${configExisted}" == "yes" && "${needsRewrite}" == "no" ]] && cmp -s "${currentConfig}" "${newConfig}"; then
    configChanged="no"
    logComment "Managed block already current; no change"
else
    configChanged="yes"
fi

if [[ "${alreadyCompliant}" == "yes" && "${configChanged}" == "no" ]]; then
    exitWith 0 "Compliant (${kexBefore}); no change needed"
fi



# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Write (only when the content changed or the owner is wrong), as the target user
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

backupFile=""

if [[ "${configChanged}" == "yes" ]]; then

    notice "Write ${sshConfig}"

    if [[ ! -e "${sshDir}" ]]; then
        runAsTargetUser /bin/mkdir -m 700 "${sshDir}" < /dev/null || exitWith 1 "Unable to create ${sshDir} as ${targetUser}"
        logComment "Created ${sshDir} as ${targetUser}"
    fi

    if [[ -L "${sshDir}" || ! -d "${sshDir}" ]]; then
        exitWith 1 "${sshDir} is not a directory; no changes made"
    fi

    if [[ "${configExisted}" == "yes" ]]; then
        backupConfig || exitWith 1 "No verified backup; no changes made"
    fi

    if ! writeConfig "${newConfig}"; then
        if [[ "${configReplaced}" == "yes" ]]; then
            rollBack
            exitWith 1 "${sshConfig} replaced but not verified; rolled back"
        fi
        exitWith 1 "Write failed; ${sshConfig} not replaced"
    fi

    # Written by the target user through mktemp: expect owner targetUser and mode 600
    if ! secureSshConfig; then
        rollBack
        exitWith 1 "Unexpected owner or mode on the new ${sshConfig}; rolled back"
    fi

fi



# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Post-check: ssh must still parse the config, and a hybrid must now come first
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

notice "Post-check: 'ssh -G ${probeHost}' as ${targetUser}"

if ! effectiveKex; then
    errorOut "'ssh -G ${probeHost}' fails with the current ${sshConfig} (${kexState})"
    if [[ "${configChanged}" == "yes" ]]; then
        rollBack
        exitWith 1 "ssh config broken after the write; rolled back"
    fi
    exitWith 1 "ssh config broken; ${sshConfig} unchanged"
fi

logComment "First key exchange: ${firstKex}"

if ! isPqHybrid "${firstKex}"; then
    warning "Still Non-Compliant (${firstKex}): an earlier catch-all or top-level KexAlgorithms (or an Include) shadows the managed block"
    # Root reads its own copy of the file, never the live one; backslashes are doubled so echo in
    # updateScriptLog prints the user's text literally (e.g., "\n" can't start a forged log line)
    grep -n -i -- "KexAlgorithms" "${newConfig}" | while IFS= read -r kexAlgorithmsLine; do
        logComment "${sshConfig}:${kexAlgorithmsLine//\\/\\\\}"
    done
    exitWith 1 "Non-Compliant (${firstKex}); managed block shadowed"
fi

exitWith 0 "Compliant: first key exchange ${kexBefore} -> ${firstKex}${backupFile:+; backup: ${backupFile}}"

Resources

Posted in Jamf Pro, macOS, Scripts, Tips & Tricks

Related Posts

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.