forked from aws-samples/aws-ipranges-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaws-ipranges-alb.yaml
849 lines (803 loc) · 29.4 KB
/
aws-ipranges-alb.yaml
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
AWSTemplateFormatVersion: 2010-09-09
Description: ALB website that returns AWS IP prefixes from ip-ranges.json ( https://github.com/aws-samples/aws-ipranges-api )
Metadata:
License:
Description: >
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: MIT-0
Permission is hereby granted, free of charge, to any person obtaining a copy of this
software and associated documentation files (the "Software"), to deal in the Software
without restriction, including without limitation the rights to use, copy, modify,
merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
AWS::CloudFormation::Interface:
ParameterGroups:
- Label:
default: ALB API
Parameters:
- awsServices
- allowedIPv4prefix
- allowedIPv6prefix
- Label:
default: Lambda
Parameters:
- pythonRuntime
- cpuArchitecture
- Label:
default: Load Balancer
Parameters:
- albScheme
- Label:
default: Networking
Parameters:
- ipAddressType
- vpc
- subnets
- Label:
default: "[Optional] HTTPS listener"
Parameters:
- certificateArn
- securityPolicy
- redirectHTTPtoHTTPS
- sendHSTSheader
ParameterLabels:
awsServices:
default: "Default AWS Service IP prefixes to return separated by commas ( https://docs.aws.amazon.com/vpc/latest/userguide/aws-ip-ranges.html#aws-ip-syntax )"
allowedIPv4prefix:
default: "Allowed source IPv4 prefix (e.g. 1.2.3.4/32). Get your IP from https://checkip.amazonaws.com"
allowedIPv6prefix:
default: "Allowed source IPv6 prefix"
pythonRuntime:
default: Python 3 runtime version ( https://docs.aws.amazon.com/lambda/latest/dg/lambda-python.html )
cpuArchitecture:
default: Instruction set architecture ( https://docs.aws.amazon.com/lambda/latest/dg/foundation-arch.html )
albScheme:
default: Load balancer scheme (internal or internet facing)
ipAddressType:
default: IPv4 only, IPv6 only or dual stack (IPv4-and-IPv6)
vpc:
default: VPC to provision ALB
subnets:
default: Subnets to provision ALB (choose at least 2)
certificateArn:
default: "Certificate ARN. Get from https://console.aws.amazon.com/acm/home?#/certificates/list ( aws acm list-certificates )"
securityPolicy:
default: "HTTPS listener security policy ( https://docs.aws.amazon.com/elasticloadbalancing/latest/application/create-https-listener.html#describe-ssl-policies )"
redirectHTTPtoHTTPS:
default: Redirect HTTP requests to HTTPS
sendHSTSheader:
default: Send HSTS (HTTP Strict Transport Security) header
Mappings:
albIpTypeMapping:
IPv4:
Value: ipv4
IPv4-and-IPv6:
Value: dualstack
IPv6:
Value: dualstack-without-public-ipv4
Parameters:
awsServices:
Type: CommaDelimitedList
AllowedValues:
- AMAZON
- AMAZON_APPFLOW
- AMAZON_CONNECT
- API_GATEWAY
- CHIME_MEETINGS
- CHIME_VOICECONNECTOR
- CLOUD9
- CLOUDFRONT
- CLOUDFRONT_ORIGIN_FACING
- CODEBUILD
- DYNAMODB
- EBS
- EC2
- EC2_INSTANCE_CONNECT
- GLOBALACCELERATOR
- IVS_REALTIME
- KINESIS_VIDEO_STREAMS
- MEDIA_PACKAGE_V2
- ROUTE53
- ROUTE53_HEALTHCHECKS
- ROUTE53_HEALTHCHECKS_PUBLISHING
- ROUTE53_RESOLVER
- S3
- WORKSPACES_GATEWAYS
Default: CLOUDFRONT_ORIGIN_FACING
ConstraintDescription: Enter a valid AWS service
allowedIPv4prefix:
Type: String
AllowedPattern: "^\\d+\\.\\d+\\.\\d+\\.\\d+\\/\\d+$"
Default: 0.0.0.0/0
allowedIPv6prefix:
Type: String
AllowedPattern: ".+"
Default: ::/0
pythonRuntime:
Type: String
AllowedPattern: "python3\\.\\d{1,2}"
ConstraintDescription: Enter a valid Python version
Default: python3.13
cpuArchitecture:
Type: String
AllowedValues:
- x86_64
- arm64
Default: arm64
certificateArn:
Type: String
Default: ""
securityPolicy:
Type: String
AllowedValues:
- ELBSecurityPolicy-TLS13-1-3-FIPS-2023-04
- ELBSecurityPolicy-TLS13-1-3-2021-06
- ELBSecurityPolicy-TLS13-1-2-Res-FIPS-2023-04
- ELBSecurityPolicy-TLS13-1-2-Res-2021-06
- ELBSecurityPolicy-TLS13-1-2-FIPS-2023-04
- ELBSecurityPolicy-TLS13-1-2-Ext2-FIPS-2023-04
- ELBSecurityPolicy-TLS13-1-2-Ext2-2021-06
- ELBSecurityPolicy-TLS13-1-2-Ext1-FIPS-2023-04
- ELBSecurityPolicy-TLS13-1-2-Ext1-2021-06
- ELBSecurityPolicy-TLS13-1-2-Ext0-FIPS-2023-04
- ELBSecurityPolicy-TLS13-1-2-2021-06
- ELBSecurityPolicy-TLS13-1-1-FIPS-2023-04
- ELBSecurityPolicy-TLS13-1-1-2021-06
- ELBSecurityPolicy-TLS13-1-0-FIPS-2023-04
- ELBSecurityPolicy-TLS13-1-0-2021-06
- ELBSecurityPolicy-TLS-1-2-Ext-2018-06
- ELBSecurityPolicy-TLS-1-2-2017-01
- ELBSecurityPolicy-TLS-1-1-2017-01
- ELBSecurityPolicy-TLS-1-0-2015-04
- ELBSecurityPolicy-FS-2018-06
- ELBSecurityPolicy-FS-1-2-Res-2020-10
- ELBSecurityPolicy-FS-1-2-Res-2019-08
- ELBSecurityPolicy-FS-1-2-2019-08
- ELBSecurityPolicy-FS-1-1-2019-08
- ELBSecurityPolicy-2016-08
Default: ELBSecurityPolicy-TLS13-1-2-2021-06
redirectHTTPtoHTTPS:
Type: String
AllowedValues:
- "Yes"
- "No"
Default: "No"
sendHSTSheader:
Type: String
AllowedValues:
- "Yes"
- "No"
Default: "Yes"
albScheme:
Type: String
AllowedValues:
- internet-facing
- internal
Default: internet-facing
ipAddressType:
Type: String
AllowedValues:
- IPv4
- IPv4-and-IPv6
- IPv6
Default: IPv4
vpc:
Type: AWS::EC2::VPC::Id
subnets:
Type: List<AWS::EC2::Subnet::Id>
Conditions:
createHttpsListener: !Not [!Equals [!Ref certificateArn, ""]]
createIPv4HttpsListener:
!And [!Condition createHttpsListener, !Condition allowIPv4]
createIPv6HttpsListener:
!And [!Condition createHttpsListener, !Condition allowIPv6]
createHttpListener: !Equals [!Ref redirectHTTPtoHTTPS, "No"]
createHttpRedirectListener: !Equals [!Ref redirectHTTPtoHTTPS, "Yes"]
sendHSTS: !Equals [!Ref sendHSTSheader, "Yes"]
allowIPv4:
!Or [
!Equals [!Ref ipAddressType, "IPv4"],
!Equals [!Ref ipAddressType, "IPv4-and-IPv6"],
]
allowIPv6:
!Or [
!Equals [!Ref ipAddressType, "IPv6"],
!Equals [!Ref ipAddressType, "IPv4-and-IPv6"],
]
Resources:
lambdaFunctionIamRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Principal:
Service:
- lambda.amazonaws.com
Action:
- sts:AssumeRole
Policies: # Access logs at https://docs.aws.amazon.com/lambda/latest/operatorguide/access-logs.html
- PolicyName: lambdaFunctionPolicy
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action:
- logs:CreateLogStream
- logs:PutLogEvents
Resource: !Sub
- "arn:${AWS::Partition}:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/lambda/${AWS::StackName}-lambdaFunction-${UID}:*"
- UID:
!Select [
3,
!Split [
"-",
!Select [2, !Split ["/", !Ref AWS::StackId]],
],
]
Tags:
- Key: StackName
Value: !Ref AWS::StackName
- Key: StackId
Value: !Ref AWS::StackId
- Key: GitHub
Value: https://github.com/aws-samples/aws-ipranges-api
lambdaFunctionLogGroup:
Type: AWS::Logs::LogGroup
DeletionPolicy: Delete
UpdateReplacePolicy: Delete
Properties:
KmsKeyId: !Ref AWS::NoValue
RetentionInDays: !Ref AWS::NoValue
LogGroupName: !Sub
- "/aws/lambda/${AWS::StackName}-lambdaFunction-${UID}"
- UID:
!Select [
3,
!Split ["-", !Select [2, !Split ["/", !Ref AWS::StackId]]],
]
Tags:
- Key: StackName
Value: !Ref AWS::StackName
- Key: StackId
Value: !Ref AWS::StackId
- Key: GitHub
Value: https://github.com/aws-samples/aws-ipranges-api
lambdaFunction:
Type: AWS::Lambda::Function
Properties:
Description: !Sub "[${AWS::StackName}] - Returns AWS IP prefixes for ALB"
FunctionName: !Sub
- "${AWS::StackName}-lambdaFunction-${UID}"
- UID:
!Select [
3,
!Split ["-", !Select [2, !Split ["/", !Ref AWS::StackId]]],
]
Handler: "index.lambda_handler"
MemorySize: 1769
ReservedConcurrentExecutions: !Ref AWS::NoValue
Role: !GetAtt lambdaFunctionIamRole.Arn
Environment:
Variables:
SERVICES: !Join [",", !Ref awsServices]
SEND_HSTS_HEADER: !If [sendHSTS, "true", "false"]
Runtime: !Ref pythonRuntime
Timeout: 25
Architectures:
- !Ref cpuArchitecture
Code: # https://docs.aws.amazon.com/lambda/latest/dg/services-alb.html
ZipFile: |
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0
import os
import json
from urllib import request
import ipaddress
# AWS services to return for default API
default_services = os.getenv('SERVICES', 'CLOUDFRONT_ORIGIN_FACING').split(',')
if default_services == ['']:
default_services = ['CLOUDFRONT_ORIGIN_FACING']
# Search function: check if valid IP address
def is_ipAddress(address):
try:
ipaddress.ip_address(address)
return True
except ValueError:
return False
def is_ipv4(address):
try:
ipaddress.IPv4Address(address)
return True
except ValueError:
return False
def lambda_handler(event, context):
# load ip-ranges.json
response = request.urlopen('https://ip-ranges.amazonaws.com/ip-ranges.json')
data = response.read()
ipranges_json = json.loads(data)
createDate = ipranges_json['createDate']
syncToken = ipranges_json['syncToken']
# send HSTS header?
sendHSTSheader = os.getenv('SEND_HSTS_HEADER', 'false') == 'true' and event['headers']['x-forwarded-proto'] and event['headers']['x-forwarded-proto'] == 'https'
hstsValue = "max-age=31536000"
url = event['path']
if url.lower() == '/favicon.ico':
if sendHSTSheader:
return {
'statusCode': 404,
'isBase64Encoded': False,
'body': 'Not Found!',
"headers": {
"Strict-Transport-Security": hstsValue,
"content-type": "text/html"
}
}
else:
return {
'statusCode': 404,
'isBase64Encoded': False,
'body': 'Not Found!',
"headers": {
"content-type": "text/html"
}
}
elif url.lower() == '/robots.txt':
if sendHSTSheader:
return {
'statusCode': 200,
'body' : 'User-agent: *\nDisallow: /',
'statusDescription': '200 OK',
'isBase64Encoded': False,
"headers": {
"Strict-Transport-Security": hstsValue,
"content-type": "text/plain"
}
}
else:
return {
'statusCode': 200,
'body' : 'User-agent: *\nDisallow: /',
'statusDescription': '200 OK',
'isBase64Encoded': False,
"headers": {
"content-type": "text/plain"
}
}
elif url.lower() == '/createdate':
if sendHSTSheader:
return {
'statusCode': 200,
'isBase64Encoded': False,
'body' : createDate,
"headers": {
"Strict-Transport-Security": hstsValue,
"content-type": "text/plain"
}
}
else:
return {
'statusCode': 200,
'isBase64Encoded': False,
'body' : createDate,
"headers": {
"content-type": "text/plain"
}
}
elif url.lower() == '/synctoken':
if sendHSTSheader:
return {
'statusCode': 200,
'isBase64Encoded': False,
'body' : syncToken,
"headers": {
"Strict-Transport-Security": hstsValue,
"content-type": "text/plain"
}
}
else:
return {
'statusCode': 200,
'isBase64Encoded': False,
'body' : syncToken,
"headers": {
"content-type": "text/plain"
}
}
# available aws services/regions/network_border_groups
all_aws_services = list()
all_aws_regions = list()
all_aws_networks = list()
for i in ipranges_json['prefixes']:
if i['service'] not in all_aws_services:
all_aws_services.append(i['service'])
if i['region'] not in all_aws_regions:
all_aws_regions.append(i['region'])
if i['network_border_group'] not in all_aws_networks:
all_aws_networks.append(i['network_border_group'])
args = url.split('/')
responseBody = ''
# SERVICES and REGIONS to filter by?
SERVICES = all_aws_services.copy()
REGIONS = all_aws_regions.copy()
NETWORKS = all_aws_networks.copy()
# return list of all prefixes / services / regions / network_border_groups
if len(args) == 2:
SERVICES = default_services
if args[1].upper() == 'SERVICE':
responseBody = all_aws_services
elif args[1].upper() == 'REGION':
responseBody = all_aws_regions
elif args[1].upper() == 'NETWORK':
responseBody = all_aws_networks
elif args[1].upper() == "SEARCH":
responseBody = list()
responseBody.append("Enter a IP address to query")
if responseBody != '':
if sendHSTSheader:
return {
'statusCode': 200,
'body': '\n'.join(sorted(responseBody)),
"headers": {
"Strict-Transport-Security": hstsValue,
"content-type": "text/plain",
"path" : url,
"syncToken": ipranges_json['syncToken'],
"createDate": ipranges_json['createDate']
}
}
else:
return {
'statusCode': 200,
'body': '\n'.join(sorted(responseBody)),
"headers": {
"content-type": "text/plain",
"path" : url,
"syncToken": ipranges_json['syncToken'],
"createDate": ipranges_json['createDate']
}
}
elif len(args) >= 3:
# /SERVICE/<SERVICE>/<REGION>
if args[1].upper()=='SERVICE' and args[2] in all_aws_services:
SERVICES = [args[2]]
if len(args) >=4 and args[3] in all_aws_regions:
REGIONS = [args[3]]
# /REGION/<REGION>/<SERVICE>
elif args[1].upper()=='REGION' and args[2] in all_aws_regions:
REGIONS = [args[2]]
if len(args) >=4 and args[3] in all_aws_services:
SERVICES= [args[3]]
# /NETWORK/<NETWORK>/<SERVICE>
elif args[1].upper()=='NETWORK' and args[2] in all_aws_networks:
NETWORKS = [args[2]]
if len(args) >=4 and args[3] in all_aws_services:
SERVICES= [args[3]]
# /SEARCH/<IPv4 or IPv6 Address>
elif args[1].upper() == 'SEARCH' and is_ipAddress(args[2]):
aws_ranges = list()
ip_object = ipaddress.ip_address(args[2])
if is_ipv4(args[2]):
for i in ipranges_json['prefixes']:
if ip_object in ipaddress.ip_network(i['ip_prefix']):
aws_ranges.append(i['ip_prefix'] + "," + i['region'] + "," + i["service"] + "," + i["network_border_group"])
else:
for i in ipranges_json['ipv6_prefixes']:
if ip_object in ipaddress.ip_network(i['ipv6_prefix']):
aws_ranges.append(i['ipv6_prefix'] + "," + i['region'] + "," + i["service"] + "," + i["network_border_group"])
if len(aws_ranges) > 0:
aws_ranges.insert(0, 'ip_prefix,region,service,network_border_group')
if sendHSTSheader:
return {
'statusCode': 200,
'body': '\n'.join(aws_ranges),
"headers": {
"Strict-Transport-Security": hstsValue,
"content-type": "text/plain",
"path" : url,
"syncToken": ipranges_json['syncToken'],
"createDate": ipranges_json['createDate']
}
}
else:
return {
'statusCode': 200,
'body': '\n'.join(aws_ranges),
"headers": {
"content-type": "text/plain",
"path" : url,
"syncToken": ipranges_json['syncToken'],
"createDate": ipranges_json['createDate']
}
}
else:
if sendHSTSheader:
return {
'statusCode': 404,
'body': 'Not AWS IP address',
"headers": {
"Strict-Transport-Security": hstsValue,
"content-type": "text/html"
}
}
else:
return {
'statusCode': 404,
'body': 'Not AWS IP address',
"headers": {
"content-type": "text/html"
}
}
else:
if sendHSTSheader:
return {
'statusCode': 404,
'body': 'Not Found!',
"headers": {
"Strict-Transport-Security": hstsValue,
"content-type": "text/html"
}
}
else:
return {
'statusCode': 404,
'body': 'Not Found!',
"headers": {
"content-type": "text/html"
}
}
# IPv4 / IPv6 only? :
ipv4_only = url.upper().endswith('/IPV4.TXT')
ipv6_only = url.upper().endswith('/IPV6.TXT')
prefixes = ''
aws_region = list()
aws_service = list()
aws_network = list()
ipv4_prefixes = list()
if not ipv6_only:
for i in ipranges_json['prefixes']:
if i['service'] in SERVICES and i['region'] in REGIONS and i['network_border_group'] in NETWORKS and i['ip_prefix'] not in ipv4_prefixes:
ipv4_prefixes.append(i['ip_prefix'])
if i['region'] not in aws_region:
aws_region.append(i['region'])
if i['service'] not in aws_service:
aws_service.append(i['service'])
if i['network_border_group'] not in aws_network:
aws_network.append(i['network_border_group'])
prefixes = '\n'.join(sorted(ipv4_prefixes, key = ipaddress.IPv4Network))
ipv6_prefixes = list()
if not ipv4_only:
for i in ipranges_json['ipv6_prefixes']:
if i['service'] in SERVICES and i['region'] in REGIONS and i['network_border_group'] in NETWORKS and i['ipv6_prefix'] not in ipv6_prefixes:
ipv6_prefixes.append(i['ipv6_prefix'])
if i['region'] not in aws_region:
aws_region.append(i['region'])
if i['service'] not in aws_service:
aws_service.append(i['service'])
if i['network_border_group'] not in aws_network:
aws_network.append(i['network_border_group'])
if len(prefixes) > 0:
prefixes += '\n'
prefixes += '\n'.join(sorted(ipv6_prefixes, key = ipaddress.IPv6Network))
sourceIp = event['headers']['x-forwarded-for']
print(f'Source IP:{sourceIp}, Path:{url}, IPv4 Prefixes:{len(ipv4_prefixes)}, IPv6 Prefixes:{len(ipv6_prefixes)}, createDate:{createDate}, syncToken:{syncToken}')
if sendHSTSheader:
return {
'statusCode': 200,
'isBase64Encoded': False,
'body': prefixes,
"headers": {
"Strict-Transport-Security": hstsValue,
"content-type": "text/plain",
"aws-service" : ','.join(sorted(aws_service)),
"aws-region" : ','.join(sorted(aws_region)),
"aws-network" : ','.join(sorted(aws_network)),
"path" : url,
"syncToken": syncToken,
"createDate": createDate
}
}
else:
return {
'statusCode': 200,
'isBase64Encoded': False,
'body': prefixes,
"headers": {
"content-type": "text/plain",
"aws-service" : ','.join(sorted(aws_service)),
"aws-region" : ','.join(sorted(aws_region)),
"aws-network" : ','.join(sorted(aws_network)),
"path" : url,
"syncToken": syncToken,
"createDate": createDate
}
}
Tags:
- Key: StackName
Value: !Ref AWS::StackName
- Key: StackId
Value: !Ref AWS::StackId
- Key: GitHub
Value: https://github.com/aws-samples/aws-ipranges-api
- Key: Description
Value: Returns AWS IP prefixes from ip-ranges.json
lambdaVersion:
Type: AWS::Lambda::Version
Properties:
FunctionName: !Ref lambdaFunction
Description: Version 1.0
alb: # https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticloadbalancingv2-loadbalancer-loadbalancerattribute.html
Type: AWS::ElasticLoadBalancingV2::LoadBalancer
Properties:
IpAddressType: !FindInMap [albIpTypeMapping, !Ref ipAddressType, Value]
Scheme: !Ref albScheme
SecurityGroups:
- !Ref securityGroup
Subnets: !Ref subnets
Tags:
- Key: StackName
Value: !Ref AWS::StackName
- Key: StackId
Value: !Ref AWS::StackId
securityGroup:
Type: AWS::EC2::SecurityGroup
Properties:
GroupDescription: Allow inbound to ALB
VpcId: !Ref vpc
SecurityGroupIngress:
- !If
- allowIPv4
- Description: HTTP (IPv4)
IpProtocol: "tcp"
FromPort: "80"
ToPort: "80"
CidrIp: !Ref allowedIPv4prefix
- !Ref AWS::NoValue
- !If
- allowIPv6
- Description: HTTP (IPv6)
IpProtocol: "tcp"
FromPort: "80"
ToPort: "80"
CidrIpv6: !Ref allowedIPv6prefix
- !Ref AWS::NoValue
- !If
- createIPv4HttpsListener
- Description: HTTPS (IPv4)
IpProtocol: tcp
FromPort: 443
ToPort: 443
CidrIp: !Ref allowedIPv4prefix
- !Ref AWS::NoValue
- !If
- createIPv6HttpsListener
- Description: HTTPS (IPv6)
IpProtocol: tcp
FromPort: 443
ToPort: 443
CidrIpv6: !Ref allowedIPv6prefix
- !Ref AWS::NoValue
SecurityGroupEgress:
- !If
- allowIPv4
- Description: Ping
IpProtocol: icmp
FromPort: -1
ToPort: -1
CidrIp: !Ref allowedIPv4prefix
- !Ref AWS::NoValue
- !If
- allowIPv6
- Description: Ping
IpProtocol: icmp
FromPort: -1
ToPort: -1
CidrIpv6: !Ref allowedIPv6prefix
- !Ref AWS::NoValue
Tags:
- Key: StackName
Value: !Ref AWS::StackName
- Key: StackId
Value: !Ref AWS::StackId
- Key: Name
Value: !Sub
- "${AWS::StackName}-securityGroup-${UID}"
- UID:
!Select [
3,
!Split ["-", !Select [2, !Split ["/", !Ref AWS::StackId]]],
]
httpListener:
Type: AWS::ElasticLoadBalancingV2::Listener
Condition: createHttpListener
Properties:
LoadBalancerArn: !Ref alb
Port: 80
Protocol: HTTP
DefaultActions:
- Type: forward
TargetGroupArn: !Ref targetGroup
httpRedirectListener:
Type: AWS::ElasticLoadBalancingV2::Listener
Condition: createHttpRedirectListener
Properties:
LoadBalancerArn: !Ref alb
Port: 80
Protocol: HTTP
DefaultActions:
- Type: "redirect"
RedirectConfig:
Protocol: "HTTPS"
Port: 443
Host: "#{host}"
Path: "/#{path}"
Query: "#{query}"
StatusCode: "HTTP_301"
httpsListener:
Type: AWS::ElasticLoadBalancingV2::Listener
Condition: createHttpsListener
Properties:
LoadBalancerArn: !Ref alb
Port: 443
Protocol: HTTPS
Certificates:
- CertificateArn: !Ref certificateArn
SslPolicy: !Ref securityPolicy
DefaultActions:
- Type: forward
TargetGroupArn: !Ref targetGroup
lambdaInvokePermission:
Type: AWS::Lambda::Permission
Properties:
FunctionName: !GetAtt lambdaFunction.Arn
Action: "lambda:InvokeFunction"
Principal: elasticloadbalancing.amazonaws.com
SourceArn: !Sub
- "arn:${AWS::Partition}:elasticloadbalancing:${AWS::Region}:${AWS::AccountId}:targetgroup/${AWS::StackName}-${UID}/*"
- UID:
!Select [
3,
!Split ["-", !Select [2, !Split ["/", !Ref AWS::StackId]]],
]
targetGroup:
Type: AWS::ElasticLoadBalancingV2::TargetGroup
Properties:
Name: !Sub
- "${AWS::StackName}-${UID}"
- UID:
!Select [
3,
!Split ["-", !Select [2, !Split ["/", !Ref AWS::StackId]]],
]
HealthCheckEnabled: false
TargetType: lambda
Targets:
- Id: !GetAtt lambdaFunction.Arn
Tags:
- Key: StackName
Value: !Ref AWS::StackName
- Key: StackId
Value: !Ref AWS::StackId
Outputs:
albDnsName:
Description: ALB DNS Name
Value: !GetAtt alb.DNSName
albConsole:
Description: ALB Console
Value: !Sub https://${AWS::Region}.console.aws.amazon.com/ec2/home?region=${AWS::Region}#LoadBalancer:loadBalancerArn=${alb.LoadBalancerArn}
lambdaFunctionLog:
Description: Cloudwatch log for Lambda function
Value: !Sub
- "https://console.aws.amazon.com/cloudwatch/home?region=${AWS::Region}#logsV2:log-groups/log-group/$252Faws$252Flambda$252F${AWS::StackName}-lambdaFunction-${UID}"
- UID:
!Select [
3,
!Split ["-", !Select [2, !Split ["/", !Ref AWS::StackId]]],
]