-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsync-ssh-keys.sh
More file actions
613 lines (496 loc) · 15 KB
/
sync-ssh-keys.sh
File metadata and controls
613 lines (496 loc) · 15 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
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
#!/bin/bash
set -euo pipefail
# SSH Key Sync Script
# Synchronizes SSH authorized_keys files for multiple users from various sources
# Author: locus313
# Repository: https://github.com/locus313/ssh-key-sync
# shellcheck disable=SC2034 # planned to be used in a future release
readonly SCRIPT_VERSION="0.1.5"
SCRIPT_NAME="$(basename "$0")"
readonly SCRIPT_NAME
# === Configuration and Constants ===
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
readonly SCRIPT_DIR
readonly CONFIG_FILE="$SCRIPT_DIR/users.conf"
readonly DEFAULT_RETRIES=3
readonly DEFAULT_RETRY_DELAY=2
readonly GITHUB_REPO="locus313/ssh-key-sync"
# === Utility Functions ===
# Log messages with timestamp
log_message() {
local message="$1"
local timestamp
timestamp="$(date '+%Y-%m-%d %H:%M:%S')"
echo "$timestamp: $message"
}
# Log error messages to stderr
log_error() {
local message="$1"
log_message "ERROR: $message" >&2
}
# Log warning messages
log_warning() {
local message="$1"
log_message "WARNING: $message"
}
# Log info messages
log_info() {
local message="$1"
log_message "INFO: $message"
}
# === Configuration Loading ===
# Load and validate configuration file
load_configuration() {
if [[ ! -f "$CONFIG_FILE" ]]; then
log_error "Configuration file 'users.conf' not found in $SCRIPT_DIR. Halting execution."
exit 1
fi
# Load GITHUB_TOKEN from config if set and not already in environment
if [[ -n "${CONF_GITHUB_TOKEN:-}" && -z "${GITHUB_TOKEN:-}" ]]; then
export GITHUB_TOKEN="$CONF_GITHUB_TOKEN"
log_info "Using GitHub token from configuration file"
fi
}
# Validate configuration after sourcing
validate_configuration() {
# Validate that USER_KEYS array is defined
if ! declare -p USER_KEYS &>/dev/null; then
log_error "USER_KEYS array not defined in configuration file. Halting execution."
exit 1
fi
}
# === Key Fetching Functions ===
# Validate method parameter
validate_method() {
local method="$1"
case "$method" in
raw|api|ghuser)
return 0
;;
*)
log_error "Unsupported method '$method'. Supported methods: raw, api, ghuser"
return 1
;;
esac
}
# Fetch key file using raw method (public URL)
fetch_raw_key() {
local url="$1"
local output_file="$2"
if [[ -z "$url" ]]; then
log_error "URL parameter is required for raw method"
return 1
fi
curl -fsSL "$url" -o "$output_file"
}
# Fetch key file using GitHub API method (private repository)
fetch_api_key() {
local url="$1"
local output_file="$2"
if [[ -z "$url" ]]; then
log_error "URL parameter is required for API method"
return 1
fi
if [[ -z "${GITHUB_TOKEN:-}" ]]; then
log_error "GITHUB_TOKEN is required for API access"
return 1
fi
curl -fsSL \
-H "Authorization: token $GITHUB_TOKEN" \
-H "Accept: application/vnd.github.v3.raw" \
"$url" -o "$output_file"
}
# Fetch key file using GitHub user method (public keys)
fetch_ghuser_key() {
local username="$1"
local output_file="$2"
if [[ -z "$username" ]]; then
log_error "Username parameter is required for ghuser method"
return 1
fi
curl -fsSL "https://github.com/${username}.keys" -o "$output_file"
}
# Main key fetching function with retry logic
fetch_key_file() {
local method="$1"
local target="$2"
local output_file="$3"
local retries="${4:-$DEFAULT_RETRIES}"
local retry_delay="${5:-$DEFAULT_RETRY_DELAY}"
# Validate required parameters
if [[ -z "$method" ]]; then
log_error "Method parameter is required"
return 1
fi
if [[ -z "$target" ]]; then
log_error "Target parameter is required"
return 1
fi
if [[ -z "$output_file" ]]; then
log_error "Output file parameter is required"
return 1
fi
# Validate method
if ! validate_method "$method"; then
return 1
fi
# Attempt to fetch with retries
for ((attempt=1; attempt<=retries; attempt++)); do
local fetch_result=0
case "$method" in
raw)
fetch_raw_key "$target" "$output_file" || fetch_result=$?
;;
api)
fetch_api_key "$target" "$output_file" || fetch_result=$?
;;
ghuser)
fetch_ghuser_key "$target" "$output_file" || fetch_result=$?
;;
esac
# If successful, return
if [[ $fetch_result -eq 0 ]]; then
return 0
fi
# Log retry attempt
if [[ $attempt -lt $retries ]]; then
log_warning "Attempt $attempt/$retries failed for method '$method' and target '$target'. Retrying in $retry_delay seconds..."
sleep "$retry_delay"
fi
done
log_error "All $retries attempts failed for method '$method' and target '$target'"
return 1
}
# === Self-Update Functions ===
# Download and validate the latest script version
download_latest_script() {
local latest_url="$1"
local temp_dir="$2"
local temp_script="$temp_dir/sync-ssh-keys.sh"
log_info "Downloading latest script from: $latest_url"
if ! curl -fsSL "$latest_url" -o "$temp_script"; then
log_error "Failed to download the latest script"
return 1
fi
if [[ ! -s "$temp_script" ]]; then
log_error "Downloaded script is empty"
return 1
fi
# Basic validation - check if it's a bash script
if ! head -1 "$temp_script" | grep -q "^#!/bin/bash"; then
log_error "Downloaded file does not appear to be a bash script"
return 1
fi
log_info "Successfully downloaded and validated script"
return 0
}
# Get the latest release download URL
get_latest_release_url() {
local repo="$1"
local api_url="https://api.github.com/repos/$repo/releases/latest"
log_info "Fetching latest release information..."
local download_url
if ! download_url=$(curl -fsSL "$api_url" | grep "browser_download_url" | grep "sync-ssh-keys.sh" | cut -d '"' -f 4); then
log_error "Could not determine the latest version URL from GitHub API"
return 1
fi
if [[ -z "$download_url" ]]; then
log_error "No download URL found for sync-ssh-keys.sh in latest release"
return 1
fi
echo "$download_url"
}
# Perform self-update of the script
self_update() {
local latest_url
local temp_dir
local current_script="$SCRIPT_DIR/$SCRIPT_NAME"
log_info "Starting self-update process..."
# Get latest release URL
if ! latest_url=$(get_latest_release_url "$GITHUB_REPO"); then
log_error "Failed to get latest release URL"
exit 1
fi
# Create temporary directory
if ! temp_dir=$(mktemp -d); then
log_error "Failed to create temporary directory"
exit 1
fi
# Ensure cleanup on exit
trap 'rm -rf "$temp_dir"' EXIT
# Download and validate
if ! download_latest_script "$latest_url" "$temp_dir"; then
log_error "Failed to download or validate the latest script"
exit 1
fi
# Replace current script
local temp_script="$temp_dir/sync-ssh-keys.sh"
if ! chmod +x "$temp_script"; then
log_error "Failed to make downloaded script executable"
exit 1
fi
if ! mv "$temp_script" "$current_script"; then
log_error "Failed to replace current script"
exit 1
fi
log_info "Script successfully updated to the latest version"
exit 0
}
# === User Management Functions ===
# Validate user exists and get user information
validate_user() {
local username="$1"
if ! id "$username" &>/dev/null; then
log_warning "User '$username' does not exist. Skipping."
return 1
fi
return 0
}
# Get user's home directory safely
get_user_home() {
local username="$1"
local user_home
if ! user_home=$(getent passwd "$username" | cut -d: -f6); then
log_error "Failed to get user information for '$username'"
return 1
fi
if [[ -z "$user_home" ]]; then
log_error "Failed to determine home directory for user '$username'"
return 1
fi
echo "$user_home"
}
# Create SSH directory with proper permissions
create_ssh_directory() {
local username="$1"
local ssh_dir="$2"
if [[ -d "$ssh_dir" ]]; then
return 0
fi
log_info "Creating .ssh directory for user '$username' at $ssh_dir"
if ! mkdir -p "$ssh_dir"; then
log_error "Failed to create .ssh directory for user '$username'"
return 1
fi
if ! chown "$username:$username" "$ssh_dir"; then
log_error "Failed to set ownership of .ssh directory for user '$username'"
return 1
fi
if ! chmod 700 "$ssh_dir"; then
log_error "Failed to set permissions on .ssh directory for user '$username'"
return 1
fi
return 0
}
# Update authorized_keys file with proper permissions
update_authorized_keys() {
local username="$1"
local temp_file="$2"
local auth_keys_file="$3"
# Check if update is needed by comparing files
if [[ -f "$auth_keys_file" ]] && files_are_identical "$temp_file" "$auth_keys_file"; then
log_info "No changes detected in authorized_keys for user '$username'"
return 0
fi
# Perform update
if [[ ! -f "$auth_keys_file" ]]; then
log_info "No existing authorized_keys file for user '$username'. Creating a new one."
else
log_info "Changes detected in authorized_keys for user '$username'. Updating the file."
fi
if ! cp "$temp_file" "$auth_keys_file"; then
log_error "Failed to copy keys to authorized_keys file for user '$username'"
return 1
fi
if ! chown "$username:$username" "$auth_keys_file"; then
log_error "Failed to set ownership of authorized_keys file for user '$username'"
return 1
fi
if ! chmod 600 "$auth_keys_file"; then
log_error "Failed to set permissions on authorized_keys file for user '$username'"
return 1
fi
log_info "Updated authorized_keys for user '$username' at $auth_keys_file"
return 0
}
# Compare two files to check if they are identical
files_are_identical() {
local file1="$1"
local file2="$2"
# Use a portable comparison method
if command -v cmp >/dev/null 2>&1; then
cmp -s "$file1" "$file2"
elif command -v diff >/dev/null 2>&1; then
diff -q "$file1" "$file2" >/dev/null 2>&1
else
# Fallback to checksum comparison if neither cmp nor diff is available
local file1_hash file2_hash
if command -v sha256sum >/dev/null 2>&1; then
file1_hash=$(sha256sum "$file1" | cut -d' ' -f1)
file2_hash=$(sha256sum "$file2" | cut -d' ' -f1)
elif command -v md5sum >/dev/null 2>&1; then
file1_hash=$(md5sum "$file1" | cut -d' ' -f1)
file2_hash=$(md5sum "$file2" | cut -d' ' -f1)
else
# Last resort: always update if we can't compare
log_warning "No file comparison tools available. Will always update authorized_keys."
return 1
fi
[[ -n "$file1_hash" && "$file1_hash" == "$file2_hash" ]]
fi
}
# Process a single user's SSH keys
process_user_keys() {
local username="$1"
local entry="$2"
local temp_file="$3"
# Validate required parameters
if [[ -z "$username" ]]; then
log_error "Username parameter is required"
return 1
fi
if [[ -z "$entry" ]]; then
log_error "Entry parameter is required for user '$username'"
return 1
fi
if [[ -z "$temp_file" ]]; then
log_error "Temporary file parameter is required for user '$username'"
return 1
fi
# Parse method and target from entry
local method="${entry%%:*}"
local target="${entry#*:}"
# Validate that we actually have both method and target
if [[ "$method" == "$entry" ]]; then
log_error "Invalid entry format for user '$username'. Expected format: method:target"
return 1
fi
# Validate user exists
if ! validate_user "$username"; then
return 1
fi
# Get user home directory
local user_home
if ! user_home=$(get_user_home "$username"); then
return 1
fi
# Set up paths
local ssh_dir="$user_home/.ssh"
local auth_keys_file="$ssh_dir/authorized_keys"
# Create SSH directory if needed
if ! create_ssh_directory "$username" "$ssh_dir"; then
return 1
fi
# Fetch key file
log_info "Fetching key file for $username from $target (method: $method)"
if ! fetch_key_file "$method" "$target" "$temp_file"; then
log_error "Failed to fetch key file for user '$username' from $target after multiple attempts"
return 1
fi
# Update authorized_keys file
if ! update_authorized_keys "$username" "$temp_file" "$auth_keys_file"; then
return 1
fi
return 0
}
# === Main Execution ===
# Display usage information
show_usage() {
cat << EOF
Usage: $SCRIPT_NAME [OPTIONS]
SSH Key Sync Script v$SCRIPT_VERSION
Synchronizes SSH authorized_keys files for multiple users from various sources.
OPTIONS:
--self-update Update the script to the latest version from GitHub
--help, -h Show this help message
--version, -v Show version information
For more information, see: https://github.com/$GITHUB_REPO
EOF
}
# Parse command line arguments
parse_arguments() {
case "${1:-}" in
--self-update)
self_update
;;
--help|-h)
show_usage
exit 0
;;
--version|-v)
echo "$SCRIPT_NAME version $SCRIPT_VERSION"
exit 0
;;
"")
# No arguments - continue with normal execution
;;
*)
log_error "Unknown option: $1"
show_usage
exit 1
;;
esac
}
# Main function
main() {
local temp_files=()
local failed_users=0
local processed_users=0
log_info "Starting SSH key synchronization (version $SCRIPT_VERSION)"
# Parse command line arguments
parse_arguments "$@"
# Source configuration file at global scope
# shellcheck source=users.conf
if ! source "$CONFIG_FILE"; then
log_error "Failed to load configuration file 'users.conf'. Please check the file for syntax errors. Halting execution."
exit 1
fi
# Load and validate configuration
log_info "Loading configuration..."
load_configuration
log_info "Configuration loaded successfully"
log_info "Validating configuration..."
validate_configuration
log_info "Configuration validated successfully"
# Count users defined in USER_KEYS array
local user_count=0
if declare -p USER_KEYS &>/dev/null; then
for username in "${!USER_KEYS[@]}"; do
user_count=$((user_count + 1))
done
fi
log_info "Found $user_count user(s) to process"
if [[ $user_count -eq 0 ]]; then
log_warning "No users defined in USER_KEYS array. Nothing to do."
exit 0
fi
# Set up cleanup trap for temporary files
trap 'rm -f "${temp_files[@]}"' EXIT
# Process each user
for username in "${!USER_KEYS[@]}"; do
local temp_file=""
if ! temp_file=$(mktemp); then
log_error "Failed to create temporary file for user '$username'"
failed_users=$((failed_users + 1))
continue
fi
temp_files+=("$temp_file")
local entry="${USER_KEYS[$username]}"
if process_user_keys "$username" "$entry" "$temp_file"; then
log_info "Successfully processed user '$username'"
else
log_error "Failed to process user '$username'"
failed_users=$((failed_users + 1))
fi
processed_users=$((processed_users + 1))
# Clean up temp file immediately after processing
rm -f "$temp_file"
done
# Summary
log_info "Synchronization complete. Processed: $processed_users, Failed: $failed_users"
if [[ $failed_users -gt 0 ]]; then
exit 1
fi
}
# Execute main function with all arguments
main "$@"