-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgh-sks.sh
More file actions
531 lines (462 loc) · 19 KB
/
gh-sks.sh
File metadata and controls
531 lines (462 loc) · 19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
#!/usr/bin/env bash
#
# gh-sks.sh
#
# Retrieves public SSH keys from GitHub for each entry in the config file
# and syncs them into the corresponding Linux user's ~/.ssh/authorized_keys.
#
# Designed to be run periodically via cron (as root).
#
# Usage:
# gh-sks
#
# Configuration:
# /etc/gh-sks/github_authorized_users — one mapping per line:
# <linux_user> <github_username>
# Blank lines and lines starting with # are ignored.
#
set -euo pipefail
# ---------------------------------------------------------------------------
# Version (replaced automatically by CI on tagged releases)
# ---------------------------------------------------------------------------
VERSION="dev"
# ---------------------------------------------------------------------------
# Configuration
# ---------------------------------------------------------------------------
CONFIG_FILE="/etc/gh-sks/github_authorized_users"
MARKER_BEGIN="# --- BEGIN gh-sks managed keys ---"
MARKER_END="# --- END gh-sks managed keys ---"
GITHUB_API_URL="https://github.com"
GH_REPO="BenDutton/gh-sks"
RELEASE_URL="https://github.com/${GH_REPO}/releases/latest/download"
LOG_PREFIX="[gh-sks]"
# ---------------------------------------------------------------------------
# Logging helpers
# ---------------------------------------------------------------------------
_ts() { date -u '+%Y-%m-%dT%H:%M:%SZ'; }
log_info() { echo "$(_ts) ${LOG_PREFIX} INFO: $*"; }
log_warn() { echo "$(_ts) ${LOG_PREFIX} WARN: $*" >&2; }
log_error() { echo "$(_ts) ${LOG_PREFIX} ERROR: $*" >&2; }
escape_regex() { printf '%s' "$1" | sed 's/[].[\^$*+?{}()|/]/\\&/g'; }
# ---------------------------------------------------------------------------
# --version
# ---------------------------------------------------------------------------
if [[ "${1:-}" == "--version" ]]; then
echo "gh-sks ${VERSION}"
exit 0
fi
# ---------------------------------------------------------------------------
# --help
# ---------------------------------------------------------------------------
if [[ "${1:-}" == "--help" || "${1:-}" == "-h" ]]; then
cat <<'USAGE'
Usage: gh-sks [OPTION]
Sync GitHub users' public SSH keys into Linux authorized_keys files.
Options:
--add <linux_user> <github_user> Add a mapping to the config file
--remove <linux_user> <github_user> Remove a mapping from the config file
--list List all configured mappings
--dry-run Show what changes would be made without writing
--update Update gh-sks to the latest release
--uninstall Fully remove gh-sks from this system
--version Print the installed version
--help, -h Show this help message
With no options, syncs keys according to the config file.
USAGE
exit 0
fi
# ---------------------------------------------------------------------------
# --list
# ---------------------------------------------------------------------------
if [[ "${1:-}" == "--list" ]]; then
if [[ ! -f "${CONFIG_FILE}" ]]; then
log_error "Config file not found: ${CONFIG_FILE}"
exit 1
fi
mapfile -t ENTRIES < <(grep -vE '^\s*(#|$)' "${CONFIG_FILE}")
if [[ ${#ENTRIES[@]} -eq 0 ]]; then
echo "No mappings configured."
exit 0
fi
printf '%-20s %s\n' "LINUX USER" "GITHUB USER"
printf '%-20s %s\n' "----------" "-----------"
for entry in "${ENTRIES[@]}"; do
read -r linux_user github_user <<< "${entry}"
printf '%-20s %s\n' "${linux_user}" "${github_user}"
done
exit 0
fi
# ---------------------------------------------------------------------------
# --add <linux_user> <github_user>
# ---------------------------------------------------------------------------
if [[ "${1:-}" == "--add" ]]; then
if [[ "$(id -u)" -ne 0 ]]; then
log_error "--add must be run as root (use sudo)."
exit 1
fi
if [[ -z "${2:-}" || -z "${3:-}" ]]; then
log_error "Usage: gh-sks --add <linux_user> <github_user>"
exit 1
fi
LINUX_USER="$2"
GITHUB_USER="${3,,}" # GitHub usernames are case-insensitive; normalise to lowercase
mkdir -p "$(dirname "${CONFIG_FILE}")"
touch "${CONFIG_FILE}"
# Check for duplicate (case-insensitive on github username)
LINUX_USER_RE="$(escape_regex "${LINUX_USER}")"
GITHUB_USER_RE="$(escape_regex "${GITHUB_USER}")"
if grep -qi "^\s*${LINUX_USER_RE}\s\+${GITHUB_USER_RE}\s*$" "${CONFIG_FILE}"; then
log_warn "Mapping already exists: ${LINUX_USER} ${GITHUB_USER}"
exit 0
fi
echo "${LINUX_USER} ${GITHUB_USER}" >> "${CONFIG_FILE}"
log_info "Added mapping: ${LINUX_USER} <- github:${GITHUB_USER}"
exit 0
fi
# ---------------------------------------------------------------------------
# --remove <linux_user> <github_user>
# ---------------------------------------------------------------------------
if [[ "${1:-}" == "--remove" ]]; then
if [[ "$(id -u)" -ne 0 ]]; then
log_error "--remove must be run as root (use sudo)."
exit 1
fi
if [[ -z "${2:-}" || -z "${3:-}" ]]; then
log_error "Usage: gh-sks --remove <linux_user> <github_user>"
exit 1
fi
LINUX_USER="$2"
GITHUB_USER="${3,,}" # GitHub usernames are case-insensitive; normalise to lowercase
if [[ ! -f "${CONFIG_FILE}" ]]; then
log_error "Config file not found: ${CONFIG_FILE}"
exit 1
fi
LINUX_USER_RE="$(escape_regex "${LINUX_USER}")"
GITHUB_USER_RE="$(escape_regex "${GITHUB_USER}")"
if ! grep -qi "^\s*${LINUX_USER_RE}\s\+${GITHUB_USER_RE}\s*$" "${CONFIG_FILE}"; then
log_warn "Mapping not found: ${LINUX_USER} ${GITHUB_USER}"
exit 1
fi
sed -i "/^\s*${LINUX_USER_RE}\s\+${GITHUB_USER_RE}\s*$/Id" "${CONFIG_FILE}"
log_info "Removed mapping: ${LINUX_USER} <- github:${GITHUB_USER}"
log_info "Run 'sudo gh-sks' to apply changes immediately."
exit 0
fi
# ---------------------------------------------------------------------------
# Self-update
# ---------------------------------------------------------------------------
if [[ "${1:-}" == "--update" ]]; then
if [[ "$(id -u)" -ne 0 ]]; then
log_error "Update must be run as root (use sudo)."
exit 1
fi
SELF_PATH="$(readlink -f "$0")"
DOWNLOAD_URL="${RELEASE_URL}/gh-sks.sh"
log_info "Updating gh-sks from latest release ..."
log_info " ${DOWNLOAD_URL}"
TEMP="$(mktemp)"
if curl -fsSL --max-time 15 -L "${DOWNLOAD_URL}" -o "${TEMP}"; then
NEW_VER=$(grep -m1 '^VERSION=' "${TEMP}" | cut -d'"' -f2)
chmod 755 "${TEMP}"
mv "${TEMP}" "${SELF_PATH}"
log_info "Update complete. ${VERSION} -> ${NEW_VER:-unknown}"
else
rm -f "${TEMP}"
log_error "Update failed — could not download from GitHub."
exit 1
fi
exit 0
fi
# ---------------------------------------------------------------------------
# Uninstall
# ---------------------------------------------------------------------------
if [[ "${1:-}" == "--uninstall" ]]; then
if [[ "$(id -u)" -ne 0 ]]; then
log_error "Uninstall must be run as root (use sudo)."
exit 1
fi
log_info "Uninstalling gh-sks..."
# 1. Stop and remove systemd timer and service
if systemctl is-active --quiet gh-sks.timer 2>/dev/null; then
systemctl disable --now gh-sks.timer
log_info "Disabled and stopped gh-sks.timer."
fi
rm -f /etc/systemd/system/gh-sks.service /etc/systemd/system/gh-sks.timer
systemctl daemon-reload 2>/dev/null || true
log_info "Removed systemd units."
# 2. Strip managed key blocks from all users' authorized_keys
for auth_file in /home/*/.ssh/authorized_keys /root/.ssh/authorized_keys; do
[[ -f "${auth_file}" ]] || continue
if grep -qF "${MARKER_BEGIN}" "${auth_file}"; then
sed -i "/${MARKER_BEGIN}/,/${MARKER_END}/d" "${auth_file}"
log_info "Removed managed keys from ${auth_file}"
fi
done
# 3. Remove config directory
if [[ -d /etc/gh-sks ]]; then
rm -rf /etc/gh-sks
log_info "Removed /etc/gh-sks/"
fi
# 4. Remove self
SELF_PATH="$(readlink -f "$0")"
log_info "Removing ${SELF_PATH}..."
rm -f "${SELF_PATH}"
log_info "Uninstall complete."
exit 0
fi
# ---------------------------------------------------------------------------
# --dry-run
# ---------------------------------------------------------------------------
DRY_RUN=false
if [[ "${1:-}" == "--dry-run" ]]; then
DRY_RUN=true
log_info "Dry-run mode — no files will be modified."
fi
# ---------------------------------------------------------------------------
# Pre-flight checks
# ---------------------------------------------------------------------------
if [[ "$(id -u)" -ne 0 ]] && [[ "${DRY_RUN}" == false ]]; then
log_error "gh-sks must be run as root (use --dry-run to preview without root)."
exit 1
fi
if [[ ! -f "${CONFIG_FILE}" ]]; then
log_error "Config file not found: ${CONFIG_FILE}"
log_error "Create it with lines in the format: <linux_user> <github_username>"
exit 1
fi
if ! command -v curl &>/dev/null; then
log_error "curl is required but not installed."
exit 1
fi
# ---------------------------------------------------------------------------
# Concurrency lock
#
# Prevent overlapping sync runs (e.g. the systemd timer firing while an
# admin runs `sudo gh-sks` manually) from racing on authorized_keys.
# Skipped in dry-run mode, which is read-only and may be invoked unprivileged.
# ---------------------------------------------------------------------------
if [[ "${DRY_RUN}" == false ]]; then
if command -v flock &>/dev/null; then
LOCK_FILE="/var/lock/gh-sks.lock"
exec 9>"${LOCK_FILE}"
if ! flock -n 9; then
log_warn "Another gh-sks run is already in progress (lock: ${LOCK_FILE}). Exiting."
exit 0
fi
else
log_warn "flock not available — concurrent runs are not protected against."
fi
fi
# ---------------------------------------------------------------------------
# Read config (skip blanks and comments)
# ---------------------------------------------------------------------------
mapfile -t LINES < <(grep -vE '^\s*(#|$)' "${CONFIG_FILE}")
if [[ ${#LINES[@]} -eq 0 ]]; then
log_warn "No entries found in ${CONFIG_FILE}. Nothing to sync."
exit 0
fi
log_info "Found ${#LINES[@]} mapping(s) to sync."
# ---------------------------------------------------------------------------
# Fetch a GitHub user's keys, distinguishing transient failures from a
# confirmed empty key set.
#
# Echoes the key body (possibly empty) on stdout and returns:
# 0 — success (HTTP 200, body may be empty)
# 1 — confirmed "no such user" (HTTP 404); treat as zero keys
# 2 — transient failure (network error, timeout, 5xx, rate limit, etc.)
# ---------------------------------------------------------------------------
fetch_github_keys() {
local user="$1"
local url="${GITHUB_API_URL}/${user}.keys"
local tmp http
tmp="$(mktemp)"
# Capture body to tmp, status code to stdout. --fail is intentionally
# omitted so 404s come back as a real status code instead of exit 22.
http="$(curl -sSL --max-time 10 -o "${tmp}" -w '%{http_code}' "${url}" 2>/dev/null || true)"
case "${http}" in
200)
cat "${tmp}"
rm -f "${tmp}"
return 0
;;
404)
rm -f "${tmp}"
return 1
;;
*)
rm -f "${tmp}"
return 2
;;
esac
}
# ---------------------------------------------------------------------------
# Fetch keys from GitHub and group by Linux user.
#
# USER_KEYS[user] — accumulated, annotated key lines (may be empty string
# when GitHub confirmed zero keys for every mapping;
# that empty value is still meaningful and triggers a
# rewrite that clears the managed block).
# USER_FAILED[user] — set to 1 if ANY mapping for this user hit a transient
# failure. Such users are skipped at write time so we
# never lock them out by erasing keys we just failed to
# re-fetch.
# ---------------------------------------------------------------------------
declare -A USER_KEYS
declare -A USER_FAILED
declare -A USER_SEEN
for line in "${LINES[@]}"; do
# Parse: <linux_user> <github_username>
read -r linux_user github_user <<< "${line}"
if [[ -z "${linux_user}" || -z "${github_user}" ]]; then
log_warn "Skipping malformed line: '${line}'"
continue
fi
# GitHub usernames are case-insensitive; normalise to lowercase
github_user="${github_user,,}"
# Verify the Linux user exists
if ! id "${linux_user}" &>/dev/null; then
log_warn "Linux user '${linux_user}' does not exist — skipping."
continue
fi
USER_SEEN["${linux_user}"]=1
# Ensure an entry exists so an all-empty result still triggers a rewrite
# (this is what clears revoked keys from the managed block).
USER_KEYS["${linux_user}"]="${USER_KEYS[${linux_user}]:-}"
url="${GITHUB_API_URL}/${github_user}.keys"
log_info "Fetching keys for github:${github_user} -> ${linux_user} from ${url}"
keys="$(fetch_github_keys "${github_user}")"
fetch_rc=$?
case "${fetch_rc}" in
0)
if [[ -z "${keys}" ]]; then
log_warn " -> github:${github_user} has zero public keys (confirmed); their entries will be removed."
continue
fi
key_count="$(printf '%s' "${keys}" | grep -c '^' || true)"
log_info " -> Retrieved ${key_count} key(s) for github:${github_user}"
while IFS= read -r key; do
[[ -z "${key}" ]] && continue
USER_KEYS["${linux_user}"]+="${key} github:${github_user}"$'\n'
done <<< "${keys}"
;;
1)
log_warn " -> github:${github_user} does not exist (HTTP 404); their entries will be removed."
;;
2)
log_error " -> Transient failure fetching keys for github:${github_user}; ${linux_user}'s authorized_keys will be left unchanged this run."
USER_FAILED["${linux_user}"]=1
;;
esac
done
if [[ ${#USER_SEEN[@]} -eq 0 ]]; then
log_warn "No usable mappings found. No authorized_keys files will be modified."
exit 0
fi
# ---------------------------------------------------------------------------
# Update each Linux user's authorized_keys
# ---------------------------------------------------------------------------
for linux_user in "${!USER_SEEN[@]}"; do
if [[ -n "${USER_FAILED[${linux_user}]:-}" ]]; then
log_warn "Skipping ${linux_user}: at least one key fetch failed this run (existing keys preserved)."
continue
fi
managed_keys="${USER_KEYS[${linux_user}]:-}"
user_home="$(getent passwd "${linux_user}" | cut -d: -f6)"
# Guard against accounts with no/empty home dir (some service accounts).
# Without this, ssh_dir would become "/.ssh" and we'd clobber the
# filesystem root.
if [[ -z "${user_home}" ]]; then
log_warn "Skipping ${linux_user}: no home directory in passwd entry."
continue
fi
if [[ ! -d "${user_home}" ]]; then
log_warn "Skipping ${linux_user}: home directory '${user_home}' does not exist."
continue
fi
ssh_dir="${user_home}/.ssh"
auth_keys="${ssh_dir}/authorized_keys"
total="$(printf '%s' "${managed_keys}" | grep -c '^' || true)"
# -- dry-run: print what would be written and move on ----------------
if [[ "${DRY_RUN}" == true ]]; then
log_info "[dry-run] Would write ${total} managed key(s) to ${auth_keys}:"
printf '%s' "${managed_keys}" | while IFS= read -r _k; do
echo " ${_k}"
done
continue
fi
# Ensure .ssh dir and authorized_keys exist with correct perms
mkdir -p "${ssh_dir}"
chmod 700 "${ssh_dir}"
chown "${linux_user}:${linux_user}" "${ssh_dir}"
touch "${auth_keys}"
chmod 600 "${auth_keys}"
chown "${linux_user}:${linux_user}" "${auth_keys}"
TEMP_FILE="$(mktemp)"
trap 'rm -f "${TEMP_FILE}"' EXIT
# Strip existing managed block if present
if grep -qF "${MARKER_BEGIN}" "${auth_keys}"; then
sed "/${MARKER_BEGIN}/,/${MARKER_END}/d" "${auth_keys}" > "${TEMP_FILE}"
else
cp "${auth_keys}" "${TEMP_FILE}"
fi
# Remove trailing blank lines
sed -i -e :a -e '/^\n*$/{$d;N;ba' -e '}' "${TEMP_FILE}" 2>/dev/null || true
# Append managed block
{
[[ -s "${TEMP_FILE}" ]] && echo ""
echo "${MARKER_BEGIN}"
echo "# Auto-generated — do not edit this section manually."
echo "# Last updated: $(date -u '+%Y-%m-%dT%H:%M:%SZ')"
echo "#"
printf '%s' "${managed_keys}"
echo "${MARKER_END}"
} >> "${TEMP_FILE}"
# Atomic replace
mv "${TEMP_FILE}" "${auth_keys}"
chmod 600 "${auth_keys}"
chown "${linux_user}:${linux_user}" "${auth_keys}"
log_info "Wrote ${total} managed key(s) to ${auth_keys}"
done
# ---------------------------------------------------------------------------
# Prune orphaned managed blocks
#
# If a Linux user that previously had a managed block is no longer present
# in the config at all, the main loop above never visits them and their old
# (now unauthorised) keys would persist. Scan known authorized_keys
# locations and strip the managed block from any file whose owner is no
# longer in USER_SEEN.
# ---------------------------------------------------------------------------
shopt -s nullglob
for auth_keys in /home/*/.ssh/authorized_keys /root/.ssh/authorized_keys; do
[[ -f "${auth_keys}" ]] || continue
grep -qF "${MARKER_BEGIN}" "${auth_keys}" || continue
# Derive the owning Linux user from the path.
if [[ "${auth_keys}" == /root/* ]]; then
linux_user="root"
else
# /home/<user>/.ssh/authorized_keys
linux_user="${auth_keys#/home/}"
linux_user="${linux_user%%/*}"
fi
# Still in the config — main loop already handled (or deliberately
# skipped due to a transient failure).
[[ -n "${USER_SEEN[${linux_user}]:-}" ]] && continue
if [[ "${DRY_RUN}" == true ]]; then
log_info "[dry-run] Would remove orphaned managed block from ${auth_keys} (no mapping for ${linux_user})."
continue
fi
TEMP_FILE="$(mktemp)"
sed "/${MARKER_BEGIN}/,/${MARKER_END}/d" "${auth_keys}" > "${TEMP_FILE}"
# Tidy trailing blank lines left behind by the deletion.
sed -i -e :a -e '/^\n*$/{$d;N;ba' -e '}' "${TEMP_FILE}" 2>/dev/null || true
mv "${TEMP_FILE}" "${auth_keys}"
chmod 600 "${auth_keys}"
chown "${linux_user}:${linux_user}" "${auth_keys}" 2>/dev/null || true
log_info "Removed orphaned managed block from ${auth_keys} (no mapping for ${linux_user})."
done
shopt -u nullglob
if [[ "${DRY_RUN}" == true ]]; then
log_info "Dry-run complete. No files were modified."
else
log_info "Sync complete."
fi