-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfunctions.sh
More file actions
1903 lines (1697 loc) · 67 KB
/
Copy pathfunctions.sh
File metadata and controls
1903 lines (1697 loc) · 67 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
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env -S bash
#
# Copyright 2024, Wim Bonis, Stylite AG
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#####################
# Functions
#####################
#==============================================================================
# CONSTANTS
#==============================================================================
readonly PROC_SSH_RAGENT=" ragent "
readonly PROC_PYTHON_MUX="sshagentmux.py"
readonly PROC_RUST_MUX="ssh-agent-mux"
#==============================================================================
# COLOR AND LOGGING UTILITIES
#==============================================================================
# Color helper function
color() {
# Skip colors if explicitly disabled
[ -n "${NO_COLOR:-}" ] && return
# Skip if TERM is "dumb" (no color support)
[ "${TERM:-}" = "dumb" ] && return
# Use colors if:
# - stdout is a TTY (interactive terminal), OR
# - FORCE_COLOR is explicitly set, OR
# - TERM is set and stderr is also a TTY (indicates interactive session, not file redirect)
# We check stderr TTY to distinguish interactive sessions from file redirects
if command -v tput >/dev/null 2>&1; then
if [ -t 1 ] || [ "${FORCE_COLOR:-0}" == "1" ] || ([ -n "${TERM:-}" ] && [ -t 2 ]); then
tput "$@" 2>/dev/null || true
fi
fi
}
# Color helper for stderr (SCA uses stderr for logging)
color_stderr() {
if [ -t 2 ] && [ -z "${NO_COLOR:-}" ] && command -v tput >/dev/null 2>&1; then
tput "$@"
fi
}
# Logging functions with colors (use color_stderr since output goes to stderr)
log_error() {
echo "$(color_stderr setaf 1)$(color_stderr bold)ERROR:$(color_stderr sgr0) $(color_stderr setaf 1)$*$(color_stderr sgr0)" >&2
}
log_warn() {
echo "$(color_stderr setaf 3)$(color_stderr bold)WARNING:$(color_stderr sgr0) $(color_stderr setaf 3)$*$(color_stderr sgr0)" >&2
}
log_info() {
echo "$(color_stderr setaf 4)$(color_stderr bold)INFO:$(color_stderr sgr0) $(color_stderr setaf 4)$*$(color_stderr sgr0)" >&2
}
log_success() {
echo "$(color_stderr setaf 2)$(color_stderr bold)✓$(color_stderr sgr0) $(color_stderr setaf 2)$*$(color_stderr sgr0)" >&2
}
log_debug() {
if [ "${DEBUG:-0}" == "1" ]; then
echo "$(color_stderr setaf 5)$(color_stderr bold)DEBUG:$(color_stderr sgr0) $(color_stderr setaf 5)$*$(color_stderr sgr0)" >&2
fi
}
log_note() {
echo "$(color_stderr setaf 6)$(color_stderr bold)NOTE:$(color_stderr sgr0) $(color_stderr setaf 6)$*$(color_stderr sgr0)" >&2
}
# Color codes for syntax highlighting
color_reset() {
color sgr0
}
color_host() {
color setaf 4 # Blue
color bold
}
color_directive() {
color setaf 6 # Cyan
}
color_value() {
color setaf 3 # Yellow
}
color_comment() {
# Try gray (8), fallback to dim white (7)
if color setaf 8 >/dev/null 2>&1; then
color setaf 8
else
color setaf 7
color dim
fi
}
color_file_header() {
color setaf 5 # Magenta
color dim
}
# Syntax highlight a line of SSH config
highlight_line() {
local line="$1"
# Host or Match directive (bold blue for keyword, yellow for values)
if [[ "$line" =~ ^([[:space:]]*)(Host|Match)[[:space:]]+(.+)$ ]]; then
local indent="${BASH_REMATCH[1]}"
local keyword="${BASH_REMATCH[2]}"
local values="${BASH_REMATCH[3]}"
printf "%s%s%s%s %s%s%s\n" \
"$indent" \
"$(color_host)" \
"$keyword" \
"$(color_reset)" \
"$(color_value)" \
"$values" \
"$(color_reset)"
return
fi
# Comment lines (gray/dim)
if [[ "$line" =~ ^[[:space:]]*# ]]; then
printf "%s%s%s\n" "$(color_comment)" "$line" "$(color_reset)"
return
fi
# Directives with values (cyan directive, yellow value)
if [[ "$line" =~ ^([[:space:]]+)([A-Za-z][A-Za-z0-9]*)[[:space:]]+(.+)$ ]]; then
local indent="${BASH_REMATCH[1]}"
local directive="${BASH_REMATCH[2]}"
local value="${BASH_REMATCH[3]}"
printf "%s%s%s%s %s%s%s\n" \
"$indent" \
"$(color_directive)" \
"$directive" \
"$(color_reset)" \
"$(color_value)" \
"$value" \
"$(color_reset)"
return
fi
# Default: just print the line
printf "%s\n" "$line"
}
#==============================================================================
# HOST MANAGEMENT FUNCTIONS
#==============================================================================
list() {
echo "## Listing Hosts" >&2
cat $PLAYBOOK_DIR/hosts/*
}
#==============================================================================
# HOST SEARCH HELPER FUNCTIONS
#==============================================================================
# Helper function to find Host block start line for any given line number
find_host_block_start() {
local file="$1"
local line_num="$2"
local start_line=$line_num
while [ $start_line -gt 0 ]; do
local line_content=$(sed -n "${start_line}p" "$file" 2>/dev/null)
# Check if this line starts with "Host " (with space) or "Match " (with space)
if echo "$line_content" | grep -qiE "^[[:space:]]*(Host|Match)[[:space:]]"; then
echo "$start_line"
return 0
fi
start_line=$((start_line - 1))
done
return 1
}
# Helper function to search for matches in all lines
search_in_all_lines() {
local file="$1"
local hostname="$2"
# Search for the hostname as a substring in all non-comment lines (case-insensitive)
# Important: ignore standalone comments like "# Autoadded ..." to avoid jumping to the previous Host block.
awk -v q="$hostname" '
BEGIN { q = tolower(q) }
/^[[:space:]]*#/ { next }
{ if (index(tolower($0), q) > 0) print NR }
' "$file" 2>/dev/null
}
# Process matching lines and extract host blocks
process_matching_lines() {
local file="$1"
local hostname="$2"
local matching_lines=$(search_in_all_lines "$file" "$hostname")
if [ -z "$matching_lines" ]; then
return 1
fi
local unique_starts=""
while IFS= read -r line_num; do
local start_line=$(find_host_block_start "$file" "$line_num")
if [ -n "$start_line" ]; then
if ! echo "$unique_starts" | grep -q "^${start_line}$"; then
unique_starts="${unique_starts}${start_line}"$'\n'
fi
fi
done <<< "$matching_lines"
if [ -n "$unique_starts" ]; then
local sorted_starts
sorted_starts=$(echo "$unique_starts" | grep -v '^$' | sort -n)
while IFS= read -r start_line; do
[ -z "$start_line" ] && continue
extract_host_block "$file" "$start_line"
done <<< "$sorted_starts"
return 0
fi
return 1
}
# Helper function to extract and print Host block from a file
extract_host_block() {
local file="$1"
local line_num="$2"
# Find the start of this Host block using the helper function
local start_line
start_line=$(find_host_block_start "$file" "$line_num")
if [ $? -ne 0 ] || [ -z "$start_line" ]; then
return 1
fi
local host_line_content=$(sed -n "${start_line}p" "$file" 2>/dev/null)
# Verify it's actually a Host or Match line with space
if ! echo "$host_line_content" | grep -qiE "^[[:space:]]*(Host|Match)[[:space:]]"; then
return 1
fi
# Find the end of this Host block (next Host or Match line, or end of file)
local total_lines=$(wc -l < "$file" 2>/dev/null)
local end_line=$total_lines
local next_line=$((start_line + 1))
while [ $next_line -le $total_lines ]; do
local line_content=$(sed -n "${next_line}p" "$file" 2>/dev/null)
# Check if this line starts a new Host or Match block (with space)
if echo "$line_content" | grep -qiE "^[[:space:]]*(Host|Match)[[:space:]]"; then
end_line=$((next_line - 1))
break
fi
next_line=$((next_line + 1))
done
# Extract the block starting from the Host line
local block_content=$(sed -n "${start_line},${end_line}p" "$file" 2>/dev/null)
# Always start with the Host line (remove any trailing whitespace)
local clean_host_line=$(echo "$host_line_content" | sed 's/[[:space:]]*$//')
# Filter the rest: remove empty lines and standalone (non-indented) comment lines
# Note: we keep this streaming below to preserve colors and avoid buffering.
# Build output: always start with Host line
# Ensure clean_host_line is not empty
if [ -z "$clean_host_line" ]; then
clean_host_line=$(sed -n "${start_line}p" "$file" 2>/dev/null | sed 's/[[:space:]]*$//')
fi
# Print file header with color
echo -n "$(color_file_header)"
echo "--- $file (lines $start_line-$end_line) ---"
echo -n "$(color_reset)"
# Always print the Host line first with highlighting
highlight_line "$clean_host_line"
# Print rest of block with highlighting - process line by line directly
echo "$block_content" | tail -n +2 | while IFS= read -r line || [ -n "$line" ]; do
# Skip empty lines and standalone (non-indented) comment lines
if [ -z "$line" ]; then
continue
fi
# Standalone comment (not indented) - skip
[[ "$line" == \#* ]] && continue
# Print the line with highlighting
highlight_line "$line"
done
echo ""
}
find() {
local hostname="$1"
local config_file="$PLAYBOOK_DIR/config"
local hosts_dir="$PLAYBOOK_DIR/hosts"
local found_any=false
echo "Searching for host: $hostname" >&2
# Search in config file
if [ -f "$config_file" ]; then
process_matching_lines "$config_file" "$hostname" && found_any=true
fi
# Search in hosts/* files
if [ -d "$hosts_dir" ]; then
for host_file in "$hosts_dir"/*; do
if [ -f "$host_file" ]; then
process_matching_lines "$host_file" "$hostname" && found_any=true
fi
done
fi
# Display results
if [ "$found_any" != "true" ]; then
echo "No host found matching: $hostname" >&2
return 1
fi
}
add() {
echo "Adding Host: $*" >&2
(cd "$PLAYBOOK_DIR" && ./addhost "$@")
}
do_cmd() {
CMD="$1"
shift
ARGS="$*"
echo "CMD: $CMD" >&2
echo "ARGS: $ARGS" >&2
# Is function $CMD defined?
if type "$CMD" >/dev/null 2>&1; then
"$CMD" $ARGS
else
echo "Command $CMD not found" >&2
fi
}
# Cleanup function for background processes
cleanup() {
SCA_EXITING=true
# Check if we have anything to clean up
local has_cleanup=false
[ -n "$SSH_PID" ] && has_cleanup=true
[ -n "$MUX_PID" ] && has_cleanup=true
[ -n "$TAIL_LOG_PID" ] && has_cleanup=true
[ -n "$RUST_MUX_LOG" ] && [ -f "$RUST_MUX_LOG" ] && has_cleanup=true
[ -n "$TEMP_AGENT_PID" ] && has_cleanup=true
if [ "$has_cleanup" != "true" ]; then
return
fi
log_info "Cleaning up background processes..."
# Kill SSH agent forwarder
if [ -n "$SSH_PID" ]; then
kill_if_exists "$SSH_PID" "SSH agent forwarder"
kill_processes "$PROC_SSH_RAGENT" "SSH agent forwarder"
log_info "Removing SSH agent socket: $SCA_SSH_AUTH_SOCK"
rm -f "$SCA_SSH_AUTH_SOCK" 2>/dev/null || true
fi
# Kill multiplexer processes
if [ -n "$MUX_PID" ]; then
kill_if_exists "$MUX_PID" "multiplexer"
kill_processes "$PROC_PYTHON_MUX" "Python multiplexer"
if [ -n "$RUST_MUX_PID" ]; then
kill_if_exists "$RUST_MUX_PID" "ssh-agent-mux"
fi
kill_process_by_name "$PROC_RUST_MUX"
log_info "Removing mux socket: $MUX_SSH_AUTH_SOCK"
rm -f "$MUX_SSH_AUTH_SOCK" 2>/dev/null || true
fi
# Kill log tail process
if [ -n "$TAIL_LOG_PID" ]; then
if kill -0 "$TAIL_LOG_PID" 2>/dev/null; then
log_info "Stopping log tail process (PID $TAIL_LOG_PID)"
kill -TERM "$TAIL_LOG_PID" 2>/dev/null || true
fi
fi
# Clean up temp log file if it exists
if [ -n "$RUST_MUX_LOG" ] && [ -f "$RUST_MUX_LOG" ]; then
log_info "Removing temp log file: $RUST_MUX_LOG"
rm -f "$RUST_MUX_LOG" 2>/dev/null || true
fi
# Clean up temporary SSH agent if it exists
if [ -n "$TEMP_AGENT_PID" ]; then
cleanup_temp_agent
fi
log_info "Cleanup complete"
}
# Kill a process if it exists
kill_if_exists() {
local pid=$1
local name=$2
if [ -n "$pid" ] && kill -0 "$pid" 2>/dev/null; then
log_info "Killing $name (PID $pid)"
kill -TERM "$pid" 2>/dev/null || true
fi
}
# Kill processes by pattern
kill_processes() {
local pattern=$1
local name=$2
if pkill -f "$pattern" 2>/dev/null; then
log_info "Killed $name processes"
fi
}
# Kill processes by exact name
kill_process_by_name() {
local name=$1
if pkill -x "$name" 2>/dev/null; then
log_info "Killed $name processes"
fi
}
# Kill all SCA-related processes
kill_all_sca_processes() {
kill_processes "$PROC_SSH_RAGENT" "SSH agent forwarder"
kill_processes "$PROC_PYTHON_MUX" "Python multiplexer"
kill_process_by_name "$PROC_RUST_MUX"
}
# Check if an SSH agent socket is working
check_agent_socket() {
local socket=$1
SSH_AUTH_SOCK="$socket" ssh-add -l >/dev/null 2>&1
}
# Check if SSH process with ragent is still running
check_ssh_agent_running() {
pgrep -f "$PROC_SSH_RAGENT" >/dev/null 2>&1
}
# Verify socket exists and is working (combined check)
verify_socket_working() {
local socket=$1
[ -S "$socket" ] && check_agent_socket "$socket"
}
# Verify socket exists, is working, and SSH process is running
verify_remote_agent_working() {
local socket=$1
[ -S "$socket" ] && check_agent_socket "$socket" && check_ssh_agent_running
}
# Display harmless error note for ssh-agent-mux
show_harmless_error_note() {
log_note "You can safely ignore these harmless errors:"
echo " $(color_stderr setaf 3)-$(color_stderr sgr0) 'ERROR [ssh_agent_mux] Unexpected error on socket ... when requesting session-bind@openssh.com extension: Agent: Protocol error: Unexpected response received'" >&2
echo " $(color_stderr setaf 3)-$(color_stderr sgr0) 'ERROR [ssh_agent_lib::agent] Error handling message: Failure'" >&2
}
# Filter out harmless Rust mux errors from log output
filter_rust_mux_errors() {
grep -vE "ERROR \[ssh_agent_lib::agent\] Error handling message: Failure|ERROR \[ssh_agent_mux\] Unexpected error on socket.*when requesting session-bind@openssh.com extension.*Protocol error.*Unexpected response received"
}
# Find identity file in common locations
find_identity_file() {
local key_file
# First, check if MY_SSH_KEY is set (from localvars.yml via playbook)
if [ -n "$MY_SSH_KEY" ] && [ "$MY_SSH_KEY" != "~/.ssh/id_unused" ]; then
# Expand ~ to $HOME if needed
key_file=$(echo "$MY_SSH_KEY" | sed "s|^~|$HOME|")
if [ -f "$key_file" ] && [ -r "$key_file" ]; then
echo "$key_file"
return 0
fi
fi
# Fall back to standard identity file locations
for key_file in ~/.ssh/id_ed25519 ~/.ssh/id_rsa ~/.ssh/id_ecdsa; do
if [ -f "$key_file" ] && [ -r "$key_file" ]; then
echo "$key_file"
return 0
fi
done
return 1
}
# Setup temporary SSH agent for identity file
setup_temp_agent() {
local identity_file=$1
local temp_socket temp_pid
if [ -z "$identity_file" ] || [ ! -f "$identity_file" ]; then
log_error "Invalid identity file: $identity_file"
return 1
fi
log_info "Creating temporary SSH agent for identity file..."
# Start ssh-agent and capture output
local agent_output
agent_output=$(ssh-agent -s 2>/dev/null)
if [ $? -ne 0 ]; then
log_error "Failed to start temporary SSH agent"
return 1
fi
# Extract socket and PID from agent output
# Handle formats like: SSH_AUTH_SOCK=/tmp/ssh-XXXXXX/agent.12345; export SSH_AUTH_SOCK;
# or: SSH_AUTH_SOCK=/tmp/ssh-XXXXXX/agent.12345
temp_socket=$(echo "$agent_output" | grep "SSH_AUTH_SOCK" | sed -E 's/.*SSH_AUTH_SOCK=([^;[:space:]]+).*/\1/' | head -1)
temp_pid=$(echo "$agent_output" | grep "SSH_AGENT_PID" | sed -E 's/.*SSH_AGENT_PID=([^;[:space:]]+).*/\1/' | head -1)
if [ -z "$temp_socket" ] || [ -z "$temp_pid" ]; then
log_error "Failed to parse ssh-agent output"
log_debug "ssh-agent output: $agent_output"
return 1
fi
# Export variables for use in this shell
export SSH_AUTH_SOCK="$temp_socket"
export SSH_AGENT_PID="$temp_pid"
# Add the identity file to the agent (this will prompt for passphrase once)
log_info "Adding identity file to temporary agent (you will be prompted for passphrase once)..."
if ! ssh-add "$identity_file"; then
log_error "Failed to add identity file to temporary agent"
cleanup_temp_agent
return 1
fi
# Set global variables
TEMP_AGENT_SOCK="$temp_socket"
TEMP_AGENT_PID="$temp_pid"
log_success "Temporary SSH agent created (PID: $temp_pid, Socket: $temp_socket)"
if [ "${DEBUG:-0}" == "1" ]; then
log_debug "Temporary agent details:"
log_debug " PID: $temp_pid"
log_debug " Socket: $temp_socket"
log_debug " Keys in temporary agent:"
SSH_AUTH_SOCK="$temp_socket" ssh-add -l 2>&1 | while IFS= read -r line; do
log_debug " $line"
done
fi
return 0
}
# Cleanup temporary SSH agent
cleanup_temp_agent() {
if [ -n "$TEMP_AGENT_PID" ]; then
if kill -0 "$TEMP_AGENT_PID" 2>/dev/null; then
log_info "Stopping temporary SSH agent (PID $TEMP_AGENT_PID)"
kill -TERM "$TEMP_AGENT_PID" 2>/dev/null || true
# Wait a bit for clean shutdown
sleep 0.5
# Force kill if still running
if kill -0 "$TEMP_AGENT_PID" 2>/dev/null; then
kill -KILL "$TEMP_AGENT_PID" 2>/dev/null || true
fi
fi
TEMP_AGENT_PID=""
fi
if [ -n "$TEMP_AGENT_SOCK" ] && [ -S "$TEMP_AGENT_SOCK" ]; then
log_info "Removing temporary SSH agent socket: $TEMP_AGENT_SOCK"
rm -f "$TEMP_AGENT_SOCK" 2>/dev/null || true
TEMP_AGENT_SOCK=""
fi
}
# Build SSH command with optional identity file
build_ssh_cmd() {
local cmd="ssh -a -F $PLAYBOOK_DIR/${SSH_CONFIG_FILE}_single"
# If we have a temporary agent, use it instead of -i to avoid multiple passphrase prompts
if [ -n "$TEMP_AGENT_SOCK" ]; then
# Use equals format to avoid quote issues when eval'd
cmd="$cmd -o IdentityAgent=$TEMP_AGENT_SOCK"
elif [ "$USE_IDENTITY_FILE" == "true" ] && [ -n "$IDENTITY_FILE" ]; then
cmd="$cmd -i \"$IDENTITY_FILE\""
fi
echo "$cmd"
}
# Determine user security level
determine_security_level() {
local ssh_cmd ssh_output ssh_exit_code my_level
# If we have a mux socket with the local key, use it directly
# Otherwise, use build_ssh_cmd which will use temp agent or identity file
if verify_socket_working "$MUX_SSH_AUTH_SOCK"; then
# Check if mux socket has the local key (needed for sca-key connection)
IDENTITY_FILE=$(find_identity_file)
if [ -n "$IDENTITY_FILE" ]; then
local id_fingerprint
id_fingerprint=$(ssh-keygen -lf "$IDENTITY_FILE" 2>/dev/null | awk '{print $2}')
if [ -n "$id_fingerprint" ]; then
if SSH_AUTH_SOCK="$MUX_SSH_AUTH_SOCK" ssh-add -l 2>/dev/null | grep -q "$id_fingerprint"; then
# Mux socket has the local key, use it
ssh_cmd="ssh -a -F $PLAYBOOK_DIR/${SSH_CONFIG_FILE}_single -o IdentityAgent=$MUX_SSH_AUTH_SOCK"
log_debug "Determining security level with mux socket: $ssh_cmd"
else
# Mux socket doesn't have local key, use build_ssh_cmd
ssh_cmd=$(build_ssh_cmd)
log_debug "Determining security level with: $ssh_cmd"
fi
else
# Can't get fingerprint, use build_ssh_cmd
ssh_cmd=$(build_ssh_cmd)
log_debug "Determining security level with: $ssh_cmd"
fi
else
# No identity file, use build_ssh_cmd
ssh_cmd=$(build_ssh_cmd)
log_debug "Determining security level with: $ssh_cmd"
fi
else
# No mux socket, use build_ssh_cmd
ssh_cmd=$(build_ssh_cmd)
log_debug "Determining security level with: $ssh_cmd"
fi
ssh_output=$(eval "$ssh_cmd -o \"SetEnv SCA_NOLEVEL=1\" sca-key groups 2>&1")
ssh_exit_code=$?
if [ "$ssh_exit_code" -ne 0 ]; then
log_error "SSH connection failed with exit code $ssh_exit_code"
log_error "SSH output: $ssh_output"
return 1
fi
my_level=$(echo "$ssh_output" | grep "level-" | grep -o -E "level-([0-9]*)" | cut -d"-" -f2 | sort -u | tail -1)
if [ -z "$my_level" ]; then
log_error "Could not determine your security level. Check your SSH connection."
if [ -n "$ssh_output" ]; then
log_error "SSH command output: $ssh_output"
fi
return 1
fi
echo "$my_level"
return 0
}
# Start remote SSH agent forwarder
start_remote_agent() {
local level=$1
local ssh_cmd ssh_pid
ssh_cmd=$(build_ssh_cmd)
log_info "Starting SSH agent forwarder (level $level)..."
SCA_LOCALUSER=$LOGNAME SCA_REMOTEUSER=$RUSERNAME SCA_IP=$(hostname) \
eval "$ssh_cmd -tt -a -L $SCA_SSH_AUTH_SOCK:/home/$RUSERNAME/yubikey-agent.sock -o \"SetEnv STY_LEVEL=$level SCA_LEVEL=$level\" sca-key ragent \"$LOGNAME,$USER,$RUSERNAME,$level,$LEVEL,$HOSTNAME,$HOME\"" >/dev/null 2>&1 &
ssh_pid=$!
log_success "SSH agent forwarder is running as PID $ssh_pid"
# Wait for connection to establish
sleep $SSH_INITIAL_DELAY
local iterations=0
while [ $iterations -lt $SSH_RETRY_MAX ]; do
((iterations++))
# Check if SSH process is still running
if ! kill -0 "$ssh_pid" 2>/dev/null; then
log_error "SSH process (PID $ssh_pid) died unexpectedly"
return 1
fi
# Check if socket exists and is working
if verify_socket_working "$SCA_SSH_AUTH_SOCK"; then
echo "$ssh_pid"
return 0
fi
log_info "Trying to connect to agent ($iterations/$SSH_RETRY_MAX)"
sleep $SSH_RETRY_DELAY
done
log_error "Cannot connect to agent after $SSH_RETRY_MAX attempts"
# Check if SSH process is still running
if kill -0 "$ssh_pid" 2>/dev/null; then
log_error "SSH process (PID $ssh_pid) is still running but socket is not working"
kill -TERM "$ssh_pid" 2>/dev/null
fi
return 1
}
# Wait for socket to be created
wait_for_socket() {
local socket=$1
local max_iterations=${2:-${SOCKET_WAIT_MAX:-10}}
local delay=${3:-${SOCKET_WAIT_DELAY:-0.1}}
local iterations=0
while [ ! -S "$socket" ] && [ "$iterations" -lt "$max_iterations" ]; do
((iterations++))
sleep "$delay"
done
[ -S "$socket" ]
}
#==============================================================================
# MULTIPLEXER SETUP
#==============================================================================
# Setup Python multiplexer (sshagentmux.py)
setup_python_multiplexer() {
log_info "Starting Python multiplexer (sshagentmux.py)..."
# The Python multiplexer uses SSH_AUTH_SOCK as the primary agent and --socket as the alternate
# We set SSH_AUTH_SOCK to the remote agent, and pass the local/temporary agent as --socket
# If ORG_SSH_AUTH_SOCK is /dev/null (no local agent), the multiplexer will detect it's invalid
# and just use the remote agent (SSH_AUTH_SOCK)
# Build level argument if MY_LEVEL is set
local level_arg=""
if [ -n "$MY_LEVEL" ]; then
level_arg="--level $MY_LEVEL"
fi
if [ "$REVERSE" == "1" ]; then
log_info "Reversing the order of the agents"
SSH_AUTH_SOCK=$SCA_SSH_AUTH_SOCK
# shellcheck disable=SC1054,SC1009,SC1056,SC1072,SC1073
eval "$($PLAYBOOK_DIR/sshagentmux.py --socket "${ORG_SSH_AUTH_SOCK}" --envname OMUX_)"
else
# Set SSH_AUTH_SOCK to remote agent (primary)
SSH_AUTH_SOCK=$SCA_SSH_AUTH_SOCK
eval "$($PLAYBOOK_DIR/sshagentmux.py --socket "${ORG_SSH_AUTH_SOCK}" --envname OMUX_)"
fi
log_info "Python multiplexer started (PID: $OMUX_SSH_AGENT_PID)"
}
# Execute command or start shell
execute_command_or_shell() {
if [ "$SHELL_MODE" == "1" ]; then
# Shell Mode: Output environment variables in ssh-agent format
# Disable cleanup trap so background processes keep running
trap - EXIT INT TERM
echo "SSH_AUTH_SOCK=$SSH_AUTH_SOCK; export SSH_AUTH_SOCK;"
# Output PID if available (prefer MUX_PID, fallback to SSH_PID)
AGENT_PID="${MUX_PID:-${SSH_PID:-}}"
if [ -n "$AGENT_PID" ]; then
echo "SSH_AGENT_PID=$AGENT_PID; export SSH_AGENT_PID;"
echo "echo Agent pid $AGENT_PID;"
fi
exit 0
elif [ "$SSH_MODE" == "1" ]; then
# SSH Mode: Direct SSH connection
# Disable cleanup trap since we're not starting any background processes
trap - EXIT INT TERM
# Select socket based on --key option (default: mux)
if [ "$KEY" == "mux" ]; then
SSH_SOCKET="$MUX_SSH_AUTH_SOCK"
elif [ "$KEY" == "local" ]; then
SSH_SOCKET="$ORG_SSH_AUTH_SOCK"
else
# Default to mux (KEY=remote or empty)
SSH_SOCKET="$MUX_SSH_AUTH_SOCK"
fi
# Verify socket exists and is working
if [ ! -S "$SSH_SOCKET" ] && [ ! -L "$SSH_SOCKET" ]; then
log_error "Socket does not exist: $SSH_SOCKET"
exit 1
fi
# Check if it's a symlink and resolve it
local resolved_socket="$SSH_SOCKET"
if [ -L "$SSH_SOCKET" ]; then
resolved_socket=$(readlink -f "$SSH_SOCKET" 2>/dev/null || readlink "$SSH_SOCKET")
log_debug "Socket $SSH_SOCKET is a symlink pointing to: $resolved_socket"
fi
if [ ! -S "$resolved_socket" ]; then
log_error "Socket symlink target does not exist: $resolved_socket"
exit 1
fi
if ! verify_socket_working "$SSH_SOCKET"; then
log_error "Socket is not working: $SSH_SOCKET"
exit 1
fi
# Debug: Show socket details and available keys
if [ "${DEBUG:-0}" == "1" ]; then
log_debug "Socket details:"
log_debug " Selected socket: $SSH_SOCKET"
if [ -L "$SSH_SOCKET" ]; then
log_debug " Type: symlink -> $resolved_socket"
else
log_debug " Type: regular socket"
fi
log_debug " Available keys:"
SSH_AUTH_SOCK="$SSH_SOCKET" ssh-add -l 2>&1 | while IFS= read -r line; do
log_debug " $line"
done
log_debug " Other socket paths:"
log_debug " MUX_SSH_AUTH_SOCK=$MUX_SSH_AUTH_SOCK"
log_debug " SCA_SSH_AUTH_SOCK=$SCA_SSH_AUTH_SOCK"
log_debug " ORG_SSH_AUTH_SOCK=$ORG_SSH_AUTH_SOCK"
if [ -n "$TEMP_AGENT_SOCK" ]; then
log_debug " TEMP_AGENT_SOCK=$TEMP_AGENT_SOCK"
fi
fi
log_info "Connecting via SSH config (IdentityAgent will use $SSH_SOCKET): ssh $SSH_ARGS"
# SSH config already has IdentityAgent set to mux socket, so just run ssh normally
local ssh_cmd="ssh"
# Add verbose flag in debug mode
if [ "${DEBUG:-0}" == "1" ]; then
ssh_cmd="$ssh_cmd -v"
fi
ssh_cmd="$ssh_cmd $SSH_ARGS"
if [ "${DEBUG:-0}" == "1" ]; then
log_debug "Executing SSH command: $ssh_cmd"
log_debug "SSH_AUTH_SOCK environment variable: ${SSH_AUTH_SOCK:-not set}"
# Show what SSH config resolves to for the target host
local target_host
target_host=$(echo "$SSH_ARGS" | awk '{print $1}')
if [ -n "$target_host" ]; then
log_debug "SSH config resolution for host '$target_host':"
ssh -G "$target_host" 2>/dev/null | grep -E "^identityagent" | while IFS= read -r line; do
log_debug " Config: $line"
done
# Resolve the IdentityAgent path from config
local config_identityagent
config_identityagent=$(ssh -G "$target_host" 2>/dev/null | grep "^identityagent " | sed 's/^identityagent //')
if [ -n "$config_identityagent" ]; then
log_debug " SSH config IdentityAgent resolves to: $config_identityagent"
if [ -L "$config_identityagent" ]; then
local resolved_agent
resolved_agent=$(readlink -f "$config_identityagent" 2>/dev/null || readlink "$config_identityagent")
log_debug " Which is a symlink to: $resolved_agent"
log_debug " Keys in resolved agent:"
SSH_AUTH_SOCK="$config_identityagent" ssh-add -l 2>&1 | while IFS= read -r line; do
log_debug " $line"
done
elif [ -S "$config_identityagent" ]; then
log_debug " Which is a regular socket"
log_debug " Keys in this agent:"
SSH_AUTH_SOCK="$config_identityagent" ssh-add -l 2>&1 | while IFS= read -r line; do
log_debug " $line"
done
fi
fi
fi
log_debug "Command will be executed with: eval"
log_debug "Environment variables that will be set:"
log_debug " SSH_AUTH_SOCK=$SSH_SOCKET (will be set to this value)"
# Verify the agent socket before executing
log_debug "Verifying agent socket before SSH execution:"
SSH_AUTH_SOCK="$SSH_SOCKET" ssh-add -l 2>&1 | while IFS= read -r line; do
log_debug " Agent keys: $line"
done
fi
SSH_AUTH_SOCK="$SSH_SOCKET" eval "$ssh_cmd"
local ssh_exit_code=$?
if [ $ssh_exit_code -ne 0 ]; then
log_error "SSH command failed with exit code $ssh_exit_code"
fi
# Clean up temporary agent after SSH connection completes
# The temporary agent was multiplexed with the remote agent, so it's no longer needed
if [ -n "$TEMP_AGENT_PID" ]; then
log_info "Cleaning up temporary SSH agent after SSH connection"
cleanup_temp_agent
fi
exit $ssh_exit_code
elif [ "$SUBSHELL_MODE" == "1" ]; then
# Subshell Mode: Open a subshell with the MUX agent environment set
log_info "Starting subshell with MUX agent environment"
$SHELL
elif [ -n "$CMD" ]; then
log_info "STARTING: $CMD"
eval $CMD
elif [ -n "$WAIT" ]; then
# Wait Mode: Monitor connection and restart if needed
log_info "WAIT in a Loop and check every $CHECK_SECONDS if the Connection is dead"
while true; do
# Check if we're intentionally exiting (Ctrl-C, etc.)
if [ "$SCA_EXITING" == "true" ]; then
log_info "Exiting..."
break
fi
# Check the appropriate socket based on whether we're using multiplexer
SOCKET_TO_CHECK="$MUX_SSH_AUTH_SOCK"
if [ ! -S "$MUX_SSH_AUTH_SOCK" ] || [ "$MUX_SSH_AUTH_SOCK" == "$SCA_SSH_AUTH_SOCK" ]; then
# No multiplexer, check remote agent directly
SOCKET_TO_CHECK="$SCA_SSH_AUTH_SOCK"
fi
if ! verify_socket_working "$SOCKET_TO_CHECK"; then
# Don't restart if we're intentionally exiting
if [ "$SCA_EXITING" == "true" ]; then
log_info "Exiting due to intentional termination"
break
fi
log_error "Can not Connect to agent!"
log_info "Stopping background processes before restart..."
kill_if_exists "$SSH_PID" "SSH"
kill_if_exists "$MUX_PID" "MUX"
# Restart Myself
export SCA_SUBSHELL=
export SSH_AUTH_SOCK=$ORG_SSH_AUTH_SOCK
log_info "Restarting MYSELF: $SCA_SCRIPT $ORG_ARGS"
exec $SCA_SCRIPT $ORG_ARGS
exit 255 # Should never be reached
else
echo -n "." >&2
fi
sleep $CHECK_SECONDS
done
else
# Default: Start Interactive Subshell
log_info "Starting Subshell"
$SHELL
fi
}
# Patch SSH config: add jump aliases (sca-jump, jump, etc.) to the Host line for
# this user's level in config_single.
# - 1st sed: strip any existing aliases after -sca-magic-jump (reset before re-apply)
# - 2nd sed: append "jump jump_local jump_my sca-jump ..." to L$MY_LEVEL-sca-magic-jump
#
# Only patches when needed; uses $PLAYBOOK_DIR/.sca-jump-level to remember:
# - LEVEL: last patched level. Re-patch if MY_LEVEL != LEVEL (backend or --level change).
# - If config_single is newer than the status file, re-patch (Ansible overwrote).
patch_jump_aliases() {
local f single status need=0
status="$PLAYBOOK_DIR/.sca-jump-level"
single="$PLAYBOOK_DIR/${SSH_CONFIG_FILE}_single"
log_info "Patching jump aliases (sca-jump, jump, etc.) for level $MY_LEVEL in SSH config"
# Need to patch if: no status yet, level changed, or config was overwritten (e.g. Ansible)
if [ ! -f "$status" ]; then
need=1
log_debug "Patch: no status file, will patch"
else
local stored
stored=$(grep -E '^LEVEL=' "$status" 2>/dev/null | cut -d= -f2)
if [ "$stored" != "$MY_LEVEL" ]; then
need=1
log_info "Patch: level changed ($stored -> $MY_LEVEL), will patch"
elif [ -f "$single" ] && [ "$single" -nt "$status" ]; then
need=1
log_info "Patch: ${SSH_CONFIG_FILE}_single newer than status (e.g. Ansible), will patch"
fi
fi
[ "$need" -eq 0 ] && log_debug "Patch: level $MY_LEVEL already applied, skip" && return 0
log_info "Patching jump aliases (sca-jump, jump, etc.) for level $MY_LEVEL in SSH config"
for f in "$single"; do
if [ ! -f "$f" ]; then
log_debug " Skip (not a file): $f"
continue
fi
log_info " Patching: $f"
sed -i.bak \
-e "s/\(-sca-magic-jump\)\(.*\)$/\1/g" \
-e "s/\(L$MY_LEVEL-sca-magic-jump\)/\1 jump jump_local jump_my sca-jump sca-jump_org sca-jump_local sca-jump_my sca-jump_mux/g" \
"$f"
done
echo "LEVEL=$MY_LEVEL" > "$status"
touch "$status"
}
# Setup new connection
setup_new_connection() {
log_info "No working agent found: Starting new connection"
rm -f $SCA_SSH_AUTH_SOCK
rm -f $MUX_SSH_AUTH_SOCK
# Determine User Security Level
MY_LEVEL=$(determine_security_level)