-
Notifications
You must be signed in to change notification settings - Fork 3
/
vcli
executable file
·2317 lines (2214 loc) · 80.4 KB
/
vcli
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 bash
# vcli internal variables
declare SCRIPTNAME
SCRIPTNAME="$(basename "$0")"
declare VERSION="0.6.2"
declare VERBOSE=${VERBOSE:-"no"}
declare DEBUG=${DEBUG:-"no"}
declare DEBUG_HEXDUMP="no"
declare DEBUGFILE="/tmp/vcli.debug"
declare TMP="/tmp"
declare is_command cmd cmd_history restcmd _key len pos history_index
declare timeout="2" # timeout to verify connection to Vault
declare http_code
declare vault_host vault_port vault_token current_pwd
# History related vars
declare VCLISTORY="$HOME/.vclistory"
declare pri_suffix="_principal"
declare crt_suffix="_crt"
declare key_suffix="_key"
declare SEARCHIST ENDHIST ADDTMPCMD search_cmd
declare -a cmd_history tmp_history
declare cert_warning_threshold="30"
declare cert_critical_threshold="15"
# vcli dependencies
declare DEPENDENCIES="curl jq openssl klist bc"
# COLOURS
TAB=$(tput setaf 4; tput bold)
RED="$(tput setaf 1; tput bold)"
GREEN="$(tput setaf 2; tput bold)"
YELLOW="$(tput setaf 3)"
CYAN="$(tput setaf 6; tput bold)"
NONE="$(tput sgr0)"
BOLD="$(tput bold)"
# URI encoder
function urlencode {
jq -nr --arg v "$1" '$v|@uri'
}
# Check dependencies
function check_dependency(){
local dependencies
dependencies=$*
for dependency in $dependencies; do
if ! command -v "$dependency" >/dev/null; then
echo "$SCRIPTNAME: command '$dependency' not found"
exit 1
fi
done
}
function check_connectivity(){
if ! timeout $timeout bash -c "</dev/tcp/$vault_host/$vault_port"; then
echo "Cannot establish connection to $protocol://$vault_host:$vault_port"
exit 1
fi
}
# check vcli latest version
function new_version(){
local latest_release
[[ $disable_prompt ]] && return
latest_release="$(timeout 2 curl -s https://api.github.com/repos/mlorenzo-stratio/vcli/releases/latest | jq -r '.tag_name')"
if [[ $latest_release && $latest_release != "null" && $VERSION != "$latest_release" ]]; then
echo -e "New version available: $latest_release\nYou can download it by running:\n curl -sL https://github.com/mlorenzo-stratio/vcli/raw/$latest_release/vcli > $0"
return 0
fi
return 1
}
# Print prompt
function prompt(){
if [[ $disable_prompt ]]; then
return
fi
local COLOUR=$CYAN
debug "prompt: http_code=$http_code"
if [[ $http_code =~ ^2 ]]; then
COLOUR=$GREEN
elif [[ $http_code =~ ^3 ]]; then
COLOUR=$YELLOW
elif [[ $http_code =~ ^4 ]] || [[ $http_code =~ ^5 ]]; then
COLOUR=$RED
fi
echo -n "[$COLOUR$http_code$NONE] $BOLD$SCRIPTNAME$TAB@$NONE$BOLD$vault_host$TAB:$NONE$BOLD$vault_port$current_pwd$TAB >$NONE "
}
function debug(){
local msg="$*"
if [[ $DEBUG == "yes" ]]; then
echo -e "$msg" >> $DEBUGFILE
fi
}
################################################# CLI FUNCTIONS #################################################
declare -A vcli_commands=(
[mount]=arg
[umount]=arg
[cd]=arg
[ls]=arg
[lsrole]=noarg
[showrole]=arg
[lspol]=noarg
[showpol]=arg
[tree]=arg
[find]=arg
[replace]=arg
[cptree]=arg
[rmtree]=arg
[backup]=arg
[restore]=arg
[cat]=arg
[cp]=arg
[getcert]=arg
[getcertlist]=arg
[getkrblist]=arg
[getcertexpiration]=arg
[getallcertlist]=arg
[getallkrblist]=arg
[getallcertexpiration]=arg
[getsan]=arg
[getprinc]=arg
[certinfo]=arg
[getkrb]=arg
[krbinfo]=arg
[mv]=arg
[put]=arg
[addsecret]=arg
[delsecret]=arg
[rm]=arg
[help]=arg
[history]=noarg
[exit]=noarg
[verbose]=noarg
[enable-debug]=noarg
[disable-debug]=noarg
[enable-hexdump-debug]=noarg
[disable-hexdump-debug]=noarg
)
declare -A vcli_commands_help=(
[mount]="mount path/to/mount \n creates mount $current_pwd/path/to/mount"
[umount]="umount path/to/mount \n destroys mount $current_pwd/path/to/mount"
[cd]="cd path/to/secret \n changes to directory $current_pwd/path/to/secret"
[ls]="ls path/to/secret \n lists paths and secrets on $current_pwd/path/to/secret"
[lsrole]="lsrole \n lists Vault roles"
[showrole]="showrole myrole \n shows Vault role named myrole"
[lspol]="lspol \n lists Vault policies"
[showpol]="showpol mypolicy \n shows Vault policy named mypolicy"
[tree]="tree path/to/secret \n prints vault's secrets tree with $current_pwd/path/to/secret as its root"
[find]="find path/to/search { \"key\": \"value\" } \n finds vault's secrets that match the JSON data provided on path $current_pwd/path/to/search"
[replace]="replace path/to/replace { \"key\": \"value\" } { \"newkey\": \"newvalue\" } \n replaces vault's secrets under $current_pwd/path/to/replace that match the JSON data with the new JSON data provided"
[cptree]="cptree path/to/secret path/to/other_secret \n copies tree to destination path $current_pwd/path/to/other_secret"
[rmtree]="rmtree [-f] path/to/secret \n removes path $current_pwd/path/to/secret recursively. Use '-f' as first argument to avoid delete confirmation"
[backup]="backup path/to/secrets \n backs up Vault /path to $TMP folder"
[restore]="restore /local/dir/file \n restores Vault backup"
[cat]="cat path/to/secret \n shows contents of secret $current_pwd/path/to/secret"
[cp]="cp path/to/secret path/to/other_secret \n copies contents of path to path $current_pwd/path/to/other_secret"
[getcert]="getcert path/to/secret \n downloads certificate CRT and KEY stored in $current_pwd/path/to/secret"
[getcertlist]="getcertlist path/to/certificates \n recovers certs.list with certificates found in $current_pwd/path/to/certificates"
[getkrblist]="getkrblist path/to/kerberos \n recovers krb.list with principals found in $current_pwd/path/to/kerberos"
[getcertexpiration]="getcertexpiration [-oo|-ow|-oc] path/to/certificate \n shows expiration date for specified certificate $current_pwd/path/to/certificates\n -oo: omit ok certs\n -ow: omit certs in warning threshold ($cert_warning_threshold days)\n -oc: omit certs in critical threshold ($cert_critical_threshold days)"
[getallcertlist]="getallcertlist path/to/certificates \n recovers certs.list with all certificates found under tree $current_pwd/path/to/certificates"
[getallkrblist]="getallkrblist path/to/kerberos \n recovers krb.list with all principals found under tree $current_pwd/path/to/kerberos"
[getallcertexpiration]="getallcertexpiration [-oo|-ow|-oc] path/to/certificate \n shows expiration date for all certificates found under tree $current_pwd/path/to/certificates\n -oo: omit ok certs\n -ow: omit certs in warning threshold ($cert_warning_threshold days)\n -oc: omit certs in critical threshold ($cert_critical_threshold days)"
[getsan]="getsan path/to/secret \n shows certificate's SAN stored in $current_pwd/path/to/secret"
[getprinc]="getprinc path/to/secret \n shows pincipal stored in keytab $current_pwd/path/to/secret"
[certinfo]="certinfo path/to/secret \n shows certificate info stored in $current_pwd/path/to/secret"
[getkrb]="getkrb path/to/secret \n exports keytab file to $TMP/principal.keytab"
[krbinfo]="krbinfo path/to/secret \n shows principal & keytab info stored in $current_pwd/path/to/secret"
[mv]="mv path/to/secret path/to/other_secret \n moves contents of path to path $current_pwd/path/to/other_secret"
[put]="put path/to/secret { \"key\": \"value\" } \n adds json={ \"key\": \"value\" } to secret $current_pwd/path/to/secret"
[addsecret]="addsecret path/to/secret { \"key2\": \"value2\" } \n adds secret { \"key2\": \"value2\" } to existing secret $current_pwd/path/to/secret"
[delsecret]="delsecret path/to/secret key \n deletes key from secret"
[rm]="rm path/to/secret \n removes secret $current_pwd/path/to/secret"
[help]="help [vcli_command] \n shows this help or the specified's command"
[history]="history \n shows vcli history"
[verbose]="verbose \n toggle verbosity"
[enable-debug]="enable-debug \n enable debugging"
[disable-debug]="disable-debug \n disable debugging"
[enable-hexdump-debug]="enable-hexdump-debug \n enable input hexdump debugging"
[disable-hexdump-debug]="disable-hexdump-debug \n disable input hexdump debugging"
[exit]="exit \n exits vcli"
)
# return whether is a command or not
function is_cmd(){
local cmd=${1%% *}
local args=${1#* }
if [[ $cmd == "$args" ]]; then unset args; fi
local args
#debug "IS_CMD1: cmd=$cmd args=$args"
for command in "${!vcli_commands[@]}"; do
#debug "IS_CMD2: command=$command, args=$args"
#debug "IS_CMD3: $cmd =~ ^$command$"
if [[ $cmd =~ ^$command$ ]]; then
if [[ ${vcli_commands[$command]} = "noarg" ]]; then
if [[ $args ]]; then
return 1
else
#debug "IS_CMD4: MATCHED"
return 0
fi
fi
#debug "IS_CMD4: MATCHED"
return 0
fi
done
return 1
}
# complete command
function completion(){
debug "run completion"
local -a tmparray
local found _cmd _path _secret paths
local -a commands=( ${!vcli_commands[@]} )
IFS=' ' read -r _cmd _option _path <<< "${@}"
if [[ ! $_path ]]; then
_path=$_option
unset _option
fi
debug "cmd: $_cmd, option: $_option, path: $_path"
# complete command
if [[ ! $_path ]]; then
if ! is_cmd "$_cmd" || [[ ! $_cmd =~ \ $ ]]; then
for c in "${commands[@]}"; do
if [[ $c =~ ^$_cmd ]]; then
debug "found: $c"
tmparray+=( $c )
fi
done
found=${#tmparray[@]}
debug "commands_found $found: " "${tmparray[@]}"
local tmpcmd_so_far cmd_so_far
if [[ $found == 1 ]]; then
cmd="${tmparray[0]} "
debug "new_cmd cmd1: $cmd"
elif [[ $found -gt 1 ]]; then
echo
for p in "${tmparray[@]}"; do
echo "$p"
done
local n=1
local i=0
# compare all found occurrences and build the common substring
while true ; do
tmpcmd_so_far=${tmparray[$i]::$n}
debug "tmpcmd_so_far: $tmpcmd_so_far"
while [[ $i -lt ${#tmparray[@]} ]]; do
debug "cmdmatch: i=$i n=$n ${tmparray[$i]::$n} == $tmpcmd_so_far"
if [[ ${tmparray[$i]::$n} != "$tmpcmd_so_far" ]]; then
end="true"
break 2
fi
tmpcmd_so_far=${tmparray[$i]::$n}
let i++
done
if [[ ! $end ]]; then
cmd_so_far=$tmpcmd_so_far
debug "cmdsofar: $cmd_so_far"
fi
let n++
let i=0
done
cmd="$cmd_so_far"
debug "new_cmd cmd+1: $cmd"
unset tmparray tmpcmd_so_far cmd_so_far end
prompt
return 1
fi
fi
# complete path
else
debug "searching path $_path"
_secret=${_path##*/}
debug "1 path: $_path, secret: $_secret"
if [[ $_path != "$_secret" ]]; then
_path=${_path%$_secret*}
else
unset _path
fi
debug "2 path: $_path, secret: $_secret"
paths=$(_ls "-_disable_colors_-" "$_path" | tr -t '\n' ' ' | tr -s ' ')
debug "DEBUG: $(_ls "-_disable_colors_-" "$_path" | tr -t '\n' ' ' | tr -s ' ')"
backIFS=$IFS
IFS=$' '
for p in $paths; do
if [[ $p =~ ^$_secret ]]; then
debug "found path: $p"
tmparray+=( $p )
fi
done
IFS=$backIFS
found=${#tmparray[@]}
debug "paths_found $found: " "${tmparray[@]}"
debug "cmd: $_cmd $_path"
local tmpath_so_far path_so_far
if [[ $found == 1 ]]; then
cmd="$_cmd $_option $_path${tmparray[0]}"
debug "new_cmd path1: $cmd"
elif [[ $found -gt 1 ]]; then
echo
for p in "${tmparray[@]}"; do
echo "$p" | sed -e "s/\//$CYAN\/$NONE/"
done
local n=1
local i=0
# compare all found occurrences and build the common substring
while true ; do
tmpath_so_far=${tmparray[$i]::$n}
debug "tmpath_so_far: $tmpath_so_far"
while [[ $i -lt ${#tmparray[@]} ]]; do
debug "pathmatch: i=$i n=$n ${tmparray[$i]::$n} == $tmpath_so_far"
if [[ ${tmparray[$i]::$n} != "$tmpath_so_far" ]]; then
end="true"
break 2
fi
tmpath_so_far=${tmparray[$i]::$n}
let i++
done
if [[ ! $end ]]; then
path_so_far=$tmpath_so_far
debug "pathsofar: $path_so_far"
fi
let n++
let i=0
done
cmd="$_cmd $_option $_path$path_so_far"
debug "new_cmd path+1: $cmd"
unset tmparray tmpath_so_far path_so_far end
prompt
return 1
fi
fi
unset tmparray found
}
# add $cmd to command history @cmd_history
function add_cmd(){
local vclistory
# If "$1" is a file then process it
if [[ -r "$1" ]]; then
mapfile -t vclistory < <(sed '1!G;h;$!d' "$1") # read history in reverse
cmd_history=( "${vclistory[@]}" )
else
local cmd
cmd="$(echo "$*" | sed -e "s/^[[:space:]]\+\(.*\)/\1/g" -e "s/[[:space:]]\+$//g" | tr -s ' ')"
is_cmd "$cmd" || return 1
local -a new_history
new_history=( "$cmd" )
for old_cmd in "${cmd_history[@]}"; do
if [[ $old_cmd != $"cmd" ]]; then
new_history+=( "$old_cmd" )
fi
done
cmd_history=( "${new_history[@]}" )
debug "add_cmd cmd_history[0]: $cmd"
fi
}
# UP: returns previous cmd in history
function get_prev_cmd(){
if [[ ! $ADDTMPCMD ]]; then
debug "get_prev add tmp_cmd: $cmd"
add_cmd "$cmd"
ADDTMPCMD="yes"
fi
if [[ $history_index -lt $((${#cmd_history[@]}-1)) ]]; then
cmd="${cmd_history[$((++history_index))]}"
debug "get_prev cmd_history[$((history_index))]: $cmd"
# move the cursor to the beginning to print the command selected
[[ $pos != 1 ]] && tput cub $((pos-1)) # move cursor left to the beginning
# print the command found in history
echo -n "$cmd"
tput el # clean to the end of the line
let pos=$((${#cmd}+1))
let len=${#cmd}
else
debug "get_next reached oldest cmd: $cmd"
fi
}
# DOWN: returns next cmd in history
function get_next_cmd(){
if [[ $history_index -gt 0 ]]; then
cmd="${cmd_history[$((--history_index))]}"
debug "get_next cmd_history[$((history_index))]: $cmd"
# move the cursor to the beginning to print the command selected
[[ $pos != 1 ]] && tput cub $((pos-1)) # move cursor left to the beginning
# print the command found in history
echo -n "$cmd"
tput el # clean to the end of the line
let pos=$((${#cmd}+1))
let len=${#cmd}
elif [[ ! $ENDHIST ]]; then
debug "get_next reached newest cmd: $cmd"
unset ADDTMPCMD
let history_index=-1
cmd=""
# move the cursor to the beginning to print the command selected
[[ $pos != 1 ]] && tput cub $((pos-1)) # move cursor left to the beginning
tput el # clean to the end of the line
let pos=$((${#cmd}+1))
let len=${#cmd}
ENDHIST=yes
fi
}
# returns last command's path
function get_lastcmd_arg(){
if [[ "$(echo "${cmd_history[$((history_index+1))]}" | cut -d' ' -f2)" =~ ^- ]]; then
echo "${cmd_history[$((history_index+1))]}" | cut -d' ' -f3
else
echo "${cmd_history[$((history_index+1))]}" | cut -d' ' -f2
fi
}
# saves history to $HOME/.vclistory
function save_history(){
: > "$VCLISTORY"
for (( idx=${#cmd_history[@]}-1 ; idx>=0 ; idx-- )) ; do
echo "${cmd_history[$idx]}" >> "$VCLISTORY"
done
}
# loads history from $HOME/.vclistory
function load_history(){
[[ ! -e $VCLISTORY ]] && return
add_cmd "$VCLISTORY"
}
# loads history from $HOME/.vclistory
function print_history(){
if [[ ${#cmd_history[@]} == 0 ]]; then
echo "No history found"
return
fi
local n=1
local depth
local historylines=${#cmd_history[@]}
depth="$(( ${#historylines} - 1 ))"
for (( idx=${#cmd_history[@]}-1 ; idx>=0 ; idx-- )) ; do
npadded="$(printf %0"${depth}"d $n)"
echo "#$npadded: ${cmd_history[$idx]}"
let n++
done
}
# return vcli commands found in history matching $cmd
function rotate_found_cmds(){
debug "rotate_found_cmds"
if [[ ! $search_cmd ]]; then
search_cmd="$*"
fi
debug "search_next_from: $search_cmd, \$SEARCHIST: $SEARCHIST"
if [[ ! $SEARCHIST ]]; then
# starting vcli search mode. Build a tmp_history with all matching commands
for (( idx=0 ; idx<=${#cmd_history[@]}-1 ; idx++ )) ; do
if [[ "${cmd_history[$idx]}" =~ $search_cmd ]]; then
tmp_history+=( "${cmd_history[$idx]}" )
fi
[[ ! $SEARCHIST ]] && SEARCHIST="0"
done
# print first command found
# if another Ctrl+r is hit next item will be printed
debug "\${#tmp_history}=${#tmp_history[@]}"
debug "\${tmp_history[$SEARCHIST]}=\"${tmp_history[$SEARCHIST]}"\"
cmd="${tmp_history[$SEARCHIST]}"
else
let SEARCHIST++
SEARCHIST=$((SEARCHIST%(${#tmp_history[@]})))
debug "\${#tmp_history}=${#tmp_history[@]}"
debug "\${tmp_history[$SEARCHIST]}=\"${tmp_history[$SEARCHIST]}"\"
cmd="${tmp_history[$SEARCHIST]}"
fi
}
################################################# CLI FUNCTIONS #################################################
# Usage
function help(){
cat <<EOH
Usage: $SCRIPTNAME -v <vault_host> -p <vault_port> -t <vault_token> [-i] [-n]
-i: use insecure http
-n: do not print prompt or commands. Useful when input is piped from stdin
$SCRIPTNAME --version
EOH
}
# Print commands help
function commands_help(){
local arg="$1"
local _cmd
local commands
commands="${!vcli_commands[@]}"
commands=${commands// /|}
if [[ ! $arg ]]; then
echo -e "Available commands:\n"
backIFS=$IFS
IFS=$'|'
local _commands
_commands=$(echo "$commands" | tr -t '|' '\n' | sort | tr -t '\n' '|')
for command in $_commands; do
echo -e "$command: $(commands_help "$command")\n"
done
IFS=$backIFS
return
fi
for _cmd in "${!vcli_commands[@]}"; do
if [[ "$_cmd" = "$arg" ]]; then
echo -e "${vcli_commands_help[$_cmd]}"
return 0
fi
done
echo -e "unkown '$arg' vcli command. Available commands:"
while read -r line ; do echo " $line"
done< <(echo -e "${commands//|/\\n}") | sort
return 1
}
# Check for given arguments
function check_arg(){
local arg=$1
local msg=$2
if [[ ! $arg ]]; then
echo -e "ERROR! No $msg provided\n"
help ; exit 1
fi
}
# save & clean & exit
function clean_n_exit(){
save_history
[[ ! $disable_prompt ]] && echo
## REMOVED: it seems this bug doesn't reproduce anymore ##
#
# reset terminal when running inside a container as local echo gets disabled (??)
# if ! head -n 1 /proc/1/sched | grep -qE "(systemd|init)"; then
# reset
# fi
if [[ ! $http_code =~ ^2 ]]; then exit_status=1 ; fi
exit $exit_status
}
# Run command and prettyfy stdout
function _run(){
local exit_status
if [[ $VERBOSE == yes ]]; then
local tmp
tmp=$(mktemp -p /dev/shm -t .run.XXXX)
eval "$*" 2> "$tmp" # store stderr in $tmp
exit_status=$?
while IFS=$'\n' read -r line; do
debug " $line"
done < "$tmp"
rm -f "$tmp"
else
eval "$*" 2> /dev/null
exit_status=$?
fi
return $exit_status
}
# simplified curl function
function _curl(){
local enable_f="-f"
local tmp
if [[ "$1" == "-_disable_-f_-" ]]; then
unset enable_f
shift
elif [[ "$1" == "-i" ]]; then
local ignore_http_code="true"
shift
elif [[ "$1" == "" ]]; then
shift
fi
local endpoint
endpoint="$(urlencode "${1#/}")" # remove initial '/' if exists
local data="$2"
local response
if [[ "$data" == "-_list_root_-" ]]; then
ROOT_QUERY="yes"
fi
# POST, GET, PUT, PATCH, DELETE
# http://www.restapitutorial.com/lessons/httpmethods.html
local method="${3:-GET}"
debug "curl: _curl '$1' '$2' '$3'"
if [[ $data ]]; then
if [[ "$VERBOSE" = "yes" ]]; then
debug "url: $protocol://$vault_host:$vault_port/v1/$endpoint\nmethod: $method\ndata:$data"
fi
mapfile -t response < <(_run "/usr/bin/curl -w \"%{http_code}\n\" -s $enable_f -k -L -X$method -H \"X-Vault-Token:$vault_token\" \
-H 'Content-type: application/json' \
-d @\"$data\" \
\"$protocol://$vault_host:$vault_port/v1/$endpoint\"")
if [[ -f "$data" ]]; then
rm -fr "$data"
fi
else
if [[ "$VERBOSE" = "yes" ]]; then
debug "url: $protocol://$vault_host:$vault_port/v1/$endpoint\nmethod: $method"
fi
mapfile -t response < <(_run "/usr/bin/curl -w \"%{http_code}\n\" -s $enable_f -k -L -X$method -H \"X-Vault-Token:$vault_token\" \
-H 'Content-type: application/json' \
\"$protocol://$vault_host:$vault_port/v1/$endpoint\"")
fi
#debug "response_mapfile: ${response[0]} # ${response[1]}"
if [[ ! "$ignore_http_code" ]]; then
if [[ ! ${response[1]} ]]; then
http_code="${response[0]}"
else
if [[ $ROOT_QUERY ]]; then
echo "${response[0]}" | jq '.data | keys[]' -r
else
echo "${response[0]}" | jq '' -r
fi
http_code="${response[1]}"
fi
debug "curl: http_code=$http_code"
if [[ ! "$http_code" =~ ^2 ]]; then
return 1
fi
fi
unset ROOT_QUERY response
}
# run command entered in CLI
function run_cmd(){
local args
local fullcmd="$*"
args=${*#* }
if [[ $fullcmd == "$args" ]]; then
unset args
fi
backIFS=$IFS
while IFS=$' ' read -r cmd arg1 arg2 arg3; do
if [[ $arg1 == "!$" ]]; then
arg1=$(get_lastcmd_arg)
fi
if ! is_cmd "$fullcmd"; then
commands_help "$cmd"
return 1
fi
case $cmd in
cd) _cd "$arg1" ;;
ls) _ls "$arg1" ;;
lsrole) _lsrole ;;
showrole) _showrole "$arg1" ;;
lspol) _lspol ;;
showpol) _showpol "$arg1" ;;
tree) backIFS=$IFS; IFS=$' ' ; _tree "$arg1" ; IFS=$backIFS;;
find) backIFS=$IFS; IFS=$' ' ; _find "$arg1" "$arg2 $arg3" ; IFS=$backIFS;;
replace) backIFS=$IFS; IFS=$' ' ; _replace "$arg1" "$arg2 $arg3" ; IFS=$backIFS;;
cptree) backIFS=$IFS; IFS=$' ' ; _cptree "$arg1" "$arg2" ; IFS=$backIFS;;
rmtree) backIFS=$IFS; IFS=$' ' ; _rmtree "$arg1" "$arg2"; IFS=$backIFS;;
backup) backIFS=$IFS; IFS=$' ' ; _backup "$arg1" ; IFS=$backIFS;;
restore) backIFS=$IFS; IFS=$' ' ; _restore "$arg1" ; IFS=$backIFS;;
cat) _cat "$arg1" ;;
put) _put "$arg1" "$arg2 $arg3" ;;
addsecret) _addsecret "$arg1" "$arg2 $arg3" ;;
delsecret) _delsecret "$arg1" "$arg2" ;;
rm) _rm "$arg1" ;;
cp) _cp "$arg1" "$arg2" ;;
getcert) _getcert "$arg1" ;;
getsan) _getsan "$arg1" ;;
getprinc) _getprinc "$arg1" ;;
getcertlist) _getcertlist "$arg1" ;;
getkrblist) _getkrblist "$arg1" ;;
getcertexpiration) _getcertexpiration "$arg1" "$arg2" "$arg3" ;;
getallcertlist) _getallcertlist "$arg1" ;;
getallkrblist) _getallkrblist "$arg1" ;;
getallcertexpiration) _getallcertexpiration "$arg1" "$arg2" ;;
certinfo) _certinfo "$arg1" ;;
getkrb) _getkrb "$arg1" ;;
krbinfo) _krbinfo "$arg1" ;;
mv) _mv "$arg1" "$arg2" ;;
mount) _mount "$args" ;;
umount) _umount "$args" ;;
history) print_history ;;
exit) save_history; exit ;;
help) commands_help "$arg1" ;;
enable-debug) echo "debug enabled" ; DEBUG="yes";;
disable-debug) echo "debug disabled" ; DEBUG="no";;
verbose) if [[ $VERBOSE == "yes" ]]; then
echo "verbose mode OFF"
VERBOSE="no"
else
echo "verbose mode ON"
VERBOSE="yes"
fi ;;
enable-hexdump-debug) echo "hexdump debug enabled" ; DEBUG_HEXDUMP="yes";;
disable-hexdump-debug) echo "hexdump debug disabled" ; DEBUG_HEXDUMP="no";;
\#*) return;; # ignore commented lines
*) commands_help "$cmd" ; return 1 ;;
esac
debug "run_cmd: $cmd $arg1 $arg2"
debug "run_cmd: http_code=$http_code"
add_cmd "$cmd $arg1 $arg2 $arg3"
done< <(echo "$fullcmd")
}
# mount function
function _mount(){
if [[ "$1" == "-i" ]]; then
local ignore_http_code="true"
shift
fi
local url="$*"
local data
if [[ ! $url ]]; then
echo "mounted paths:"
_ls /
# mount $url
else
# get full path if relative reference
if [[ ! "$url" =~ ^/ ]]; then
url="/sys/mounts/$current_pwd$url"
else
url="/sys/mounts$url"
fi
data=$(mktemp -p /dev/shm -t .put.XXXX)
echo "{ \"type\": \"generic\", \"description\": \"$url secret backend\" }" > "$data"
if [[ $ignore_http_code ]]; then
_curl -i "$url" "$data" "POST"
else
_curl "$url" "$data" "POST"
fi
echo "mounted '$url'"
fi
}
# umount function
function _umount(){
if [[ "$1" == "-i" ]]; then
local ignore_http_code="true"
shift
fi
local url="$*"
if [[ ! $url ]]; then
echo "umount needs an argument"
_mount
fi
# get full path if relative reference
if [[ ! "$url" =~ ^/ ]] && [[ ! "$url" =~ ^/sys/mounts ]]; then
url="/sys/mounts/$current_pwd$url"
elif [[ ! "$url" =~ ^/sys/mounts ]]; then
url="/sys/mounts$url"
fi
if [[ $ignore_http_code ]]; then
_curl -i "$url" "" "DELETE"
else
_curl "$url" "" "DELETE"
fi
}
# cd function
function _cd(){
local url="$1"
if [[ $url == ".." ]]; then
url=${current_pwd%*/}
url=${url%/*}/
elif [[ $url =~ ^/ ]]; then
: # do nothing url is perfect as it is
elif [[ $url ]]; then
url="$current_pwd/$url/"
url=${url//\/\//\/}
elif [[ $current_pwd ]]; then
url="$current_pwd/"
url=${url//\/\//\/}
else
current_pwd="/"
fi
if [[ $url != "/" ]] && [[ "$1" != ".." ]] && ! _ls "$url" | grep -q "."; then
echo "Error! '$url' not found"
elif [[ $url != "/" ]]; then
current_pwd="$url"
else
current_pwd=""
fi
debug "cd: cd $1 ; current_pwd=$current_pwd"
}
# ls function
function _ls(){
local url tmp method
if [[ $1 == "-_disable_colors_-" ]]; then
local disable_colors="yes"
shift
fi
if [[ "$1" == "-i" ]]; then
local ignore_http_code="-i"
shift
fi
if [[ ! $1 =~ ^/ ]]; then
url="$current_pwd/$1"
else
url="$1"
fi
if [[ $url == '/' ]]; then
if [[ $disable_colors ]]; then
_cat /sys/mounts "-_list_root_-" | tr -d '"'
else
_cat /sys/mounts "-_list_root_-" | tr -d '"' | sed -e "s/\//$CYAN\/$NONE/"
fi
return
elif [[ $url ]]; then
url="$url"
method="LIST"
else
url="$current_pwd"
method="LIST"
fi
if [[ $disable_colors ]]; then
tmp=$(mktemp -p /dev/shm -t ls.XXXX)
_curl $ignore_http_code "$url" "" "$method" > "$tmp"
jq '.data .keys[]' -r < "$tmp"
else
tmp=$(mktemp -p /dev/shm -t ls.XXXX)
_curl $ignore_http_code "$url" "" "$method" > "$tmp"
jq '.data .keys[]' -r < "$tmp" | sed -e "s/\//$CYAN\/$NONE/"
fi
rm -f "$tmp"
}
# lsrole list roles
function _lsrole(){
local tmp
tmp=$(mktemp -p /dev/shm -t lsrole.XXXX)
_cat /auth/approle/role?list=true > "$tmp"
jq '.data .keys[]' -r < "$tmp"
rm "$tmp"
}
# showpol list role policies
function _showrole(){
local funcname
funcname="${FUNCNAME[0]}"
local role="$1"
local tmp
if [[ ! $role ]]; then
echo "Error! Missing role"
commands_help "${funcname//_/}"
return
fi
tmp=$(mktemp -p /dev/shm -t showrole.XXXX)
_cat /auth/approle/role/"$role" > "$tmp"
echo -n "policies: "
jq ".data .policies[]" -r < "$tmp"
rm "$tmp"
}
# lspol list policies
function _lspol(){
local tmp
tmp=$(mktemp -p /dev/shm -t lspol.XXXX)
_cat /sys/policy > "$tmp"
jq '.data .policies[]' -r < "$tmp"
rm "$tmp"
}
# showpol list policy rules
function _showpol(){
local funcname
funcname="${FUNCNAME[0]}"
local policy="$1"
local tmp
if [[ ! $policy ]]; then
echo "Error! Missing policy"
commands_help "${funcname//_/}"
return
fi
tmp=$(mktemp -p /dev/shm -t showpol.XXXX)
_cat /sys/policy/"$policy" > "$tmp"
jq ".data .rules" -r < "$tmp" | tr -d '\\' | tr -s ' ' | sed -e "s/}/ }\n/g" -e "s/^[[:space:]]\+//"
rm "$tmp"
}
function padecho(){
local msg="$1"
local depth="$2"
local space="$3"
local echospace="$4"
# we print 2 spaces for every depth
for (( i=${#space} ; i<$((depth*2)) ; i++ )) ; do
# if is folder
echo -n " "
done
msg=${msg/\/\//\/}
msg=${msg//\//$CYAN\/$NONE}
space=${space//+/$CYAN+$NONE}
space=${space//\`/$CYAN\`$NONE}
debug "${echospace}msg: $msg, depth: $depth ; space: \"$space\""
echo "$space$msg"
}
# display the vault's secret tree
function _tree(){
local url
if [[ ! $1 =~ ^/ ]]; then
url="$current_pwd$1"
else
url=${1//\/\//\/}
fi
local depth="$2"
local space="$3"
local echo_space="$4"
# If no "$2" was passed then this iteration is the very first one, so depth=0
if [[ ! $depth ]]; then
depth=0
# other wise we increment a depth as we go deeper in the structure
else
let depth++
fi
debug "${echo_space}tree: '$url', depth: $depth, space: \"$space\""
# if $url is /
padecho "$(basename "$url")/" "$depth" "$space" "$echo_space "
paths=$(_ls "-_disable_colors_-" "$url" | tr -t '\n' ' ' | tr -s ' ')
for path in $paths; do
debug "${echo_space} depth: $depth => found: $paths"
space=${space/+/ }
if [[ $path =~ /$ ]]; then
_tree "$url/$path" "$depth" "$space+ " "$echo_space "
else
padecho "$path" "$((depth+1))" "$space\` " "$echo_space "
fi
done
}
# find secret in the vault's tree
function _find(){
local url
if [[ ! $1 =~ ^/ ]]; then
url="$current_pwd/$1"
else
url=${1//\/\//\/}
fi
shift
local data
data="$(echo "$@" | jq . -M -S | tr -t '\n' ' ' | tr -s ' ')"
# if $url is /
paths=$(_ls "-_disable_colors_-" "$url" | sed -e "s/,//" | tr -t '\n' ' ' | tr -s ' ')
for path in $paths; do
debug "${echo_space}find: '$url' => found: $paths"
if [[ $path =~ /$ ]]; then
_find "$url/$path" "$data"
else
secret=$(_cat "$url/$path" | jq -M -S ".data" | tr -t '\n' ' ' | tr -s ' ')
debug "find: '$data' '$url'"
if [[ $secret == "$data" ]]; then
debug "find: $secret = $data!"
padecho "$url/$path" "0" "" ""
else
debug "find: $secret == $data"
fi
fi
done
}
# find in $1 and replace secret $2 with new secret $3
function _replace(){
local url
if [[ ! $1 =~ ^/ ]]; then
url="$current_pwd$1"
else
url=${1//\/\//\/}
fi
shift
if [[ ! $url =~ /$ ]]; then
url+="/"
fi
debug "replace2: url=$url"
debug "replace3: rest=\"$*\""
local data
data="$(echo "${@%\{*}" | jq . -M -S | tr -t '\n' ' ' | tr -s ' ')"
local newdata
newdata="$(echo "${@#*\}}" | jq . -M -S | tr -t '\n' ' ' | tr -s ' ')"
debug "replaceX: data=${*%\{*}"
debug "replaceX: newdata=${*#*\}}"
# if $url is /
paths=$(_ls "-_disable_colors_-" "$url" | tr -t '\n' ' ' | tr -s ' ')
debug "replace1: url=$url, data=\"$data\", newdata=\"$newdata\""
for path in $paths; do
if [[ $path =~ /$ ]]; then
_replace "$url/$path" "$data$newdata"
else
secret=$(_cat "$url$path" | jq -M -S ".data" | tr -t '\n' ' ' | tr -s ' ')
debug "replace: '$data' => '$newdata' on '$url'"
if [[ $secret == "$data" ]]; then