#!/bin/bash # # Add and remove an auth line at the top of a PAM service's stack, for signing # in to sudo and polkit (the password prompts of COSMIC's apps and settings) # with a security key or a fingerprint. Each line is "sufficient": when the key # or finger isn't there, it falls through to the password, as before. # # Only these two services change, not common-auth, which pam-auth-update owns # and every service (the login screen, su, sshd) includes. # For the tests PAM_DIR="${PAM_DIR:-/etc/pam.d}" PAM_VENDOR_DIR="${PAM_VENDOR_DIR:-/usr/lib/pam.d}" # The services to sign in to this way (used by the items that source this) # shellcheck disable=SC2034 PAM_SERVICES=(sudo polkit-1) # True if service $1's stack uses module $2 (pam_u2f.so) pam_has() { grep -qE "^[^#]*[[:space:]]$2([[:space:]]|$)" "$PAM_DIR/$1" 2> /dev/null } # Make sure service $1 has its own file in PAM_DIR. polkit's comes in # PAM_VENDOR_DIR, and a file in PAM_DIR replaces it. pam_own_file() { [ -f "$PAM_DIR/$1" ] && return 0 [ -f "$PAM_VENDOR_DIR/$1" ] || { echo "There's no PAM file for $1."; return 1; } sudo cp "$PAM_VENDOR_DIR/$1" "$PAM_DIR/$1" } # The first line of a stack's auth part: an auth line, or Ubuntu's # "@include common-auth", which is how sudo's and polkit's start PAM_AUTH_START='^[[:space:]]*(-?auth[[:space:]]|@include[[:space:]]+common-auth([[:space:]]|$))' # pam_add SERVICE MODULE LINE...: put the lines just before the first auth line # of SERVICE's stack, unless it already uses MODULE pam_add() { local service="$1" module="$2" file shift 2 file="$PAM_DIR/$service" pam_has "$service" "$module" && return 0 pam_own_file "$service" || return 1 grep -qE "$PAM_AUTH_START" "$file" || { echo "$file has no auth lines."; return 1; } # awk writes the new file, then it replaces the old one in one step, so sudo # never sees a half-written file PAM_LINES="$(printf '%s\n' "$@")" awk -v start="$PAM_AUTH_START" ' !done && $0 ~ start { print ENVIRON["PAM_LINES"]; done = 1 } { print } ' "$file" | sudo tee "$file.federated-connector" > /dev/null \ && sudo chmod 644 "$file.federated-connector" \ && sudo mv -f "$file.federated-connector" "$file" } # pam_remove SERVICE PATTERN: remove the lines matching PATTERN (an extended # regular expression) from SERVICE's stack pam_remove() { local file="$PAM_DIR/$1" [ -f "$file" ] && grep -qE "$2" "$file" || return 0 grep -vE "$2" "$file" | sudo tee "$file.federated-connector" > /dev/null \ && sudo chmod 644 "$file.federated-connector" \ && sudo mv -f "$file.federated-connector" "$file" }