-
Notifications
You must be signed in to change notification settings - Fork 2
/
aws-ipranges-cloudfront.yaml
605 lines (565 loc) · 22 KB
/
aws-ipranges-cloudfront.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
AWSTemplateFormatVersion: 2010-09-09
Description: CloudFront 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: CloudFront API
Parameters:
- awsServices
- Label:
default: Lambda
Parameters:
- pythonRuntime
- cpuArchitecture
- Label:
default: CloudFront
Parameters:
- enableIPv6
- viewerProtocolPolicy
- cachePolicy
- responseHeaderPolicy
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 )"
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 )
enableIPv6:
default: Enable IPv6
viewerProtocolPolicy:
default: Communication policy between viewer and CloudFront
cachePolicy:
default: Managed cache policy ( https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/using-managed-cache-policies.html )
responseHeaderPolicy:
default: Managed response headers policy ( https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/using-managed-response-headers-policies.html )
Mappings:
cachePolicyMapping: # https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/using-managed-cache-policies.html
CachingDisabled:
Value: 4135ea2d-6df8-44a3-9df3-4b5a84be39ad
CachingOptimized:
Value: 658327ea-f89d-4fab-a63d-7e88639e58f6
CachingOptimizedForUncompressedObjects:
Value: b2884449-e4de-46a7-ac36-70bc7f1ddd6d
UseOriginCacheControlHeaders:
Value: 83da9c7e-98b4-4e11-a168-04f0df8e2c65
responseHeaderPolicyMapping: # https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/using-managed-response-headers-policies.html
CORS-and-SecurityHeadersPolicy:
Value: e61eb60c-9c35-4d20-a928-2b84e02af89c
CORS-With-Preflight:
Value: 5cc3b908-e619-4b99-88e5-2cf7f45965bd
CORS-with-preflight-and-SecurityHeadersPolicy:
Value: eaab4381-ed33-4a86-88ca-d9558dc6cd63
SecurityHeadersPolicy:
Value: 67f7725c-6f97-4210-82d7-5512b31e9d03
SimpleCORS:
Value: 60669652-455b-4ae9-85a4-c4c02393f86c
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
pythonRuntime:
Type: String
AllowedPattern: "python3\\.\\d{1,2}"
ConstraintDescription: Enter a valid Python version
Default: python3.12
cpuArchitecture:
Type: String
AllowedValues:
- x86_64
- arm64
Default: arm64
enableIPv6:
Type: String
AllowedValues:
- "Yes"
- "No"
Default: "Yes"
viewerProtocolPolicy:
Type: String
AllowedValues:
- allow-all
- https-only
- redirect-to-https
Default: redirect-to-https
cachePolicy:
Type: String
AllowedValues:
- CachingDisabled
- CachingOptimized
- CachingOptimizedForUncompressedObjects
- UseOriginCacheControlHeaders
Default: CachingDisabled
responseHeaderPolicy:
Type: String
AllowedValues:
- SecurityHeadersPolicy
- CORS-and-SecurityHeadersPolicy
- CORS-With-Preflight
- CORS-with-preflight-and-SecurityHeadersPolicy
- SimpleCORS
Default: SecurityHeadersPolicy
Conditions:
hasIPv6: !Equals [!Ref enableIPv6, "Yes"]
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: !Sub ${AWS::StackName}
- Key: StackId
Value: !Sub ${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: !Sub ${AWS::StackName}
- Key: StackId
Value: !Sub ${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 CloudFront"
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]
Runtime: !Ref pythonRuntime
Timeout: 25
Architectures:
- !Ref cpuArchitecture
Code: # https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-develop-integrations-lambda.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']
url = event['requestContext']['http']['path']
if url.lower() == '/favicon.ico':
return {
'statusCode': 404,
'body': 'Not Found!',
"headers": {
"content-type": "text/html"
}
}
elif url.lower() == '/robots.txt':
return {
'statusCode': 200,
'body' : 'User-agent: *\nDisallow: /',
"headers": {
"content-type": "text/plain"
}
}
elif url.lower() == '/createdate':
return {
'statusCode': 200,
'body' : createDate,
"headers": {
"content-type": "text/plain"
}
}
elif url.lower() == '/synctoken':
return {
'statusCode': 200,
'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 != '':
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')
return {
'statusCode': 200,
'body': '\n'.join(aws_ranges),
"headers": {
"content-type": "text/plain",
"path" : url,
"syncToken": ipranges_json['syncToken'],
"createDate": ipranges_json['createDate']
}
}
else:
return {
'statusCode': 404,
'body': 'Not AWS IP address',
"headers": {
"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['requestContext']['http']['sourceIp']
print(f'Source IP:{sourceIp}, Path:{url}, IPv4 Prefixes:{len(ipv4_prefixes)}, IPv6 Prefixes:{len(ipv6_prefixes)}, createDate:{createDate}, syncToken:{syncToken}')
return {
'statusCode': 200,
'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: !Sub ${AWS::StackName}
- Key: StackId
Value: !Sub ${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
lambdaFunctionUrl:
Type: "AWS::Lambda::Url"
DependsOn: lambdaFunction
Properties:
AuthType: AWS_IAM
TargetFunctionArn: !GetAtt lambdaFunction.Arn
lambdaFunctionUrlPermission:
Type: "AWS::Lambda::Permission"
Properties:
FunctionName: !Sub
- "${AWS::StackName}-lambdaFunction-${UID}"
- UID:
!Select [
3,
!Split ["-", !Select [2, !Split ["/", !Ref AWS::StackId]]],
]
Action: "lambda:InvokeFunctionUrl"
SourceArn: !Sub arn:${AWS::Partition}:cloudfront::${AWS::AccountId}:distribution/${cloudFrontDistribution.Id}
Principal: "cloudfront.amazonaws.com"
cloudFrontOriginAccessControl:
Type: "AWS::CloudFront::OriginAccessControl"
Properties:
OriginAccessControlConfig:
Name: !Sub
- "${AWS::StackName}-cloudFrontOriginAccessControl-${UID}"
- UID:
!Select [
3,
!Split ["-", !Select [2, !Split ["/", !Ref AWS::StackId]]],
]
SigningBehavior: "always"
Description: !Sub
- "OAC for ${AWS::StackName}-lambdaFunction-${UID}"
- UID:
!Select [
3,
!Split ["-", !Select [2, !Split ["/", !Ref AWS::StackId]]],
]
SigningProtocol: "sigv4"
OriginAccessControlOriginType: "lambda"
cloudFrontDistribution:
Type: "AWS::CloudFront::Distribution"
Properties:
DistributionConfig:
Origins:
- OriginAccessControlId: !Ref cloudFrontOriginAccessControl
CustomOriginConfig:
OriginSSLProtocols:
- "TLSv1.2"
OriginProtocolPolicy: "https-only"
DomainName:
!Select [2, !Split ["/", !GetAtt lambdaFunctionUrl.FunctionUrl]]
Id: !Sub
- "${AWS::StackName}-lambdaFunction-${UID}"
- UID:
!Select [
3,
!Split ["-", !Select [2, !Split ["/", !Ref AWS::StackId]]],
]
DefaultCacheBehavior:
Compress: true
TargetOriginId: !Sub
- "${AWS::StackName}-lambdaFunction-${UID}"
- UID:
!Select [
3,
!Split ["-", !Select [2, !Split ["/", !Ref AWS::StackId]]],
]
ViewerProtocolPolicy: !Ref viewerProtocolPolicy
CachePolicyId:
!FindInMap [cachePolicyMapping, !Ref cachePolicy, Value]
ResponseHeadersPolicyId:
!FindInMap [
responseHeaderPolicyMapping,
!Ref responseHeaderPolicy,
Value,
]
OriginRequestPolicyId: "b689b0a8-53d0-40ab-baf2-68738e2966ac" # https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/using-managed-origin-request-policies.html
AllowedMethods:
- "HEAD"
- "GET"
CachedMethods:
- "HEAD"
- "GET"
HttpVersion: "http2and3"
Enabled: true
IPV6Enabled: !If [hasIPv6, true, false]
Comment: !Sub
- "CloudFront distribution for ${AWS::StackName}-lambdaFunction-${UID}"
- UID:
!Select [
3,
!Split ["-", !Select [2, !Split ["/", !Ref AWS::StackId]]],
]
Tags:
- Key: StackName
Value: !Sub ${AWS::StackName}
- Key: StackId
Value: !Sub ${AWS::StackId}
Outputs:
cloudFrontURL:
Description: CloudFront distribution URL
Value: !Sub "https://${cloudFrontDistribution.DomainName}"
cloudFrontConsole:
Description: CloudFront console
Value: !Sub "https://console.aws.amazon.com/cloudfront/home#/distributions/${cloudFrontDistribution.Id}"
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]]],
]