-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path.bashrc_aws
788 lines (643 loc) · 27.8 KB
/
.bashrc_aws
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
#----- header -----
[ "${0##*/}" != "${BASH_SOURCE##*/}" ] || { >&2 echo -e "ERROR\tfile must be sourced ($0)"; return 2; }
# prevent multiple-inclusion
__link=`readlink -f "$BASH_SOURCE"`
declare -n __tag=SOURCE_${__link//[^a-zA-Z0-9_]/}
[ ${__tag:-0} -eq 0 ] || return 0
#------------------
# multi-version support
#AWS_VERSION=2
if is_windows; then
AWSCLI=Amazon/AWSCLIV2
# SSM Session-Manager
# ref: https://docs.aws.amazon.com/systems-manager/latest/userguide/session-manager-working-with-install-plugin.html
#
# Windows CLI auto-detects PLUGIN location from registry
# AWS_SM_PLUGIN=${AWSCLI%/*}/SessionManagerPlugin
fi
source ${BASH_SOURCE%_*}_3rdparty aws
[ -n "$AWS_SM_PLUGIN" ] &&
source ${BASH_SOURCE%_*}_3rdparty session-manager-plugin
#TODO just use 'aws shell' instead
if link=`is_exec -v aws_completer`; then
complete -C `printf '%q' "$link"` aws
fi
unset link
addPath -k PATH /usr/local/ec2-ami-tools*/**/bin
# session credentials expire in 4h
export AWS_SESSION_DURATION=$((3600 * 4))
alias aws='__AWS'
alias aws.clearenv='aws.profile RESET'
alias aws.pushd='pushd "${AWS_CONFIG_FILE%/*}/${AWS_DEFAULT_REGION}"'
#alias ec2.disconnect='__AWS ssm terminate-session --session'
# TODO DELETE=1 ec2.connect -i <instnace>
__tag=1
#------------------
function __prompt.aws() {
[ -n "${AWS_PROFILE}${AWS_CONFIG_FILE}${AWS_DEFAULT_REGION}${AWS_SESSION_TOKEN}" ] || return 0
local _config=${AWS_CONFIG_FILE#$HOME/}; _config=${_config#.aws/}; _config=${_config%/config};
#alt: $( sed -E "s|^$HOME/(.aws/)?||; s|/config$||" <<< "$AWS_CONFIG_FILE" )
echo -ne "\n${UL}AWS:${RS} ${FMAG}${_config:---} ${HC}${AWS_PROFILE:---}${RS} / ${FBLE}${HC}${AWS_DEFAULT_REGION:---}${RS}"
#FIXME don't use math, print to common format and simple compare?
if [ -n "$AWS_SESSION_TOKEN" -a -n "$AWS_SESSION_EXPIRE" ]; then
local -i remain=$(( (`date --date="$AWS_SESSION_EXPIRE" '+%s'` - `date '+%s'`) / 60 ))
[ $remain -gt 0 ] && echo -ne " (${remain} min)" || echo -ne " (${BRED}expired${RS})"
fi
}
#FIXME secret handshake from .bashrc_prompt
__prompts+=( __prompt.aws )
function aws.printenv() { local v; for v in ${!AWS_*}; do printf '%s=%q\n' "$v" "${!v}"; done; }
#TODO '-m' or MASK=1 causes **************<truncated value> to print. use printf for
#padding and feed ${var:<pad_width>:<max_width>} to it.
function aws.region() {
local region __default=
local -i OPTIND; local OPTARG opt long_opts=()
while getopts ':hdPr:-:' opt; do
case "$opt" in
d) __default=$OPTARG ;;
P) region='prompt' ;;
r) region=$OPTARG ;;
\-) [[ "$OPTARG" =~ \= ]] || log.notice "assuming simple flag (${!OPTIND})"
long_opts+=( "${!OPTIND}" )
;;
:) log.error "missing argument (${!OPTIND})" ;;&
\?) log.error "unsupported option (-$OPTARG)" ;&
h|*) >&2 cat << EOF
Usage: $FUNCNAME ... TODO
EOF
return 2
esac
done
shift $((OPTIND - 1))
: ${region=${1-'prompt'}}
[ "$region" = '-' ] && region=
# short-circuit on 'blank' argument or match current
# except AWS_*REGION can't be left blank since it's non-obvious
[ -z "$region" ] && [ -n "$AWS_DEFAULT_REGION" ] && return
[ "$region" = "${AWS_DEFAULT_REGION:-__unset__}" ] && return
: ${region:=${__default:-`__AWS configure get region`}}
# still unset after multiple attempts
if [ "${region:-prompt}" = 'prompt' ]; then
local REPLY= PS3=`echo -ne "\nChoose REGION: "`
select region in "${__aws_regions[@]}"; do
[[ "$region" ]] && break
# examine REPLY for textual format
array.contains __aws_regions "$REPLY" && { region=$REPLY; break; }
done
fi
#BUG! Java API uses AWS_REGION; Amazon refused consistency fix
export AWS_{DEFAULT_,}REGION=${region:?}
}
function aws.creds-load() {
return 2
}
function aws.creds-save() {
#TODO pass in as HASH using -H
local profile=${1:?profile} key=${2:?ACCESS_KEY} secret=${3:?SECRET} session=$4
local cmd=( __AWS configure --profile "$profile" set )
[ "$profile" != 'default' ] || { log.error "unsupported profile ($profile)"; return; }
"${cmd[@]}" aws_access_key_id "$key"
"${cmd[@]}" aws_secret_access_key "$secret"
[ -z "$session" ] || "${cmd[@]}" aws_session_token "$4"
}
function aws.profile() {
local profile region
# hacktastic shortcuts
case "${1^^}" in
RESET) aws.rmPath; unset ${!AWS_*}; return ;;
#TODO DELETE=1 $FUNCNAME -p <value>
LIST) __AWS configure list-profiles | column; return ;;
esac
local -i OPTIND; local OPTARG opt long_opts=()
while getopts ':hlPp:-:' opt; do
case "$opt" in
l) $FUNCNAME LIST; return ;;
P) profile='prompt' ;;
p) profile=$OPTARG ;;
\-) [[ "$OPTARG" =~ \= ]] || log.notice "assuming simple flag (${!OPTIND})"
long_opts+=( "${!OPTIND}" )
;;
:) log.error "missing argument (${!OPTIND})" ;;&
\?) log.error "unsupported option (-$OPTARG)" ;&
h|*) >&2 cat << EOF
Usage: $FUNCNAME [profile] [region]
EOF
return 2
esac
done
shift $((OPTIND - 1))
function __finish() { export ${!AWS_*}; aws.addPath; }
: ${profile=${1-'prompt'}}
[ "$profile" = '-' ] && profile=
# short-circuit on 'blank' argument or match current
if [ -z "$profile" -a -n "$AWS_PROFILE" ] || [ "$profile" = "$AWS_PROFILE" ]; then
aws.region "${region-$2}"
__finish; return
fi
if [ "${profile:-'prompt'}" = 'prompt' ]; then
local -a list=( `__AWS configure list-profiles` )
#alt:
# pattern='$1 ~ /^\[(profile|\w+)/ { gsub(/\[|\]/, "", $NF); print $NF; }'
# list=( `awk -- "$pattern" "$conf" "$creds" | sort -u` )
(( ${#list[@]} )) || {
log.warn "no profile(s) found (${AWS_CONFIG_FILE:-${__aws_defaults['config']}})"
return
}
local REPLY= PS3=`echo -ne "\nChoose PROFILE: "`
select profile in "${list[@]}"; do
[[ "$profile" ]] && break
# examine REPLY for textual format
array.contains list "$REPLY" && { profile=$REPLY; break; }
done
fi
#NOTE 'configure get' does NOT follow 'source_profile' keyword
# nor fall-thru to 'default' if --profile is specified.
#
# aws-cli (boto-core) returns 255 on ProfileNotFound, but can (fixed?)
# stacktrace if value of AWS_PROFILE is not defined in file(s).
#
# $? == 1 simply means no explicit declaration
local __region
__region=$( __AWS ${profile:+'--profile' "$profile"} configure get region )
if [ $? -eq 255 ] || [[ "${__region:-X}" =~ ProfileNotFound ]]; then return 255; fi
# cleanup previous environment
if [ "$profile" != "${AWS_PROFILE:-default}" ]; then
aws.rmPath
#TODO iam.session DROP || true
fi
[ "$profile" = 'default' ] && unset AWS_PROFILE || AWS_PROFILE=${profile:?}
aws.region -d "$__region" "${region-$2}"
__finish
}
# Config directive 'source_profile' can NOT be chained to pick up MFA
# if role_arn defined, CLI will transparently invoke 'assume-role' and prompt for TOTP
# and saves session creds to cli/cache.
#{
# "Credentials": {
# "AccessKeyId": "ASIAB",
# "SecretAccessKey": "y71g2qNo0PsvgoflGC",
# "SessionToken": "FwoDwNY=",
# "Expiration": "2023-10-12T01:14:31+00:00"
# },
# "AssumedRoleUser": {
# "AssumedRoleId": "AROAQ7JR2ZADYF5UFG4GB:botocore-session-1697069671",
# "Arn": "arn:aws-us-gov:sts::067213379591:assumed-role/deployer/botocore-session-1697069671"
# }
#
# so any profile that requires MFA must explicitely call it out? even if duplicated over and over? yes
#TODO aws.configure() that wraps the native and does RECURSION (-R) to look for stuff, like region and mfa or role.
# delete a profile via:
# sed '/^\[profile deployer/,/^\[/ { /^\[profile deployer/ d; /^\[/ !d; }' $AWS_CONFIG_FILE
# but ^^^ will eat any commented out lines unlucky enough to be within the range
# similar for credentials file just without the keyword 'profile'
# to print JUST the profile (and any blank or embedded comments
# sed -n '/^\[profile deployer/,/^\[/ { /^\[/ !p; }' or
# sed '/^\[profile deployer/,/^\[/ !d' | sed '$d'
function iam.session-load() {
local input=
local -a keys=()
local -i OPTIND; local OPTARG opt long_opts=()
while getopts ':hf:k:-:' opt; do
case "$opt" in
k) keys+=( "$OPTARG" ) ;;
f) is_file "$OPTARG" || return
input=$( < "$OPTARG" ) ;;
\-) long_opts+=( "--${OPTARG}" )
[[ "$OPTARG" =~ \= ]] || log.notice "assuming flag (--${OPTARG})"
;;
:) log.error "missing argument (${!OPTIND})" ;;&
\?) log.error "unsupported option (-$OPTARG)" ;&
h|*) >&2 cat << EOF
Usage: $FUNCNAME [filename]
EOF
return 2
esac
done
shift $((OPTIND - 1))
if is_file "$1"; then
input=$( < "$1" )
else
: ${input:=$( < /dev/stdin )}
fi
[ -n "$input" ] || { log.error "empty input"; return; }
local format
is_json "$input" && format='json'
case "${format:-text}" in
json) __JQ '.Credentials' <<< "$input" | log.debug || { log.error "invalid input"; return; }
# JSON fields != ENVVAR names (missing underscores)
# jq -r '.Credentials | to_entries | map("\(.key|ascii_upcase)=\(.value|tostring)") | .[]'
local -u v
for k in ${keys[@]:-`keys __aws_session`}; do
v=$( value __aws_session "$k" );
[ -n "$v" ] || { log.error "invalid key ($k)"; return 2; }
local -n vref=$v
vref=$( __JQR --arg field "$k" '.Credentials[$field]' <<< "$input" )
done
#TODO only if role. assign to AWS_SESSION_ROLE_ID and use in prompt
#ref: https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sts/assume-role.html
# may need to use Arn instead otherwise it'll be a session_id
# __JQR '.AssumedRoleUser.AssumedRoleId' <<< "$input" | log.info
;;
text) log.warn "AWS CLI 'text' output is garbage" ;&
#504 read AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_SESSION_TOKEN < <(
#505 __AWS sts assume-role --output text --role-arn "${ROLE_ARN:?}" \
#506 --role-session-name "${session_name}" \
#507 --query 'Credentials.[AccessKeyId,SecretAccessKey,SessionToken]'
#508 )
*) log.error "unsupported format ($format)"; return 2
esac
export ${!AWS_*}
# 'if' needed to thwart pipefail
aws.printenv | log.info
}
function iam.session-save() {
local format input=$1
if is_file "$1"; then
input=$( < "$1" )
else
: ${input:=$( < /dev/stdin )}
fi
[ ${AWS_PROFILE:-default} != 'default' ] || {
log.notice "aborted - no overwrite of default credentials!"
return 128
}
# minimal safety check
[ -n "`__AWS configure get aws_session_token`" -o -n "`__AWS configure get source_profile`" ] || {
log.warn "Possible long-term credentials (`__AWS configure get aws_access_key_id`)"
read -t 7 -ep "Are you DAMN sure to overwrite? (yes/N): "
[ -n "$REPLY" -a "${REPLY,,}" = 'yes' ] || return
}
if [ -n "$input" ]; then
is_json "$input" && format='json'
# case "${format:-text}" in
# json) __JQ '.Credentials' <<< "$input" | log.debug || {
# log.error "invalid input"; return
# }
# # JSON fields != ENVVAR names (missing underscores)
# # jq -r '.Credentials | to_entries | map("\(.key|ascii_upcase)=\(.value|tostring)") | .[]'
# local k v
# for k in `keys __aws_session`; do
# v=`value __aws_session "$k"`
# local -n nv=${v^^}
# nv=`__JQR --arg field "$k" '.Credentials[$field]' <<< "$input"`
# done
# #TODO only if role. assign to AWS_SESSION_ROLE_ID and use in prompt
# #ref: https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sts/assume-role.html
# # may need to use Arn instead otherwise it'll be a session_id
# # __JQR '.AssumedRoleUser.AssumedRoleId' <<< "$input" | log.info
# ;;
# text) log.error "AWS CLI is seriously broken" ;&
# *) log.error "unsupported format ($format)"; return 2
# esac
else # use environment
local -u v
for v in `values __aws_session`; do
__AWS configure set "${v,,}" "${!v}"
done
fi
#? __AWS configure show | log.info
}
# CLI does NOT chain 'source_profile' in search of 'mfa_serial'. Neither for
# creds except in 'assume-role'. 'get-session' requires iam.session() wrapper
# or manual invocation with all necessary arguments and ENV set.
#
# Attempting 'get-session' on profile with define 'role_arn' detonates Boto3
#ref: https://docs.aws.amazon.com/STS/latest/APIReference/API_GetSessionToken.html
#
# STS rejects duration > 3600 if role-chaining
#ref: https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html
function iam.session() {
# hacktastic shortcuts
case "$1" in
DROP) unset `values __aws_session | to_upper`
iam.session-save; return
;;
# CLEAN) find "$cache_dir" -maxdepth 1 -type f -mtime +1 -exec rm {} \; 2>/dev/null
#FIXME,
# local -ir now=`date '+%s'`
# for f in "$cache_dir"/*; do
# [ -f "$f" ] || continue
#
# local expires=`date --date $(__JQR '.Credentials.Expiration' "$f") '+%s'`
#FIXME large number safe? use $((expr)) instead?
# [ ${expires:-0} -ge ${now:?} ] || { rm -f "$f"; continue; }
#FIXME emit filename 'input_filename', or just printf() it.
# [ "$opt" = 'L' ] && __JQR '.AssumedRoleUser.Arn' "$f"
# done
# return
# ;;
esac
local -i duration subshell=0
local role mfa
local token= # MUST be string! Bash strips leading ZEROs, printf treats as Octal
local -i OPTIND; local opt OPTARG long_opts=()
while getopts ':hr:St:x:-:' opt; do
case "$opt" in
r) role=$OPTARG ;;
S) subshell=1 ;;
t) [[ "$OPTARG" =~ ${__aws_regex['token']} ]] || {
log.error "invalid TOTP format ($OPTARG)"; return 2; }
token=$OPTARG ;;
x) duration=$OPTARG ;;
\-) long_opts+=( "--${OPTARG}" )
[[ "$OPTARG" =~ \= ]] || log.notice "assuming flag (--${OPTARG})"
;;
:) log.error "missing argument (${!OPTIND})" ;;&
\?) log.error "unsupported option (-$OPTARG)" ;&
h|*) >&2 cat << EOF
Usage: $FUNCNAME [options]
EOF
return 2
esac
done
shift $((OPTIND - 1))
local ofile
ofile=$( mktemp "${AWS_PROFILE:-default}.XXXXX" ) || return
trap "rm -f $ofile" RETURN
function __doit() (
local -i recurse
[ ${#source_creds[@]} -gt 0 ] && eval `hash.print -V source_creds`
__AWS "${cmd[@]}" \
${mfa:+'--serial-number' "$mfa"} \
${token:+'--token-code' "$token"} \
${duration:+'--duration-seconds' "$duration"} && return
local rc=$?
[ ${recurse:-0} -eq 0 ] || return $rc # prevent infinite loop
# 'ExpiredToken' with one-shot retry
if [ $rc -eq 254 ]; then ${FUNCNAME[1]} DROP; recurse=1 $FUNCNAME; fi
)
#----- main -----
local -A source_creds=()
local -a cmd=( sts )
#ref: https://docs.aws.amazon.com/cli/latest/reference/sts/assume-role.html
if [ -n "${role:=`__AWS configure get role_arn`}" ]; then
local session_name
session_name=$( __AWS configure get role_session_name ||
printf 'SN%.15s@%.12s.%d,%s' "${role##*:role/}" "${AWS_PROFILE:-default}" $$ `date '+%T'`
)
# sanitize illegal chars
cmd+=( assume-role '--role-arn' "$role"
'--role-session-name' "${session_name//[^a-zA-Z0-9@=.,-]}" )
__doit || return $PIPESTATUS > >( tee "$ofile" | log.info )
iam.session-load -k 'Expiration' "$ofile"
# AWS_ROLE_ARN=$role
# compare arn:aws-us-gov:iam::067213379591:role/sudo vs .AssumedRoleUser.Arn = "arn:aws-us-gov:sts::067213379591:assumed-role/sudo/botocore-session-1700103358"
# to confirm match. If so, then consult expiration time .Credentials.Expiration to be sure.
# AWS_ROLE_SESSION_NAME=$session_name or .AssumedRoleUser.AssumedRoleId once stripped of '^[A-Z0-9]:'
# export ${!AWS_*}
# if --output=text use IFS=$'\t ' read -r -a credentials < $ofile
# AWS_ACCESS_KEY_ID=${credentials[0]}, AWS_SECRET_ACCESS_KEY=${credentials[1]}
# AWS_SESSION_TOKEN=${credentials[2]}
return
fi
#-- else !role --
#ref: https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sts/get-session-token.html#options
cmd+=( get-session-token )
# Technically 'get-session-token' works fine without an MFA, but a
# 'ForceMFA'-style IAM policy is likely in effect, rendering such credentials void.
[ -n "$mfa" ] || mfa=$( __AWS configure get mfa_serial ||
__AWS iam list-mfa-devices | __JQR '.MFADevices[].SerialNumber' )
#BUG!
# per https://github.com/aws/aws-cli/issues/1985 implicit MFA ignored and
# makes no prompt for missing Token, whereas 'assume-role' runs checks.
if [ -n "$mfa" -a ${#token} -ne 6 ]; then
while read -t 20 -ep "${mfa#*iam::} TOTP token: " -N 6; do
[[ "${REPLY:-X}" =~ ${__aws_regex['token']} ]] && { token=$REPLY; break; }
done
fi
#BUG! CLI improperly ignores 'source_profile'
local source_profile=`__AWS configure get source_profile`
[ -n "$source_profile" ] &&
for k in aws_access_key_id aws_secret_access_key; do
source_creds+=( ["${k^^}"]=`__AWS --profile "$source_profile" configure get "$k"` ) || {
log.error "not found ($k) for profile ($source_profile)" "file: ${AWS_CONFIG_FILE:-default}"
return; }
done
__doit || return $PIPESTATUS > >( tee "$ofile" | log.info )
#TODO? keep AWS_PROFILE? but set AWS_SESSION_NAME from ofile?
[ ${subshell:-0} -eq 1 ] && (
set -a
iam.session-load "$ofile" && { AWS_PROFILE=${ofile##*/}; "$SHELL"; }
return
)
iam.session-load "$ofile" || return
AWS_PROFILE=${ofile##*/}
export ${!AWS_*}
}
#maybe we DO want '-S' in aws.profile() to force iam.session? Is there OPSEC reasons
#to prefer session creds over perm even in the absence of MFA?
#if we have MFA in account should we just assume to use it? or only force issue if aws.profile
#detects that serial_number is defined in PROFILE?
#TODO create a derivative profile with new creds. instead of creating a cache file just
# run a series of 'aws configure set' to create the ephemeral, and save the creds.
# see https://github.com/YevheniiPokhvalii/generate-aws-tokens
#
# aws configure --profile <_mfa_000> set aws_access_key_id "$AWS_ACCESS_KEY_ID"
# aws configure --profile _mfa_000 set aws_session_token "$AWS_SESSION_TOKEN" (ends up in AWS_CONFIG_FILE
# ditto aws_session_expire
#
# get-caller-ident only rerturns uid, name and ARN but nothing specific to the profile.
#ref: https://github.com/aws/aws-cli/issues/6980
#name the
#cache file appropriately if possible. see what assume-role does. Point being it should be
#possible to switch back and forth from with-MFA profile back to base (or another) and then
#pop back in, assuming the temp creds haven't expired. If they have, then re-auth or force
#user to re-invoke iam.session.
#aws.profile --list should show temporary derivitive profile(s), with perhaps '--clean|clear_cache'
function aws.addPath() {
local -i DELETE load_sshkeys=1
local flags=()
local -i OPTIND; local OPTARG opt
while getopts ':hDL' opt; do
case "$opt" in
D) DELETE=1 ;;
L) load_sshkeys=0 ;;
:) log.error "missing argument (-$OPTARG)" ;;&
# assume flags to addPath
\?) local flags+=( "-$OPTARG" ) ;;
h|*) >&2 cat <<EOF
Usage: $FUNCNAME ... TODO
EOF
return 2
esac
done
shift $((OPTIND - 1))
local _shopt=`shopt -p failglob nullglob`
trap 'eval "$_shopt"' RETURN
shopt -u failglob
while read item; do
[ -n "$item" ] || { shift; continue; }
if [ ${DELETE:-0} -eq 1 ]; then
[[ "$item" =~ .ssh/?$ ]] && #BUG! errors emit stdout when '-d'
${DEBUG:+ runv} ssh-add -d ${VERBOSE:+'-v'} "${item%/}"/*.pub >/dev/null
[[ "$item" =~ /bin/?$ ]] && rmPath "${item%/}"
else
#NOTE use 'IdentitiesOnly yes' in ssh_config, else AuthFailure from many attempts
[[ "$item" =~ .ssh/?$ ]] && [ ${load_sshkeys:-0} -eq 1 ] &&
${DEBUG:+ runv} ssh-add ${VERBOSE:+'-v'} "${item%/}"/{id_*,*.pem} 2>/dev/null
[[ "$item" =~ /bin/?$ ]] && addPath -P "${flags[@]}" "${item%/}"
fi
done < <(
if ! (( $# )); then
local prefix=${AWS_CONFIG_FILE%/*} token=
: ${prefix:=${__aws_defaults['config']%/*}}
case "${FUNCNAME[1]}" in
aws.profile) [ -n "$AWS_PROFILE" ] && token="/$AWS_PROFILE" ;&
aws.region) [ -n "$AWS_DEFAULT_REGION" ] && token="/${AWS_DEFAULT_REGION}${token}" ;;
esac
#WARN! potentially expensive search with possible overlap from symlink(s)
shopt -s nullglob
set -- "${prefix}${token}"/**/{*.ssh,bin}/
fi
IFS=$'\n'; echo "$*" | sort -u
)
return 0
}
function aws.rmPath() { aws.addPath -D "$@"; }
#TODO model after 18f, probes for region, VPC, and instance when invoked with '-P' or '--prompt'
#
# -d for 'direct', -s for 'ssm session', -c for ec2-instance-connect
# with 'connect' you can temporarily (60 seconds) push an SSH key to the host if IAM authorized
#ref: https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/permissions-for-ec2-instance-connect-endpoint.html
#ssh -i my-key-pair.pem ec2-user@i-0123456789example \
# -o ProxyCommand='aws ec2-instance-connect open-tunnel --instance-id i-0123456789example'
# or aws ec2-instance-connect open-tunnel --instance-id i-01234 --local-port 8888
# and then use '-p 8888' for successive traditional SSH client connections
#ref: https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/connect-with-ec2-instance-connect-endpoint.html
#
# but does 'instance-connect' really provide useful differentiation over ssm w/ tunnel??
# though an IAM condition set to separate out certain instances for focused access (users) vs sysadmin carte blanc?
#ref: https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-connect-configure-IAM-role.html
#TODO scrape host ssh signature. https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/connect-to-linux-instance.html
#ssh-keyscan host | ssh-keygen -lf - [-E md5] but obviously this requires L3 connectivity!
#instead have bootstrap post signatures in instance metadata or possibly SSM parameter store.
#http://169.254.169.254/latest/dynamic/instance-identity/document
#
# "accountId" : "067213379591",
# "architecture" : "x86_64",
# "availabilityZone" : "us-gov-west-1a",
# "billingProducts" : null,
# "devpayProductCodes" : null,
# "marketplaceProductCodes" : null,
# "imageId" : "ami-027a29f0c8393dad2",
# "instanceId" : "i-0fd4dd72aaa97987e",
# "instanceType" : "t3a.small",
# "kernelId" : null,
# "pendingTime" : "2024-05-27T04:00:14Z",
# "privateIp" : "192.168.80.4",
# "ramdiskId" : null,
# "region" : "us-gov-west-1",
# "version" : "2017-09-30"
#cat /etc/ssh/ssh_host_*.pub | ssh-keygen -lf - #add to TAGs during cloud-init.
# 256 SHA256:V4HbEmLIlLdWefCVM4iSRjVaxVh3D78pSQxx9F9vG20 no comment (ECDSA)
# 256 SHA256:wuMAAQSMbf67S+F9uq2pTEPVF734+151PzanpZ7fkJI no comment (ED25519)
# 2048 SHA256:EgY9IyP1hMGyvz1ej7AEz5pFmim7RJL0KqKwq+9fEQ0 no comment (RSA)
#
# write an SSM document and invoke against the nodes, possibly invoked by a cron lambda to 'find' new hosts.
#https://docs.aws.amazon.com/systems-manager/latest/userguide/walkthrough-cli.html
function ec2.connect() {
local -a cmd=( ssm start-session )
local -i OPTIND; local OPTARG opt long_opts=()
while getopts ':hL:-:' opt; do
case "$opt" in
#ref: https://docs.aws.amazon.com/systems-manager/latest/userguide/session-manager-working-with-sessions-start.html
L) local -i lport rport
local rhost
# pseudo SSH port-forward spec '[local_port:][remote_host:]remote_port'
IFS=: read -a words <<< "$OPTARG"
case ${#words[@]} in
1) rport=$words ;;
2) rport=${words[1]}
is_number "${words:?}" && lport=$words || rhost=$words ;;
3) lport=$words; rhost=${words[1]}; rport=${words[2]} ;;
*) log.error "invalid port-forward spec ('[local_port:][remote_host:]remote_port')" "$OPTARG"
return 2
esac
# exclude 'localhost', TODO ipv6
grep -qE 'localhost|127\.[0-9]+' - -- <<< "$rhost" && unset rhost
[ ${rport:?} -gt 0 ] || { log.error "invalid remote port ($rport)"; return 2; }
cmd+=( '--document-name' AWS-StartPortForwardingSession${rhost:+SessionToRemoteHost} )
local params=`string.join -zd ',' "portNumber=$rport" \
"${lport:+localPortNumber=$lport}" \
"${rhost:+host=$rhost}"`
[ -n "$params" ] && cmd+=( '--parameters' "$params" )
;;
-) [[ "$OPTARG" =~ \= ]] || log.notice "assuming simple flag (--${OPTARG})"
long_opts+=( "${!OPTIND}" )
;;
:) log.error "missing argument (${!OPTIND})" ;;&
\?) log.error "unsupported (-$OPTARG)" ;&
h|*) >&2 cat << EOF
Usage: $FUNCNAME ... TODO
EOF
return 2
esac
done
shift $((OPTIND - 1))
#TODO? check if
__AWS "${cmd[@]}" --target ${1:?InstanceId} "${long_opts[@]}" "${@:2}"
}
# backwards compat
function ec2.session() { log.warn "deprecated - use 'ec2.connect()'"; ec2.connect "$@"; }
#TODO invoke as ec2.connect --list
function ec2.session-list() {
#TODO getopt 'A' -> '--state Active'
__AWS ssm describe-sessions --state Active | __JQR '.Sessions[] | "\(.Target): \(.SessionId)"'
}
function aws.route53-export() {
local -u zone_id=${1:?zone_id}
local domain=${1%.}; domain+='.'
# if doesn't match pattern assume Domain name was specified
#FIXME will pick first occurance which is likely not intended, use read() to prompt
grep -qE '([A-Z]|[0-9]){12,}' - -- <<< "$zone_id" || zone_id=$(
__AWS route53 list-hosted-zones |
__JQR --arg domain "$domain" '.HostedZones[] | select(.Name == $domain) | .Id' |
cut -d'/' -f3 | head -n 1
)
for zone in $zone_id; do
echo -e "; $zone\n"
#TODO use printf() with width
__AWS route53 list-resource-record-sets --hosted-zone-id=${zone:?} |
__JQR --join-output '.ResourceRecordSets[] | "\(.Name)\t\(.TTL)\t\(.Type)\t\(.ResourceRecords[].Value)\n"'
echo
done
}
#TODO rewrite as aws.describe() item
function iam.sshkeys {
# Example: $FUNCNAME __AWS iam get-group --group-name <group> pipe JQR '.Users[].UserName'
local -u format
local status
: ${format:=ssh}
: ${status:=Active}
while (( $# ));do
[ "$1" ] || { shift; continue; }
for kid in $( __AWS iam list-ssh-public-keys --user-name "$1" |
__JQR --arg STATUS "$status" '.SSHPublicKeys[] | select(.Status == $STATUS) | .SSHPublicKeyId //empty'
); do
#TODO use JQ and drop @sh?
__AWS iam get-ssh-public-key --user-name "$1" --ssh-public-key-id "$kid" --encoding $format |
__JQR '.SSHPublicKey | .UserName, .SSHPublicKeyBody | @sh'
done
shift
done
}
#alt aws-session attemp https://github.com/ksperling/aws-session/blob/master/aws-session
# IP ranges - https://ip-ranges.amazonaws.com/ip-ranges.json
# 'EC2' ranges are for instances, not services but subset of 'AMAZON'
#
# jq -r '.prefixes[] | select(.region == "us-east-1") | [select(.service=="AMAZON").ip_prefix] - [select(.service=="EC2").ip_prefix] | add // empty' ip-ranges.json
#ref: https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-files.html
for f in "${BASH_SOURCE/bashrc/functions}"; do
[ -s "$f" ] || continue
source "$f" || { log.error "RC=$? during $f"; return; }
done
#TODO version_compare() w/ sort -g (--version-sort doesn't actually work)
# echo -e '2.3.43\n2.3.7' | sort -t . -k 1,1 -k 2,2 -k 3,3
#ref: https://github.com/ivan-dyachenko/version
# https://stackoverflow.com/questions/48491662/comparing-two-version-numbers-in-a-shell-script
# https://stackoverflow.com/questions/4023830/how-to-compare-two-strings-in-dot-separated-version-format-in-bash
__aws_api=$( __AWS --version | awk '{ split($1, terms, "/"); print terms[2]; }' )
[[ ${__aws_api} > 2.3.7 ]] || [[ ${__aws_api} > 2.10 ]] ||
log.warn "very old CLI version ($__aws_api)"
unset __aws_api
# vim: expandtab:ts=8:sw=4