-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfunctions.sh
5081 lines (4501 loc) · 167 KB
/
functions.sh
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
#!/bin/bash
#
# Copyright © 2008-2016 RAAF Technology bv
#
# This file is part of Session.
#
# Session is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Session is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Session. If not, see <http://www.gnu.org/licenses/>.
# Function declarations have the following form:
#
# # foo(<parm1> [<parm2>]) # Required and optional parameters
# # Prints. # (Side-)effects, e.g., "Sets variable flurb"
# #
# # Does a trick to x because of z. # Description of foo's behavior
# #
# function foo {
# reportDebugFuncEntry "$*" "<var1> <var2>" # Names of global variables read, separated by spaces
# }
#
# report(<message_text>...)
# Prints.
#
# Print <message_text>s with standard framing text.
#
function report { printf "$*\n" ; }
function reportSession { report "Session: $*" ; }
function reportInfo { reportSession "Info: $*" ; }
function reportWarning { reportSession "Warning: $*" >&2 ; }
function reportError { reportSession "Error: ${FUNCNAME[1]}(): $*" >&2 ; }
function reportDebug {
[ ! "$debug" -o "$debug" = 0 ] && return
typeset msg
msg="Debug: ${FUNCNAME[1]}(): $*"
reportSession "$msg" >&2
[ ! "$logfile" ] || printf "%s\n" "$msg" >> "$logfile"
}
# reportDebugFuncEntry(<argument_name_vector> <environment_variable_name_vector> <additional_message>)
# Prints, Writes to log file.
#
# Report a debugging message containing:
# the argument string supplied to that function
# selected environment variable names separated by spaces
# and an additional message.
# E.g.,
# function foo { bar=BARVAL baz=BAZVAL reportDebugFuncEntry "$*" "bar baz" "have a nice day" ; }
# foo FOO1 FOO2
# => Session: Debug: Entering foo(FOO1 FOO2) with environment bar=BARVAL baz=BAZVAL ; have a nice day.
#
function reportDebugFuncEntry {
[ ! "$debug" -o "$debug" = 0 ] && return
typeset funcname="${FUNCNAME[1]}"
typeset args="$1"
typeset varname
typeset varval
typeset envstr=""
typeset msg
typeset IFS=" "
for varname in $2 ; do
varval="$(eval printf '%s\\n' "\$$varname")"
envstr="${envstr:+$envstr, }${varname}=${varval}"
done
msg="Entering $funcname($args)${envstr:+ with environment $envstr${3:+; }}$3"
reportSession "Debug: $msg" >&2
[ ! "$logfile" ] || printf "%s\n" "$msg" >> "$logfile"
return
}
# isLoopback(<domain_name_or_address>)
# Returns truth value.
#
# Return 0 if address is loopback domain name or address; non-zero otherwise.
#
function isLoopback {
reportDebugFuncEntry "$*"
# Handles only IPv4 at present
[[ "$1" =~ ^localhost\. ]] || [[ "$1" =~ ^127\. ]]
}
# isLocal(<name>)
# Returns truth value.
#
# Return 0 if name matches non-null short local hostname, 1 otherwise.
#
function isLocal {
reportDebugFuncEntry "$*"
[ "$hostname" ] || return 1
[ "$1" = "$hostname" ]
}
# toLocalWindowsPath(<path>)
# Prints.
#
# Convert path to Windows-style but with forward slashes.
# Inspired by Cygwin's cygpath.
#
# Should only be used to generate path (string) arguments for local Windows commands.
#
function toLocalWindowsPath {
reportDebugFuncEntry "$*"
typeset input="$1"
typeset output
typeset path
typeset file
if [ ! "$input" ]; then
reportError "No input given"
return 1
fi
if [[ "$input" =~ : ]]; then
# Windows path was passed (ie. contains colon). Only forward slashes.
reportDebug "Detected colon, only forwarding slashes"
output="$(printf "$input\n" | tr -d '\015' | sed 's|\\|/|g')"
elif [ -d "$input" ]; then
# Path exists locally and is a directory, enter, read out and forward slashes.
reportDebug "Path exists locally and is a directory. Entering, read out and forwarding slashes"
output="$(cd "$input" ; cmd.exe /c cd | tr -d '\015' | sed 's|\\|/|g')"
elif [ -f "$input" -o "$(dirname "$input")" != "/" ]; then
# Path exists locally and is a file, enter parent, read out and forward slashes.
reportDebug "Path exists locally and is a file. Entering, read out and forwarding slashes"
path="$(cd "$(dirname "$input")" ; cmd.exe /c cd | tr -d '\015' | sed 's|\\|/|g')"
file="$(basename "$input")"
output="$path/$file"
else
# File does not exist locally, and contains no colon. Prepend C: and forward slashes.
reportDebug "File does not exist locally and contains no colon. Prepending C: and forwarding slashes"
output="$(printf "C:$input\n" | tr -d '\015' | sed 's|\\|/|g' )"
fi
reportDebug "Incoming: $input"
reportDebug "Outgoing: $output"
report "$output"
return 0
}
# toRemoteWindowsPath(<path>)
# Prints.
#
# Convert path to Windows-style but with forward slashes.
#
function toRemoteWindowsPath {
reportDebugFuncEntry "$*"
typeset input="$1"
if [ ! "$input" ]; then
reportError "No input given"
return 1
fi
if [[ "$input" =~ : ]]; then
output="$(printf "$input\n" | sed 's|\\|/|g')"
else
output="$(printf "C:$input\n" | sed 's|\\|/|g' )"
fi
reportDebug "Incoming: $input"
reportDebug "Outgoing: $output"
report "$output"
return 0
}
# viaScript(<command>)
# Writes a shell or batch script, executes and cleans up.
#
# Handle execution of <command> via a platform's native scripting method.
#
function viaScript {
reportDebugFuncEntry "$*"
typeset command="$*"
typeset retval
typeset nametmp="${name}.$$"
[ "$nametmp" ] || nametmp=local
if [ "$platform" = "linux" -o "$platform" = "bsd" -o "$platform" = "macosx" ]; then
reportDebug "Writing UNIX shell script"
echo "#!/bin/sh" > "$usrcfd/tmp/session.tell.$nametmp.sh"
echo "$command" | sed 's/^[[:space:]]*//' 2> /dev/null >> "$usrcfd/tmp/session.tell.$nametmp.sh"
reportDebug "Executing $usrcfd/tmp/session.tell.$nametmp.sh"
sh "$usrcfd/tmp/session.tell.$nametmp.sh"
retval="$?"
if [ "$debug" ]; then
reportDebug "Not removing $usrcfd/tmp/session.tell.$nametmp.sh"
else
rm "$usrcfd/tmp/session.tell.$nametmp.sh"
fi
elif [ "$platform" = "windows" ]; then
reportDebug "Writing DOS batch script"
printf "@echo off\n" > "$usrcfd/tmp/session.tell.$nametmp.bat.unix"
printf '%s\n' "$command" | sed 's/^[[:space:]]*//' 2> /dev/null >> "$usrcfd/tmp/session.tell.$nametmp.bat.unix"
reportDebug "Correcting for DOS style line endings"
sed 's/$/\r/' "$usrcfd/tmp/session.tell.$nametmp.bat.unix" > "$usrcfd/tmp/session.tell.$nametmp.bat"
rm "$usrcfd/tmp/session.tell.$nametmp.bat.unix"
reportDebug "Executing $usrcfd/tmp/session.tell.$nametmp.bat"
cd "$usrcfd/tmp" ; cmd.exe /c "session.tell.$nametmp.bat" ; cd - > /dev/null
retval="$?"
if [ "$debug" ]; then
reportDebug "Not removing $usrcfd/tmp/session.tell.$nametmp.bat"
else
rm "$usrcfd/tmp/session.tell.$nametmp.bat"
fi
else
reportError "Unknown platform specified: $platform"
return 1
fi
return $retval
}
# viaWscript(<command>)
# Writes a Visual Basic Script to execute a command in the background, executes and cleans up.
#
# Handle execution of <command> via a visual basic wrapper.
#
function viaWscript {
reportDebugFuncEntry "$*"
typeset command="$*"
typeset retval
typeset nametmp="${name}.$$"
[ "$nametmp" ] || nametmp=local
if [ "$platform" = "windows" ]; then
reportDebug "Writing DOS batch script"
printf "@echo off\n" > "$usrcfd/tmp/session.tell.$nametmp.bat.unix"
printf '%s\n' "$command" | sed 's/^[[:space:]]*//' 2> /dev/null >> "$usrcfd/tmp/session.tell.$nametmp.bat.unix"
reportDebug "Correcting for DOS style line endings"
sed 's/$/\r/' "$usrcfd/tmp/session.tell.$nametmp.bat.unix" > "$usrcfd/tmp/session.tell.$nametmp.bat"
rm "$usrcfd/tmp/session.tell.$nametmp.bat.unix"
reportDebug "Writing Wscript execution wrapper"
printf 'CreateObject("Wscript.Shell").Run """" & WScript.Arguments(0) & """", 0, False' > "$usrcfd/tmp/session.tell.$nametmp.vbs"
reportDebug "Executing $usrcfd/tmp/session.tell.$nametmp.bat via Wscript execution wrapper"
cd "$usrcfd/tmp" ; wscript.exe "session.tell.$nametmp.vbs" "session.tell.$nametmp.bat" //nologo ; cd - > /dev/null
retval="$?"
if [ "$debug" ]; then
reportDebug "Not removing $usrcfd/tmp/session.tell.$nametmp.vbs"
reportDebug "Not removing $usrcfd/tmp/session.tell.$nametmp.bat"
else
sleep 1
rm "$usrcfd/tmp/session.tell.$nametmp.bat"
rm "$usrcfd/tmp/session.tell.$nametmp.vbs"
fi
else
reportError "Visual Basic Script wrapper not supported on platform: $platform"
return 1
fi
return $retval
}
# localTellCommandWriter(<command>)
# Prints.
#
# Print <command> for immediate local execution.
#
function localTellCommandWriter {
reportDebugFuncEntry "$*"
typeset command="$*"
printf '%s\n' "$command"
}
# psexecTellCommandWriter(<addr> <user> <pass> <command>)
# Prints.
#
# Print <command> for execution over smb using psexec.
#
function psexecTellCommandWriter {
reportDebugFuncEntry "$*"
typeset addr="$1"
typeset user="$2"
typeset pass="$3"
typeset command="$4"
# Older version of psexec?
if [ "$user" ]; then user="-u \"$user\"" ; fi
if [ "$pass" ]; then pass="-p \"$pass\"" ; fi
printf "$psexec \\\\\\\\$addr -h $user $pass cmd.exe /c $command\n"
}
# winexeTellCommandWriter(<addr> <user> <pass> <command>)
# Prints.
#
# Print <command> for execution over smb using winexe.
#
function winexeTellCommandWriter {
reportDebugFuncEntry "$*"
typeset addr="$1"
typeset user="$2"
typeset pass="$3"
typeset command="$4"
# Make sure we only pass --password when pass was not empty.
if [ ! -z "$pass" ]; then
# printf "winexe -U '%s%%%s' //%s 'cmd.exe /c \"%s\"' 2> /dev/null\n" "$user" "$pass" "$addr" "$command"
echo "winexe -U '$user%$pass' //$addr 'cmd.exe /c \"$command\"' 2> /dev/null"
else
# printf "winexe -U '%s' //%s 'cmd.exe /c \"%s\"' 2> /dev/null\n" "$user" "$addr" "$command"
echo "winexe -U '$user' //$addr 'cmd.exe /c \"$command\"' 2> /dev/null"
fi
}
# plinkTellCommandWriter(<addr> <user> <command>)
# Prints.
#
# Print <command> for execution over ssh using plink.
#
function plinkTellCommandWriter {
reportDebugFuncEntry "$*"
typeset addr="$1"
typeset user="$2"
typeset command="$3"
typeset escapedCommand="$(echo $command | sed -e 's#\(\^\)#^\1#g' -e 's#\([\]\)#^\1#g' -e 's#\([&]\)#^\1#g' -e 's#\([>]\)#^\1#g' -e 's#\([<]\)#^\1#g' -e 's#\([|]\)#^\1#g' -e 's#"#^"#g')"
typeset nametmp="${name}.$$"
[ "$nametmp" ] || nametmp=local
printf "echo $escapedCommand > \"session.tell.$nametmp.command\"\n"
printf "$plink -batch -x $sshopts -l \"$user\" $addr -m \"session.tell.$nametmp.command\"\n"
}
# sshTellCommandWriter(<host> <user> <command>)
# Prints.
#
# Print <command> for execution using ssh on <host> as <user>.
#
function sshTellCommandWriter {
reportDebugFuncEntry "$*"
typeset host="$1"
typeset user="$2"
typeset command="$3"
printf "ssh $sshopts -l '$user' '$host' -q '$command'\n"
}
# localSendCommandWriter(<source> <target>)
# Prints.
#
# Print a command for sending data using the appropriate local copy command.
#
function localSendCommandWriter {
reportDebugFuncEntry "$*"
typeset source
typeset target
if [ "$platform" = "linux" -o "$platform" = "bsd" -o "$platform" = "macosx" ]; then
source="$1"
target="$2"
printf "cp -Rpd \"$source\" \"$target\" >/dev/null 2>&1 </dev/null\n"
elif [ "$platform" = "windows" ]; then
source="$(toLocalWindowsPath "$1")"
target="$(toLocalWindowsPath "$2")"
printf "$robocopy /e \"$source\" \"$target\" >nul 2>&1\n"
else
reportError "Unknown platform specified: $platform"
return 1
fi
return 0
}
# robocopySendCommandWriter(<addr> <user> <pass> <source> <target>)
# Prints.
#
# Print a command for sending data using robocopy remotely.
#
function robocopySendCommandWriter {
reportDebugFuncEntry "$*"
typeset addr="$1"
typeset user="$2"
typeset pass="$3"
typeset source="$(toLocalWindowsPath "$4")"
typeset target="$(toLocalWindowsPath "$5")"
typeset driveLetter
driveLetter="$(printf "$target\n" | cut -d ':' -f 1)"
reportDebug "Extracted drive letter $driveLetter from $target"
target="$(printf "$target\n" | sed "s|$driveLetter:|//${addr}/${driveLetter}\$|" | sed 's|/|\\|g')"
reportDebug "Target is now $target"
if [ "$pass" ]; then pass="\"$pass\"" ; fi
printf %s "
net use \\\\$addr\\$driveLetter\$ /user:\"${user}\" ${pass} 2>nul
$robocopy /e \"$source\" \"$target\" >nul 2>&1
net use \\\\$addr\\$driveLetter\$ /delete >nul 2>&1
" | sed 's/^[[:space:]]*//'
}
# smbclientSendCommandWriter(<addr> <user> <pass> <source> <target>)
# Prints.
#
# Print a command for sending data using smbclient remotely.
#
function smbclientSendCommandWriter {
reportDebugFuncEntry "$*"
typeset addr="$1"
typeset user="$2"
typeset pass="$3"
typeset source="$4"
typeset target="$(toRemoteWindowsPath "$5")"
typeset share
typeset smbcommand
share="$(printf "$target\n" | sed "s|:|$|" | cut -d/ -f 1 | sed 's|"||g')"
target="$(printf "$target\n" | sed 's|/|\\\\|g' | cut -d: -f2- | sed 's|"||g')"
smbcommand="mkdir \"$target\";cd \"$target\";lcd \"$source\";prompt off;recurse on;mput *;quit"
if [ "$pass" ]; then pass="%$pass" ; fi
printf "smbclient //$addr/$share -U \"${user}${pass}\" -c '$smbcommand' 2>/dev/null\n"
}
# pscpSendCommandWriter(<addr> <uopts> <source> <target>)
# Prints.
#
# Print a command for sending data using pscp remotely.
#
function pscpSendCommandWriter {
reportDebugFuncEntry "$*"
typeset addr="$1"
typeset uopts="$2"
typeset source="$(toLocalWindowsPath "$3")"
typeset target="$4"
printf "$pscp $sshopts -scp -p -q -r -l \"$uopts\" \"$source\" $addr:\"$target\"\n"
}
# scpSendCommandWriter(<addr> <uopts> <source> <target>)
# Prints.
#
# Print a command for sending data using scp remotely.
#
function scpSendCommandWriter {
reportDebugFuncEntry "$*"
typeset addr="$1"
typeset uopts="$2"
typeset source="$3"
typeset target="$4"
typeset sshuser
sshuser="$(printf "$uopts\n" | sed 's|\ |\\ |g'| sed 's|\\|\\\\|g')"
printf "scp -q $sshopts -r \"$source\" $sshuser@$addr:\"$target\"\n"
}
# toolFinder()
# Writes $usrcfd/cfg/tools.required and $usrcfd/cfg/tools.found.
#
# Detect required and optional tools.
#
function toolFinder {
reportDebugFuncEntry "$*" "usrcfd color"
typeset IFS=","
typeset tools_terminal
typeset tools_desktop
typeset tools_browser
typeset tools_access_result
typeset tooltypes
typeset tooltype
typeset values
typeset tool
# Make sure color is off if requested.
if [ "$color" = 0 ]; then unset color; fi
# First write out tools.required.
if [ "$platform" = "linux" -o "$platform" = "bsd" -o "$platform" = "macosx" ]; then
printf "tools_session='awk,cut,grep,host,lsof,$nmap,sed,tr,ps'\n" > "$usrcfd/cfg/tools.required"
printf "tools_execute='ssh,winexe'\n" >> "$usrcfd/cfg/tools.required"
printf "tools_agent='ssh-agent,ssh-add'\n" >> "$usrcfd/cfg/tools.required"
printf "tools_send='cp,scp,smbclient'\n" >> "$usrcfd/cfg/tools.required"
elif [ "$platform" = "windows" ]; then
printf "tools_session='awk,cut,grep,$nmap,nslookup.exe,sed,tr,$pslist'\n" > "$usrcfd/cfg/tools.required"
printf "tools_execute='$plink,$psexec'\n" >> "$usrcfd/cfg/tools.required"
printf "tools_agent='$pageant'\n" >> "$usrcfd/cfg/tools.required"
printf "tools_send='$pscp,$robocopy'\n" >> "$usrcfd/cfg/tools.required"
else
printf "# unidentified platform specified: $platform\n" > "$usrcfd/cfg/tools.required"
printf "# toolFinder says you need to define tools_ variables!\n" >> "$usrcfd/cfg/tools.required"
fi
if [ "$terminal" = "putty" ]; then
tools_terminal="$putty"
elif [ "$terminal" = "apple" ]; then
PATH="${PATH}:/Applications/Utilities/Terminal.app/Contents/MacOS"
tools_terminal="osascript,Terminal"
elif [ "$terminal" = "gnome" ]; then
tools_terminal="gnome-terminal,pgrep,xdotool"
elif [ "$terminal" = "screen" ]; then
tools_terminal="screen"
fi
if [ "$desktop" = "mstsc" ]; then
tools_desktop="$cryptrdp5,$mstsc"
elif [ "$desktop" = "amsrdc" ]; then
PATH="${PATH}:/Applications/Microsoft Remote Desktop.app/Contents/MacOS"
tools_desktop="Microsoft Remote Desktop"
elif [ "$desktop" = "rdesktop" ]; then
tools_desktop="rdesktop"
fi
if [ "$browser" = "windows" ]; then
tools_browser="$explorer"
elif [ "$browser" = "apple" ]; then
tools_browser="open"
elif [ "$browser" = "gnome" ]; then
# Some linux distributions name 'open' differently. Quick fix.
if [ -x "/usr/bin/xdg-open" ];then
tools_browser="xdg-open"
elif [ -x "/usr/bin/gnome-open" ];then
tools_browser="gnome-open"
else
tools_browser="open"
fi
fi
# Construct tools_access_result from tools_terminal, tools_desktop and tools_browser
for tools_access_type in tools_terminal tools_desktop tools_browser; do
typeset current="$(eval printf '%s\\n' "\$$tools_access_type" | tr '\r\n' ',' | sed 's|,$||g')"
if [ "$current" ]; then
tools_access_result="$current,$tools_access_result"
fi
done
printf "tools_access='$tools_access_result'\n" | sed "s|,'$|'|" >> "$usrcfd/cfg/tools.required"
# Clean up old tools.found first.
rm -f "$usrcfd/cfg/tools.found"
# Read tooltypes from generated tools.required, create comma-separated list.
tooltypes="$(cat "$usrcfd/cfg/tools.required" | cut -d "=" -f 1 | tr '\r\n' ',' | sed 's|,$||g')"
# Loop over all tooltypes and for each tooltype over its values.
for tooltype in $tooltypes ; do
values="$(cat "$usrcfd/cfg/tools.required" | grep $tooltype | cut -d '=' -f 2 | sed "s|'||g")"
printf "$(printf "$tooltype\n" | cut -d "_" -f 2): "
printf "${tooltype}_found='" >> "$usrcfd/cfg/tools.found"
for tool in $values ; do
if [ ! "$color" ]; then
unset color_red color_green color_yellow color_blue color_end
fi
if [ "$(basename "$(which $tool 2>/dev/null)")" ]; then
printf "${color_green}${tool}${color_end} "
printf "$tool," >> "$usrcfd/cfg/tools.found"
else
printf "(${color_red}${tool}${color_end}) "
fi
done
printf "\n"
printf "'\n" >> "$usrcfd/cfg/tools.found"
done
printf "\n"
# Remove trailing commas from tools.found.
sed -e "s|,'$|'|" "$usrcfd/cfg/tools.found" > "$usrcfd/tmp/tools.found" 2>/dev/null
mv "$usrcfd/tmp/tools.found" "$usrcfd/cfg/tools.found"
}
# handleSshPrivateKeys()
# Detects private keys, handles automatic agent starting when needed.
#
# Check for private keys and be smart about agent handling.
#
function handleSshPrivateKeys {
reportDebugFuncEntry "$*"
# Set private key option when private key found.
if [ "$platform" = "linux" -o "$platform" = "bsd" -o "$platform" = "macosx" ]; then
# Look for OpenSSH style public/private keypair.
if [ -e "$HOME/.ssh/id_dsa" ]; then
sshkey="$HOME/.ssh/id_dsa"
sshpub="$HOME/.ssh/id_dsa.pub"
sshopts="-i $sshkey"
elif [ -e "$HOME/.ssh/id_rsa" ]; then
sshkey="$HOME/.ssh/id_rsa"
sshpub="$HOME/.ssh/id_rsa.pub"
sshopts="-i $sshkey"
fi
# Load private key into ssh-agent if agent handling is enabled.
if [ "$sshkey" -a "$agent" == "ssh-agent" ]; then
sshagentfile="$usrcfd/tmp/session.ssh-agent.out"
sshagentproc="$(ps x | grep ssh-agent | grep -v grep)"
if [ "$SSH_AUTH_SOCK" ]; then
reportDebug "Reusing previously set environment variables for running ssh-agent"
printf "SSH_AUTH_SOCK=$SSH_AUTH_SOCK; export SSH_AUTH_SOCK;\n" > "$sshagentfile"
printf "SSH_AGENT_PID=$SSH_AGENT_PID; export SSH_AGENT_PID;\n" >> "$sshagentfile"
source "$sshagentfile"
elif [ "$sshagentproc" ]; then
reportDebug "Environment values not set but agent is running, inspecting agent"
reportDebug "I'm using $privy lsof to do this"
sshagentlsof="$($privy lsof /tmp/ssh-*/agent.* 2> /dev/null | grep ssh-agent | tail -n1)"
SSH_AUTH_SOCK="$(printf "$sshagentlsof\n" | awk '{print $8}')"
SSH_AGENT_PID="$(printf "$sshagentlsof\n" | awk '{print $2}')"
printf "SSH_AUTH_SOCK=$SSH_AUTH_SOCK; export SSH_AUTH_SOCK;\n" > "$sshagentfile"
printf "SSH_AGENT_PID=$SSH_AGENT_PID; export SSH_AGENT_PID;\n" >> "$sshagentfile"
source "$sshagentfile"
elif [ ! "$sshagentproc" ]; then
reportInfo "You have a private key; starting new ssh-agent"
ssh-agent | grep -v "^echo " > "$sshagentfile"
chmod 600 "$sshagentfile"
source "$sshagentfile"
else
reportError "Unexpected exit"
exit 1
fi
sshkeyloaded="$(ssh-add -l | grep "$sshkey")"
if [ -z "$sshkeyloaded" ]; then
reportDebug "Loading ssh key(s) into ssh-agent "
ssh-add
fi
elif [ "$agent" == "gpg-agent" ]; then
reportDebug "You have set agent to gpg-agent; assuming your keys are loaded."
sshkey=in-gpg
fi
# Disable strict host and reverse mapping checks if not already set.
if [ -e "$HOME/.ssh/config" ]; then
if [[ ! "$(cat "$HOME/.ssh/config")" =~ "StrictHostKeyChecking" ]]; then
printf "StrictHostKeyChecking no\n" >> "$HOME/.ssh/config"
fi
else
mkdir -p "$HOME/.ssh"
printf "StrictHostKeyChecking no\n" >> "$HOME/.ssh/config"
fi
elif [ "$platform" = "windows" ]; then
# Look for PuTTY style public/private keypair.
if [ -e "$usrcfd/../.ssh/id_dsa.ppk" ]; then
sshkey="$(toLocalWindowsPath "$usrcfd/../.ssh/id_dsa.ppk")"
sshpub="$(toLocalWindowsPath "$usrcfd/../.ssh/id_dsa.pub")"
sshopts="-i \"$sshkey\""
elif [ -e "$usrcfd/../.ssh/id_rsa.ppk" ]; then
sshkey="$(toLocalWindowsPath "$usrcfd/../.ssh/id_rsa.ppk")"
sshpub="$(toLocalWindowsPath "$usrcfd/../.ssh/id_rsa.pub")"
sshopts="-i \"$sshkey\""
fi
# Load private key into pageant if agent handling is enabled.
if [ "$sshkey" -a "$agent" == "pageant" ]; then
running="$($pslist | grep -i $pageant | grep -v grep)"
if [ ! "$running" ]; then
reportInfo "You have a private key; loading into ssh-agent"
typeset command="start /b $pageant \"$sshkey\""
viaScript "$(localTellCommandWriter "$command")" &
sleep 10
fi
elif [ "$sshkey" -a "$agent" == "gpg-agent" ]; then
reportInfo "You have set agent to gpg-agent; assuming your keys are loaded."
fi
fi
}
# handleQuotedRegExpBehaviour()
# Sets shell options.
#
# Check quoted regexp behaviour and take appropriate action.
#
function handleQuotedRegExpBehaviour {
reportDebugFuncEntry "$*"
# http://dougbarton.us/Bash/Bash-FAQ.html, see E15
# http://ftp.gnu.org/gnu/bash/bash-3.2-patches/bash32-010, regarding quoted regexp matching
# http://ftp.gnu.org/gnu/bash/bash-3.2-patches/bash32-039, regarding compat31 shopt
typeset major="${BASH_VERSINFO[0]}"
typeset minor="${BASH_VERSINFO[1]}"
typeset patch="${BASH_VERSINFO[2]}"
if [ "$major" -lt 3 ]; then # Major is lower than 3
reportError "Bash major version lower than 3, exiting"
exit 1
elif [ "$major" = 3 ]; then # Major is 3
if [ "$minor" -lt 2 ]; then # Version 3.0 and 3.1 will work
reportDebug "Bash version is old but will work with quoted regexp matching"
elif [ "$minor" -eq 2 ]; then # Handle 3.2 idiosyncracies
if [ 0 -le "$patch" -a "$patch" -le 9 ]; then # Version 3.2.0 to 3.2.9 is broken
reportError "Bash version has known unfixed issues with quoted regexp matching"
exit 1
elif [ "$patch" -lt 39 ]; then # Version 3.2.10 to 3.2.38 might work
reportDebug "Bash version is old but may work with quoted regexp matching"
else # Version 3.2.39 and higher has compat31
reportDebug "Setting shell option compat31 to handle quoted rexexp matching"
shopt -s compat31
fi
elif [ "$minor" -gt 2 ]; then # Currently non-existing version of bash 3.3 or higher but not 4
reportDebug "Setting shell option compat31 to handle quoted rexexp matching"
shopt -s compat31
fi
else # 4 and higher.
reportDebug "Setting shell option compat31 to handle quoted rexexp matching"
shopt -s compat31
fi
}
# sshSendKey(<username>)
# Sends a local public key to another machine.
#
# This function takes a username which is supposed to exist on a remote
# system and first sends the key to the remote system and then executes
# the commandlist routine below to install the key for the specified user.
#
function sshSendKey {
reportDebugFuncEntry "$*" "sshpub addr"
typeset source="$sshpub"
typeset target="/tmp/pubkey"
typeset user="$1"
typeset retval
typeset commandlist
[ "$addr" ] || { reportError "\$addr is empty; aborting" ; return 1 ; }
[ "$sshpub" ] || { reportError "\$sshpub is empty; aborting" ; return 1 ; }
reportInfo "Attempting to send public key $sshpub"
viaScript "$(${sshsend}SendCommandWriter "$addr" "$user" "$source" "$target")"
retval="$?"
if [ "$retval" != 0 ]; then
reportError "Failed to send $sshpub with return code: $retval"
return 1
fi
reportInfo "Key sent successfully; will now attempt to install it"
# Keep commandlist as one line, plink will go crazy if you do not.
commandlist='[ "$HOME" ] || exit 1 ; mkdir -p $HOME/.ssh ; touch $HOME/.ssh/authorized_keys ; cat $HOME/.ssh/authorized_keys /tmp/pubkey | sort | uniq > /tmp/authorized_keys ; mv /tmp/authorized_keys $HOME/.ssh/authorized_keys ; rm /tmp/pubkey ; chmod 755 $HOME ; chmod 755 $HOME/.ssh ; chmod 600 $HOME/.ssh/authorized_keys'
viaScript "$(${sshtell}TellCommandWriter "$addr" "$user" "$commandlist")"
retval="$?"
if [ "$retval" != 0 ]; then
reportError "Installation attempt failed with return code: $retval"
return 1
fi
reportInfo "Key installed"
return 0
}
# winStoreCreds(<type> <name>)
# Writes pwd files.
#
# Store credentials for services that talk smb or rdp.
#
function winStoreCreds {
reportDebugFuncEntry "$*"
typeset store_type="$1"
typeset store_name="$2"
typeset store_pass1="unset1"
typeset store_pass2="unset2"
while [ "$store_pass1" != "$store_pass2" ]; do
printf "Please supply password for $store_type $store_name: "
stty -echo
read store_pass1
stty echo
printf "\n"
printf "Retype password for confirmation: "
stty -echo
read store_pass2
stty echo
printf "\n"
if [ "$store_pass1" != "$store_pass2" ]; then
reportError "Passwords do not match"
return 1
fi
done
mkdir -p "$usrcfd/sys/$name"
if [ "$user" = "$admin" ]; then
printf "$store_pass2\n" > "$usrcfd/sys/$name/user.pwd"
printf "$store_pass2\n" > "$usrcfd/sys/$name/admin.pwd"
else
printf "$store_pass2\n" > "$usrcfd/sys/$name/$store_type.pwd"
fi
return 0
}
# osglobals(<osmt>)
# Sets osstop, osreboot and oslisten.
#
# Set generic global variables for commands that interact
# with the given operating system.
#
function osGlobals {
reportDebugFuncEntry "$*"
# Defaults
osstop="/sbin/shutdown -h now"
osreboot="reboot"
oslisten="netstat -na|grep \"LISTEN\"|grep -w -e \"0\.0\.0\.0:$port\" -e \":::$port\" -e \"$addr:$port\" "
# Override defaults given above for certain osses.
case "$1" in
alpine*)
osstop="/sbin/poweroff"
;;
haiku)
osstop="/bin/shutdown"
;;
aix*|hpux*)
osstop="/sbin/shutdown -hy 0"
;;
dfbsd*|fbsd*)
osstop="/sbin/shutdown -p now"
;;
nbsd*|obsd*)
osstop="/sbin/shutdown -h -p now"
;;
chimera|sol10|sol11)
osstop="/usr/sbin/poweroff"
;;
windows-like|win2k3|win2k8|win2k12|winxp|winv|win7|win8|win10|reactos)
osstop="shutdown -s -t 01"
osreboot="shutdown -r -t 01"
oslisten="netstat -na|findstr \"LISTEN\"|findstr \"\<0\.0\.0\.0:$port\> \<$addr:$port\>\" "
;;
esac
}
# capsFirst(<arg>...)
# Prints.
#
# Echo all args with first one capitalized if it starts with a letter.
#
function capsFirst {
reportDebugFuncEntry "$*"
typeset input="$*"
typeset upr
case "$input" in
a*) upr=A ;; b*) upr=B ;; c*) upr=C ;; d*) upr=D ;;
e*) upr=E ;; f*) upr=F ;; g*) upr=G ;; h*) upr=H ;;
i*) upr=I ;; j*) upr=J ;; k*) upr=K ;; l*) upr=L ;;
m*) upr=M ;; n*) upr=N ;; o*) upr=O ;; p*) upr=P ;;
q*) upr=Q ;; r*) upr=R ;; s*) upr=S ;; t*) upr=T ;;
u*) upr=U ;; v*) upr=V ;; w*) upr=W ;; x*) upr=X ;;
y*) upr=Y ;; z*) upr=Z ;;
*) printf "$input\n" ; return ; ;;
esac
printf "${upr}${input#?}\n"
}
# rndGen(<count> <split_char>)
# Prints.
#
# Print <count> random 2-digit hex numerals separated by <split_char>.
#
function rndGen {
reportDebugFuncEntry "$*"
typeset count=1
typeset split
typeset part
typeset length
if [ "$1" ]; then
count="$1"
fi
if [ "$2" ]; then
split="$2"
fi
while [ "$count" -gt 0 ]; do
part="$(printf '%02X' $RANDOM | cut -c2-3)"
length=${#part}
if [ "$length" -lt 2 ]; then
part="$part$part"
fi
printf "$part"
if [ "$count" != 1 ]; then
printf "$split"
fi
let count-=1
done
printf "\n"
}
# macGen(<type>)
# Sets macaddr. Writes $usrcfd/sys/$name/generated.mac.
#
# Generate a MAC address for adapter of the give type.
#
function macGen {
reportDebugFuncEntry "$*"
typeset vendor_vmw="00:50:56"
typeset vendor_xen="00:16:3E"
typeset vendor_kvm="54:52:00"
typeset first
typeset newfirst
typeset genmac
typeset venmac
typeset indec
typeset check
case "$1" in
global)
genmac="$(rndGen 6 :)"
first="$(printf "$genmac\n" | cut -d : -f 1)"
indec="$(printf "%d" 0x$first)"
check="$(( $indec % 2 ))"
if [ "$check" != 0 ]; then
newfirst="$(printf "%x" $(( $indec + 1)))"
genmac="$(printf "$genmac\n" | sed "s|^$first|$newfirst|")"
fi
macaddr="$genmac"
;;
vmw|vmf|esx)
venmac="$vendor_vmw"
genmac="$(rndGen 3 :)"
macaddr="$venmac:$genmac"
;;
xen)
venmac="$vendor_xen"
genmac="$(rndGen 3 :)"
macaddr="$venmac:$genmac"
;;
kvm)
venmac="$vendor_kvm"
genmac="$(rndGen 3 :)"
macaddr="$venmac:$genmac"
;;
*)
reportError "No macGen method specified; expected any of global|vmw|vmf|esx|xen|kvm"
return 1
;;
esac
mkdir -p "$usrcfd/sys/$name"
printf "$macaddr\n" > "$usrcfd/sys/$name/generated.mac"
return 0
}