-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathawsHunter.sh
More file actions
executable file
·3225 lines (2732 loc) · 131 KB
/
Copy pathawsHunter.sh
File metadata and controls
executable file
·3225 lines (2732 loc) · 131 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/bin/bash
#===============================================================================
# AWS Lambda/Cognito Security Testing Script
#
# This script tests for common AWS misconfigurations including:
# - Cognito Identity Pool unauthenticated access
# - Credential enumeration from leaked keys
# - Service access enumeration
#
# Usage: ./awsHunter.sh [options]
#
# Author: Sedric Louissaint @l0lsec aka ShowUpShowOut
#===============================================================================
# Don't use set -e as many AWS commands legitimately return non-zero
# set -e
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
PURPLE='\033[0;35m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color
# Output file for results (will be created after parsing args)
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
OUTPUT_DIR="./awsHunter_results_${TIMESTAMP}"
#===============================================================================
# Helper Functions
#===============================================================================
print_banner() {
echo -e "${PURPLE}"
cat << 'EOF'
██████╗ ██╗ ██╗███████╗ ██╗ ██╗██╗ ██╗███╗ ██╗████████╗███████╗██████╗
██╔════╝ ██║ ██║██╔════╝ ██║ ██║██║ ██║████╗ ██║╚══██╔══╝██╔════╝██╔══██╗
███████╗ ██║ █╗ ██║███████╗ ███████║██║ ██║██╔██╗ ██║ ██║ █████╗ ██████╔╝
██╔═══██╗██║███╗██║╚════██║ ██╔══██║██║ ██║██║╚██╗██║ ██║ ██╔══╝ ██╔══██╗
╚██████╔╝╚███╔███╔╝███████║ ██║ ██║╚██████╔╝██║ ╚████║ ██║ ███████╗██║ ██║
╚═════╝ ╚══╝╚══╝ ╚══════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═╝ ╚══════╝╚═╝ ╚═╝
EOF
echo -e "${CYAN}"
cat << 'EOF'
╭──────────────────────────────────────╮
│ ☁️ AWS Security Testing Framework │
│ 🔍 Multi-Region Cred & Svc Enum │
│ 👤 @l0lsec aka ShowUpShowOut │
╰──────────────────────────────────────╯
EOF
echo -e "${YELLOW}"
cat << 'EOF'
⠀⠀⠀⠀⠀⠀⢀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⡀
⠀⠀⠀⠀⠀⠀⣾⠉⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⣷ "Hunt credentials.
⠀⠀⠀⠀⠀⠀⣿⠀⠀🎯⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣿ Enumerate access.
⠀⠀⠀⠀⠀⠀⣿⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣿ Extract secrets."
⠀⠀⠀⠀⠀⠀⠛⠛⠛⠛⠛⠛⠛⠛⠛⠛⠛⠛⠛⠛⠛⠛⠛⠛⠛⠛⠛⠛⠛⠛
EOF
echo -e "${NC}"
}
print_section() {
echo -e "\n${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo -e "${CYAN} $1${NC}"
echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
}
print_success() {
echo -e "${GREEN}[✓] $1${NC}"
}
print_error() {
echo -e "${RED}[✗] $1${NC}"
}
print_warning() {
echo -e "${YELLOW}[!] $1${NC}"
}
print_info() {
echo -e "${BLUE}[i] $1${NC}"
}
print_finding() {
echo -e "${RED}[🚨 FINDING] $1${NC}"
}
test_service() {
local service_name="$1"
local command="$2"
local output_file="$3"
echo -n "Testing $service_name... "
if result=$(eval "$command" 2>&1); then
echo "$result" > "$OUTPUT_DIR/$output_file"
print_success "ACCESS GRANTED - Results saved to $output_file"
return 0
else
if echo "$result" | grep -q "AccessDenied\|UnauthorizedOperation\|AccessDeniedException\|AuthorizationError"; then
print_error "Access Denied"
return 1
else
print_warning "Error: $result"
return 2
fi
fi
}
# Test a service across all regions
test_service_all_regions() {
local service_name="$1"
local command_template="$2" # Use {REGION} as placeholder
local output_file_base="$3"
local found_access=false
local regions_with_access=()
if [ "$MULTI_REGION" != true ]; then
# Single region mode - just test the default region
local command="${command_template//\{REGION\}/$AWS_REGION}"
test_service "$service_name" "$command" "$output_file_base"
return $?
fi
echo -n "Testing $service_name across all regions... "
for region in "${ALL_REGIONS[@]}"; do
local command="${command_template//\{REGION\}/$region}"
local output_file="${output_file_base%.json}_${region}.json"
[ "${output_file_base: -4}" != ".json" ] && output_file="${output_file_base}_${region}.txt"
if result=$(eval "$command" 2>&1); then
# Check if result has actual content (not empty arrays/objects)
if [ -n "$result" ] && ! echo "$result" | grep -qE '^\s*\[\s*\]\s*$|^\s*\{\s*\}\s*$|"[A-Za-z]*":\s*\[\]'; then
echo "$result" > "$OUTPUT_DIR/$output_file"
regions_with_access+=("$region")
found_access=true
fi
fi
done
if [ "$found_access" = true ]; then
print_success "ACCESS GRANTED in ${#regions_with_access[@]} regions: ${regions_with_access[*]}"
return 0
else
print_error "Access Denied (all regions)"
return 1
fi
}
# Get all available AWS regions
get_all_regions() {
print_info "Fetching list of all AWS regions..."
ALL_REGIONS=($(aws ec2 describe-regions --query 'Regions[].RegionName' --output text 2>/dev/null))
if [ ${#ALL_REGIONS[@]} -eq 0 ]; then
print_warning "Could not fetch regions, using default list"
ALL_REGIONS=(
"us-east-1" "us-east-2" "us-west-1" "us-west-2"
"eu-west-1" "eu-west-2" "eu-west-3" "eu-central-1" "eu-north-1"
"ap-southeast-1" "ap-southeast-2" "ap-northeast-1" "ap-northeast-2" "ap-northeast-3" "ap-south-1"
"sa-east-1"
"ca-central-1"
"me-south-1"
"af-south-1"
)
fi
print_success "Found ${#ALL_REGIONS[@]} regions to test"
echo "${ALL_REGIONS[*]}" > "$OUTPUT_DIR/regions_tested.txt"
}
#===============================================================================
# Usage & Help
#===============================================================================
show_help() {
cat << EOF
AWS Security Testing Script
===========================
Usage: $0 [OPTIONS]
Options:
-h, --help Show this help message
-r, --region REGION AWS region (default: us-east-1)
-p, --pool-id ID Cognito Identity Pool ID to test
-e, --encoded CREDS Base64 encoded credentials string to decode
-a, --access-key KEY AWS Access Key ID
-s, --secret-key KEY AWS Secret Access Key
-t, --session-token TOK AWS Session Token (for temporary credentials)
-o, --output DIR Output directory (default: ./awsHunter_results_TIMESTAMP)
-q, --quick Quick mode - skip some slower tests
-v, --verbose Verbose output
-m, --multi-region Test all AWS regions (slower but comprehensive)
--regions REGIONS Comma-separated list of regions to test (e.g., us-east-1,us-west-2)
--skip-cognito Skip Cognito Identity Pool testing
--skip-privesc Skip privilege escalation checks
--skip-secrets Skip secret extraction (faster)
--test-create Enable destructive tests (attempt to create resources)
WARNING: This will create test resources in the target account
Cognito User Pool Client Auth:
--client-id ID Cognito App Client ID
--client-secret SECRET Cognito App Client Secret
--token-url URL OAuth2 token endpoint URL
(e.g., https://mydomain.auth.us-east-2.amazoncognito.com/oauth2/token)
--username USER Cognito username (for USER_PASSWORD_AUTH flow)
--password PASS Cognito password (for USER_PASSWORD_AUTH flow)
--user-pool-id ID Cognito User Pool ID (e.g., us-east-1_AbCdEfG)
Required for --username/--password flow.
Optional for --token-url client_credentials flow.
Service Selection:
--service SERVICES Comma-separated list of services to test (e.g., s3,lambda,dynamodb)
--service-category CAT Test all services in specified categories (e.g., database,secrets)
--list-services Show all available services and categories
Examples:
# Test with environment variables
export AWS_ACCESS_KEY_ID="AKIAXXXXXXXXX"
export AWS_SECRET_ACCESS_KEY="secretkey"
$0
# Test specific Cognito Identity Pool
$0 -p us-east-1:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
# Test with direct credentials
$0 -a AKIAXXXXXXXXX -s secretkey -r us-west-2
# Decode credentials from Lambda response
$0 -e "PT1RYU1KVGJZUlVWRWhFYUpSa1N3..."
# Quick test (skip slow operations)
$0 --quick
# Test only S3 and Lambda
$0 --service s3,lambda
# Test only database services
$0 --service-category database
# Test database and secrets services
$0 --service-category database,secrets
# List all available services
$0 --list-services
# Get Bearer token with Cognito client credentials (no IAM keys needed)
$0 --client-id ABC123 --client-secret SECRETXYZ \\
--token-url https://mydomain.auth.us-east-2.amazoncognito.com/oauth2/token
# Client credentials + probe a specific API Gateway
API_BASE_URL=https://xxxxx.execute-api.us-east-2.amazonaws.com \\
$0 --client-id ABC123 --client-secret SECRETXYZ \\
--token-url https://mydomain.auth.us-east-2.amazoncognito.com/oauth2/token
# User Pool auth with username/password (exchanges for IAM creds)
$0 --client-id ABC123 --client-secret SECRETXYZ \\
--username user@example.com --password 'P@ssw0rd!' \\
--user-pool-id us-east-1_AbCdEfG -p us-east-1:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
Environment Variables:
AWS_ACCESS_KEY_ID AWS Access Key ID
AWS_SECRET_ACCESS_KEY AWS Secret Access Key
AWS_SESSION_TOKEN AWS Session Token (optional)
AWS_REGION AWS Region
COGNITO_IDENTITY_POOL_ID Cognito Identity Pool ID
ENCODED_CREDENTIALS Encoded credentials to decode
Output:
Results are saved to ./awsHunter_results_TIMESTAMP/
- security_report.md Full security assessment report
- ALL_SECRETS_FOUND.txt Consolidated list of discovered secrets
- *.json Raw API responses
- *_secrets.txt Extracted secrets per service
EOF
exit 0
}
#===============================================================================
# Parse Command Line Arguments
#===============================================================================
QUICK_MODE=false
VERBOSE=false
SKIP_COGNITO=false
SKIP_PRIVESC=false
SKIP_SECRETS=false
CUSTOM_OUTPUT_DIR=""
MULTI_REGION=false
CUSTOM_REGIONS=""
ALL_REGIONS=()
TEST_DESTRUCTIVE=false
SELECTED_SERVICES=""
SELECTED_CATEGORIES=""
# Services to test (space-separated string, used as a simple lookup)
SERVICES_TO_TEST=""
#===============================================================================
# Available Services Definition
#===============================================================================
# Service category definitions (using simple strings for compatibility)
CATEGORY_GLOBAL="s3 iam-users iam-roles route53 cloudfront organizations"
CATEGORY_COMPUTE="lambda ec2 ecs eks elasticbeanstalk lightsail batch emr sagemaker"
CATEGORY_DATABASE="dynamodb rds elasticache redshift documentdb neptune"
CATEGORY_STORAGE="efs fsx backup"
CATEGORY_SECRETS="secretsmanager ssm kms"
CATEGORY_MESSAGING="sqs sns kinesis firehose eventbridge mq"
CATEGORY_CONTAINERS="ecr"
CATEGORY_SERVERLESS="apigateway appsync amplify stepfunctions"
CATEGORY_DATA="glue athena"
CATEGORY_DEVTOOLS="codecommit codebuild codepipeline"
CATEGORY_IOT="iot transfer"
CATEGORY_SECURITY="guardduty securityhub inspector macie config cloudtrail ram wafv2"
CATEGORY_NETWORK="vpc security-groups subnets vpc-endpoints network-acls nat-gateways internet-gateways vpn directconnect elb target-groups"
CATEGORY_EMAIL="ses"
CATEGORY_LOGS="cloudwatch-logs"
CATEGORY_OTHER="cognito-pools cloudformation acm opensearch cost-explorer budgets"
# All categories list
ALL_CATEGORIES="global compute database storage secrets messaging containers serverless data devtools iot security network email logs other"
# Flat list of all services
ALL_SERVICES="s3 iam-users iam-roles route53 cloudfront organizations lambda ec2 ecs eks elasticbeanstalk lightsail batch emr sagemaker dynamodb rds elasticache redshift documentdb neptune efs fsx backup secretsmanager ssm kms sqs sns kinesis firehose eventbridge mq ecr apigateway appsync amplify stepfunctions glue athena codecommit codebuild codepipeline iot transfer guardduty securityhub inspector macie config cloudtrail ram wafv2 vpc security-groups subnets vpc-endpoints network-acls nat-gateways internet-gateways vpn directconnect elb target-groups ses cloudwatch-logs cognito-pools cloudformation acm opensearch cost-explorer budgets"
# Function to get services for a category
get_category_services() {
local category="$1"
case "$category" in
global) echo "$CATEGORY_GLOBAL" ;;
compute) echo "$CATEGORY_COMPUTE" ;;
database) echo "$CATEGORY_DATABASE" ;;
storage) echo "$CATEGORY_STORAGE" ;;
secrets) echo "$CATEGORY_SECRETS" ;;
messaging) echo "$CATEGORY_MESSAGING" ;;
containers) echo "$CATEGORY_CONTAINERS" ;;
serverless) echo "$CATEGORY_SERVERLESS" ;;
data) echo "$CATEGORY_DATA" ;;
devtools) echo "$CATEGORY_DEVTOOLS" ;;
iot) echo "$CATEGORY_IOT" ;;
security) echo "$CATEGORY_SECURITY" ;;
network) echo "$CATEGORY_NETWORK" ;;
email) echo "$CATEGORY_EMAIL" ;;
logs) echo "$CATEGORY_LOGS" ;;
other) echo "$CATEGORY_OTHER" ;;
*) echo "" ;;
esac
}
# Function to list all available services
list_services() {
echo -e "${CYAN}Available Services for Testing${NC}"
echo -e "${CYAN}===============================${NC}"
echo ""
echo -e "${YELLOW}[global]${NC}"
for service in $CATEGORY_GLOBAL; do echo " - $service"; done
echo ""
echo -e "${YELLOW}[compute]${NC}"
for service in $CATEGORY_COMPUTE; do echo " - $service"; done
echo ""
echo -e "${YELLOW}[database]${NC}"
for service in $CATEGORY_DATABASE; do echo " - $service"; done
echo ""
echo -e "${YELLOW}[storage]${NC}"
for service in $CATEGORY_STORAGE; do echo " - $service"; done
echo ""
echo -e "${YELLOW}[secrets]${NC}"
for service in $CATEGORY_SECRETS; do echo " - $service"; done
echo ""
echo -e "${YELLOW}[messaging]${NC}"
for service in $CATEGORY_MESSAGING; do echo " - $service"; done
echo ""
echo -e "${YELLOW}[containers]${NC}"
for service in $CATEGORY_CONTAINERS; do echo " - $service"; done
echo ""
echo -e "${YELLOW}[serverless]${NC}"
for service in $CATEGORY_SERVERLESS; do echo " - $service"; done
echo ""
echo -e "${YELLOW}[data]${NC}"
for service in $CATEGORY_DATA; do echo " - $service"; done
echo ""
echo -e "${YELLOW}[devtools]${NC}"
for service in $CATEGORY_DEVTOOLS; do echo " - $service"; done
echo ""
echo -e "${YELLOW}[iot]${NC}"
for service in $CATEGORY_IOT; do echo " - $service"; done
echo ""
echo -e "${YELLOW}[security]${NC}"
for service in $CATEGORY_SECURITY; do echo " - $service"; done
echo ""
echo -e "${YELLOW}[network]${NC}"
for service in $CATEGORY_NETWORK; do echo " - $service"; done
echo ""
echo -e "${YELLOW}[email]${NC}"
for service in $CATEGORY_EMAIL; do echo " - $service"; done
echo ""
echo -e "${YELLOW}[logs]${NC}"
for service in $CATEGORY_LOGS; do echo " - $service"; done
echo ""
echo -e "${YELLOW}[other]${NC}"
for service in $CATEGORY_OTHER; do echo " - $service"; done
echo ""
echo -e "${CYAN}Usage Examples:${NC}"
echo " # Test single service"
echo " $0 --service s3"
echo ""
echo " # Test multiple services"
echo " $0 --service s3,lambda,dynamodb"
echo ""
echo " # Test all services in a category"
echo " $0 --service-category global"
echo " $0 --service-category database,secrets"
echo ""
echo " # Test all services (default behavior)"
echo " $0"
exit 0
}
# Function to check if a service should be tested
should_test_service() {
local service="$1"
# If no specific services selected, test all
if [ -z "$SERVICES_TO_TEST" ]; then
return 0
fi
# Check if this service is in the selected list (with word boundaries)
if echo " $SERVICES_TO_TEST " | grep -q " $service "; then
return 0
fi
return 1
}
# Function to parse service selection
parse_service_selection() {
local services_input="$1"
local valid_count=0
# Clear existing selections
SERVICES_TO_TEST=""
# Parse comma-separated list
IFS=',' read -ra services_array <<< "$services_input"
for service in "${services_array[@]}"; do
# Trim whitespace
service=$(echo "$service" | xargs)
# Validate service exists
if echo " $ALL_SERVICES " | grep -q " $service "; then
SERVICES_TO_TEST="$SERVICES_TO_TEST $service"
((valid_count++))
else
print_warning "Unknown service: $service (skipping)"
fi
done
# Trim leading/trailing spaces
SERVICES_TO_TEST=$(echo "$SERVICES_TO_TEST" | xargs)
if [ -z "$SERVICES_TO_TEST" ]; then
print_error "No valid services specified!"
echo "Use --list-services to see available services"
exit 1
fi
print_info "Testing $valid_count selected services: $SERVICES_TO_TEST"
}
# Function to parse category selection
parse_category_selection() {
local categories_input="$1"
local valid_count=0
# Clear existing selections
SERVICES_TO_TEST=""
# Parse comma-separated list
IFS=',' read -ra categories_array <<< "$categories_input"
for category in "${categories_array[@]}"; do
# Trim whitespace
category=$(echo "$category" | xargs)
# Get services for this category
local cat_services=$(get_category_services "$category")
if [ -n "$cat_services" ]; then
SERVICES_TO_TEST="$SERVICES_TO_TEST $cat_services"
else
print_warning "Unknown category: $category (skipping)"
fi
done
# Trim and count unique services
SERVICES_TO_TEST=$(echo "$SERVICES_TO_TEST" | xargs)
valid_count=$(echo "$SERVICES_TO_TEST" | wc -w | xargs)
if [ -z "$SERVICES_TO_TEST" ]; then
print_error "No valid categories specified!"
echo "Available categories: $ALL_CATEGORIES"
exit 1
fi
print_info "Testing $valid_count services from selected categories"
}
while [[ $# -gt 0 ]]; do
case $1 in
-h|--help)
show_help
;;
-r|--region)
AWS_REGION="$2"
shift 2
;;
-p|--pool-id)
COGNITO_IDENTITY_POOL_ID="$2"
shift 2
;;
-e|--encoded)
ENCODED_CREDENTIALS="$2"
shift 2
;;
-a|--access-key)
DIRECT_ACCESS_KEY="$2"
shift 2
;;
-s|--secret-key)
DIRECT_SECRET_KEY="$2"
shift 2
;;
-t|--session-token)
DIRECT_SESSION_TOKEN="$2"
shift 2
;;
-o|--output)
CUSTOM_OUTPUT_DIR="$2"
shift 2
;;
-q|--quick)
QUICK_MODE=true
shift
;;
-v|--verbose)
VERBOSE=true
shift
;;
-m|--multi-region)
MULTI_REGION=true
shift
;;
--regions)
CUSTOM_REGIONS="$2"
MULTI_REGION=true
shift 2
;;
--skip-cognito)
SKIP_COGNITO=true
shift
;;
--skip-privesc)
SKIP_PRIVESC=true
shift
;;
--skip-secrets)
SKIP_SECRETS=true
shift
;;
--test-create)
TEST_DESTRUCTIVE=true
shift
;;
--service)
SELECTED_SERVICES="$2"
shift 2
;;
--service-category)
SELECTED_CATEGORIES="$2"
shift 2
;;
--client-id)
COGNITO_CLIENT_ID="$2"
shift 2
;;
--client-secret)
COGNITO_CLIENT_SECRET="$2"
shift 2
;;
--username)
COGNITO_USERNAME="$2"
shift 2
;;
--password)
COGNITO_PASSWORD="$2"
shift 2
;;
--user-pool-id)
COGNITO_USER_POOL_ID="$2"
shift 2
;;
--token-url)
COGNITO_TOKEN_URL="$2"
shift 2
;;
--list-services)
list_services
;;
*)
print_error "Unknown option: $1"
echo "Use -h or --help for usage information"
exit 1
;;
esac
done
# Validate Cognito client auth flag combinations
if [ -n "$COGNITO_CLIENT_ID" ]; then
if [ -z "$COGNITO_CLIENT_SECRET" ]; then
print_error "--client-id requires --client-secret"
exit 1
fi
if [ -n "$COGNITO_USERNAME" ] && [ -z "$COGNITO_PASSWORD" ]; then
print_error "--username requires --password"
exit 1
fi
if [ -z "$COGNITO_USERNAME" ] && [ -n "$COGNITO_PASSWORD" ]; then
print_error "--password requires --username"
exit 1
fi
# USER_PASSWORD_AUTH needs a User Pool ID to build the provider string
if [ -n "$COGNITO_USERNAME" ] && [ -z "$COGNITO_USER_POOL_ID" ]; then
print_error "--username/--password flow requires --user-pool-id"
exit 1
fi
# client_credentials flow without --token-url needs --user-pool-id for domain discovery
if [ -z "$COGNITO_USERNAME" ] && [ -z "$COGNITO_TOKEN_URL" ] && [ -z "$COGNITO_USER_POOL_ID" ]; then
print_error "Provide --token-url or --user-pool-id so the OAuth2 endpoint can be determined"
exit 1
fi
fi
# Parse service selection if specified
if [ -n "$SELECTED_SERVICES" ]; then
parse_service_selection "$SELECTED_SERVICES"
elif [ -n "$SELECTED_CATEGORIES" ]; then
parse_category_selection "$SELECTED_CATEGORIES"
fi
#===============================================================================
# Configuration
#===============================================================================
# Cognito Identity Pool to test (can be passed as argument or set here)
COGNITO_IDENTITY_POOL_ID="${COGNITO_IDENTITY_POOL_ID:-}"
AWS_REGION="${AWS_REGION:-us-east-1}"
# Encoded credentials string (from Lambda response - for decoding test)
ENCODED_CREDENTIALS="${ENCODED_CREDENTIALS:-}"
# Direct credentials (if already known)
DIRECT_ACCESS_KEY="${DIRECT_ACCESS_KEY:-${AWS_ACCESS_KEY_ID:-}}"
DIRECT_SECRET_KEY="${DIRECT_SECRET_KEY:-${AWS_SECRET_ACCESS_KEY:-}}"
DIRECT_SESSION_TOKEN="${DIRECT_SESSION_TOKEN:-${AWS_SESSION_TOKEN:-}}"
# Set custom output directory if specified
if [ -n "$CUSTOM_OUTPUT_DIR" ]; then
OUTPUT_DIR="$CUSTOM_OUTPUT_DIR"
fi
#===============================================================================
# Main Testing Functions
#===============================================================================
decode_credentials() {
print_section "DECODING CREDENTIALS"
if [ -n "$ENCODED_CREDENTIALS" ]; then
print_info "Attempting to decode encoded credentials string..."
# Try base64 decode + reverse + base64 decode
decoded=$(echo "$ENCODED_CREDENTIALS" | base64 -d 2>/dev/null | rev 2>/dev/null)
if [ -n "$decoded" ]; then
# Try to decode the reversed string
final_decoded=$(echo "$decoded" | base64 -d 2>/dev/null)
if [ -n "$final_decoded" ]; then
print_finding "Successfully decoded credentials!"
echo "$final_decoded"
# Try to extract Access Key and Secret Key
# Format: AKIAXXXXXXXXXXXXXXXXX/SecretKeyHere
if [[ "$final_decoded" =~ ^(AKIA[A-Z0-9]{16})/(.+)$ ]]; then
DECODED_ACCESS_KEY="${BASH_REMATCH[1]}"
DECODED_SECRET_KEY="${BASH_REMATCH[2]}"
print_finding "Extracted Access Key: $DECODED_ACCESS_KEY"
print_finding "Extracted Secret Key: $DECODED_SECRET_KEY"
echo "Access Key: $DECODED_ACCESS_KEY" >> "$OUTPUT_DIR/decoded_credentials.txt"
echo "Secret Key: $DECODED_SECRET_KEY" >> "$OUTPUT_DIR/decoded_credentials.txt"
fi
fi
fi
fi
}
test_cognito_unauth_access() {
print_section "TESTING COGNITO IDENTITY POOL UNAUTHENTICATED ACCESS"
print_info "Identity Pool ID: $COGNITO_IDENTITY_POOL_ID"
print_info "Region: $AWS_REGION"
# Step 1: Get an identity ID
echo -n "Getting identity ID... "
IDENTITY_RESULT=$(aws cognito-identity get-id \
--identity-pool-id "$COGNITO_IDENTITY_POOL_ID" \
--region "$AWS_REGION" 2>&1)
if echo "$IDENTITY_RESULT" | grep -q "IdentityId"; then
IDENTITY_ID=$(echo "$IDENTITY_RESULT" | jq -r '.IdentityId')
print_success "Got Identity ID: $IDENTITY_ID"
print_finding "Cognito Identity Pool allows UNAUTHENTICATED access!"
echo "$IDENTITY_RESULT" > "$OUTPUT_DIR/cognito_identity.json"
# Step 2: Get credentials for this identity
echo -n "Getting credentials for identity... "
CREDS_RESULT=$(aws cognito-identity get-credentials-for-identity \
--identity-id "$IDENTITY_ID" \
--region "$AWS_REGION" 2>&1)
if echo "$CREDS_RESULT" | grep -q "Credentials"; then
print_success "Got temporary credentials!"
print_finding "Unauthenticated credentials obtained!"
echo "$CREDS_RESULT" > "$OUTPUT_DIR/cognito_credentials.json"
# Extract credentials
COGNITO_ACCESS_KEY=$(echo "$CREDS_RESULT" | jq -r '.Credentials.AccessKeyId')
COGNITO_SECRET_KEY=$(echo "$CREDS_RESULT" | jq -r '.Credentials.SecretKey')
COGNITO_SESSION_TOKEN=$(echo "$CREDS_RESULT" | jq -r '.Credentials.SessionToken')
COGNITO_EXPIRATION=$(echo "$CREDS_RESULT" | jq -r '.Credentials.Expiration')
print_info "Access Key: $COGNITO_ACCESS_KEY"
print_info "Expiration: $COGNITO_EXPIRATION"
return 0
else
print_error "Failed to get credentials: $CREDS_RESULT"
return 1
fi
else
print_error "Failed to get identity: $IDENTITY_RESULT"
return 1
fi
}
test_cognito_client_auth() {
print_section "COGNITO USER POOL CLIENT AUTHENTICATION"
print_info "Client ID: $COGNITO_CLIENT_ID"
print_info "User Pool ID: $COGNITO_USER_POOL_ID"
[ -n "$COGNITO_USERNAME" ] && print_info "Username: $COGNITO_USERNAME"
local id_token=""
if [ -n "$COGNITO_USERNAME" ] && [ -n "$COGNITO_PASSWORD" ]; then
# USER_PASSWORD_AUTH flow
print_info "Attempting USER_PASSWORD_AUTH flow..."
local auth_params="USERNAME=${COGNITO_USERNAME},PASSWORD=${COGNITO_PASSWORD}"
if [ -n "$COGNITO_CLIENT_SECRET" ]; then
local secret_hash
secret_hash=$(printf '%s' "${COGNITO_USERNAME}${COGNITO_CLIENT_ID}" \
| openssl dgst -sha256 -hmac "$COGNITO_CLIENT_SECRET" -binary \
| base64)
auth_params="${auth_params},SECRET_HASH=${secret_hash}"
fi
echo -n "Authenticating... "
AUTH_RESULT=$(aws cognito-idp initiate-auth \
--client-id "$COGNITO_CLIENT_ID" \
--auth-flow USER_PASSWORD_AUTH \
--auth-parameters "$auth_params" \
--region "$AWS_REGION" 2>&1)
if echo "$AUTH_RESULT" | grep -q "AuthenticationResult"; then
print_success "Authentication successful!"
print_finding "Cognito User Pool accepted credentials!"
echo "$AUTH_RESULT" > "$OUTPUT_DIR/cognito_client_auth.json"
id_token=$(echo "$AUTH_RESULT" | jq -r '.AuthenticationResult.IdToken')
local access_token
access_token=$(echo "$AUTH_RESULT" | jq -r '.AuthenticationResult.AccessToken')
print_info "ID Token obtained (${#id_token} chars)"
print_info "Access Token obtained (${#access_token} chars)"
if echo "$AUTH_RESULT" | jq -e '.AuthenticationResult.NewDeviceMetadata' >/dev/null 2>&1; then
print_warning "New device metadata returned - MFA may be configured"
fi
elif echo "$AUTH_RESULT" | grep -q "ChallengeName"; then
local challenge
challenge=$(echo "$AUTH_RESULT" | jq -r '.ChallengeName')
print_warning "Auth challenge required: $challenge"
print_info "Challenges like NEW_PASSWORD_REQUIRED, MFA_SETUP, SMS_MFA need interactive handling"
echo "$AUTH_RESULT" > "$OUTPUT_DIR/cognito_auth_challenge.json"
return 1
else
print_error "Authentication failed: $AUTH_RESULT"
return 1
fi
else
# Client credentials (OAuth2) flow — no username/password
print_info "No username/password provided. Attempting client_credentials OAuth2 flow..."
local domain_url=""
if [ -n "$COGNITO_TOKEN_URL" ]; then
domain_url="$COGNITO_TOKEN_URL"
else
local token_endpoint
token_endpoint=$(aws cognito-idp describe-user-pool \
--user-pool-id "$COGNITO_USER_POOL_ID" \
--region "$AWS_REGION" \
--query 'UserPool.Domain' --output text 2>&1)
if [ -n "$token_endpoint" ] && [ "$token_endpoint" != "None" ]; then
domain_url="https://${token_endpoint}.auth.${AWS_REGION}.amazoncognito.com/oauth2/token"
else
print_error "Could not determine User Pool domain for OAuth2 endpoint"
print_info "Provide --token-url with the full OAuth2 token URL"
print_info " e.g., --token-url https://mydomain.auth.us-east-2.amazoncognito.com/oauth2/token"
print_info "Or provide --username and --password for USER_PASSWORD_AUTH flow instead"
return 1
fi
fi
local basic_auth
basic_auth=$(printf '%s:%s' "$COGNITO_CLIENT_ID" "$COGNITO_CLIENT_SECRET" | base64)
print_info "Token endpoint: $domain_url"
echo -n "Requesting client_credentials grant... "
local token_result
token_result=$(curl -s -X POST "$domain_url" \
-H "Authorization: Basic ${basic_auth}" \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "grant_type=client_credentials" 2>&1)
if echo "$token_result" | jq -e '.access_token' >/dev/null 2>&1; then
print_success "Client credentials grant successful!"
OAUTH2_ACCESS_TOKEN=$(echo "$token_result" | jq -r '.access_token')
OAUTH2_TOKEN_URL="$domain_url"
print_info "Access Token obtained (${#OAUTH2_ACCESS_TOKEN} chars)"
echo "$token_result" > "$OUTPUT_DIR/cognito_oauth2_token.json"
local expires_in
expires_in=$(echo "$token_result" | jq -r '.expires_in // empty')
[ -n "$expires_in" ] && print_info "Token expires in: ${expires_in}s"
print_info "Token type: client_credentials (Bearer)"
print_warning "This token cannot be exchanged for IAM credentials (no IdToken)"
print_info "Will probe APIs accessible with this Bearer token"
return 0
else
print_error "Client credentials grant failed: $token_result"
return 1
fi
fi
# Exchange IdToken for AWS credentials via Identity Pool
if [ -z "$COGNITO_IDENTITY_POOL_ID" ]; then
print_warning "No Identity Pool ID (-p) provided"
print_warning "Cannot exchange tokens for AWS credentials without an Identity Pool"
print_info "IdToken saved — provide -p <identity-pool-id> to get AWS credentials"
return 1
fi
local provider="cognito-idp.${AWS_REGION}.amazonaws.com/${COGNITO_USER_POOL_ID}"
print_info "Exchanging IdToken via Identity Pool..."
print_info "Provider: $provider"
echo -n "Getting identity ID (authenticated)... "
local id_result
id_result=$(aws cognito-identity get-id \
--identity-pool-id "$COGNITO_IDENTITY_POOL_ID" \
--logins "{\"${provider}\": \"${id_token}\"}" \
--region "$AWS_REGION" 2>&1)
if echo "$id_result" | grep -q "IdentityId"; then
local identity_id
identity_id=$(echo "$id_result" | jq -r '.IdentityId')
print_success "Got authenticated Identity ID: $identity_id"
echo -n "Getting AWS credentials for authenticated identity... "
local creds_result
creds_result=$(aws cognito-identity get-credentials-for-identity \
--identity-id "$identity_id" \
--logins "{\"${provider}\": \"${id_token}\"}" \
--region "$AWS_REGION" 2>&1)
if echo "$creds_result" | grep -q "Credentials"; then
print_success "Got temporary AWS credentials!"
print_finding "Authenticated Cognito credentials obtained!"
echo "$creds_result" > "$OUTPUT_DIR/cognito_authenticated_credentials.json"
COGNITO_ACCESS_KEY=$(echo "$creds_result" | jq -r '.Credentials.AccessKeyId')
COGNITO_SECRET_KEY=$(echo "$creds_result" | jq -r '.Credentials.SecretKey')
COGNITO_SESSION_TOKEN=$(echo "$creds_result" | jq -r '.Credentials.SessionToken')
local expiration
expiration=$(echo "$creds_result" | jq -r '.Credentials.Expiration')
print_info "Access Key: $COGNITO_ACCESS_KEY"
print_info "Expiration: $expiration"
return 0
else
print_error "Failed to get credentials for authenticated identity: $creds_result"
return 1
fi
else
print_error "Failed to get authenticated identity: $id_result"
return 1
fi
}
enumerate_with_bearer_token() {
print_section "BEARER TOKEN ENUMERATION"
print_info "Enumerating access using OAuth2 Bearer token"
print_info "Token length: ${#OAUTH2_ACCESS_TOKEN} chars"
# --- Decode JWT claims ---
print_section "JWT TOKEN ANALYSIS"
local jwt_payload
jwt_payload=$(echo "$OAUTH2_ACCESS_TOKEN" | cut -d'.' -f2)
# Fix base64 padding
local padded="$jwt_payload"
local mod=$((${#padded} % 4))
if [ "$mod" -eq 2 ]; then padded="${padded}==";
elif [ "$mod" -eq 3 ]; then padded="${padded}="; fi
local decoded_claims
decoded_claims=$(echo "$padded" | base64 -d 2>/dev/null)
if [ -n "$decoded_claims" ] && echo "$decoded_claims" | jq . >/dev/null 2>&1; then
print_success "JWT decoded successfully"
echo "$decoded_claims" | jq . > "$OUTPUT_DIR/jwt_claims.json"
echo "$decoded_claims" | jq .
local issuer client_id token_use scopes sub exp
issuer=$(echo "$decoded_claims" | jq -r '.iss // empty')
client_id=$(echo "$decoded_claims" | jq -r '.client_id // empty')
token_use=$(echo "$decoded_claims" | jq -r '.token_use // empty')
scopes=$(echo "$decoded_claims" | jq -r '.scope // empty')
sub=$(echo "$decoded_claims" | jq -r '.sub // empty')
exp=$(echo "$decoded_claims" | jq -r '.exp // empty')
[ -n "$issuer" ] && print_info "Issuer: $issuer"
[ -n "$client_id" ] && print_info "Client ID: $client_id"
[ -n "$token_use" ] && print_info "Token use: $token_use"
[ -n "$sub" ] && print_info "Subject: $sub"
if [ -n "$scopes" ]; then
print_finding "Scopes: $scopes"
echo "$scopes" > "$OUTPUT_DIR/token_scopes.txt"
fi