/
IoTPrivatelink.yaml
executable file
·559 lines (516 loc) · 16.6 KB
/
IoTPrivatelink.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
AWSTemplateFormatVersion: 2010-09-09
Description: An AWS cloudformation template for simple iot device simulator
Transform: 'AWS::Serverless-2016-10-31'
Parameters:
Environment:
Type: String
Default: dev
AvaibilityZone1:
Type: String
Default: us-east-1a
AvaibilityZone2:
Type: String
Default: us-east-1b
UserName:
Type: String
Default: developer
Var1:
Type: String
Default: ""
Var2:
Type: String
Default: ""
Mappings:
SubnetConfig:
VPCB:
CIDR: 10.0.0.0/16
SubnetB:
CIDR: 10.0.0.0/24
VPCA:
CIDR: 10.1.0.0/16
SubnetPublicA:
CIDR: 10.1.1.0/24
SubnetPrivateA:
CIDR: 10.1.2.0/24
EC2InstanceConfig:
InstanceType:
Experiment: t2.micro
ImageId:
Experiment: ami-0a8b4cd432b1c3063
Resources:
AccessKey:
Type: AWS::IAM::AccessKey
Properties:
UserName: !Sub ${UserName}
AccessKeySecret:
Type: AWS::SecretsManager::Secret
Properties:
Name: !Sub AccessKey-${Environment}
Description: IoT Privatelink Access Key
SecretString: !Sub '{"AccessKeyId":"${AccessKey}","SecretAccessKey":"${AccessKey.SecretAccessKey}"}'
KmsKey:
Type: AWS::KMS::Key
Properties:
Description: CDF encryption key
EnableKeyRotation: true
KeyPolicy:
Version: "2012-10-17"
Id: key-default-1
Statement:
- Sid: Enable IAM User Permissions
Effect: Allow
Principal:
AWS:
- !Sub "arn:aws:iam::${AWS::AccountId}:root"
- !Sub "arn:aws:iam::${AWS::AccountId}:user/${UserName}"
Action:
- kms:*
Resource: "*"
KeyPair:
Type: 'AWS::EC2::KeyPair'
Properties:
KeyName: EC2KeyPair
VPCA:
Type: AWS::EC2::VPC
Properties:
EnableDnsHostnames: true
EnableDnsSupport: true
CidrBlock:
Fn::FindInMap:
- SubnetConfig
- VPCA
- CIDR
SubnetPublicA:
Type: AWS::EC2::Subnet
Properties:
VpcId: !Ref VPCA
CidrBlock:
Fn::FindInMap:
- SubnetConfig
- SubnetPublicA
- CIDR
MapPublicIpOnLaunch: true
AvailabilityZone: !Sub ${AvaibilityZone1}
SubnetPrivateA:
Type: AWS::EC2::Subnet
Properties:
VpcId: !Ref VPCA
CidrBlock:
Fn::FindInMap:
- SubnetConfig
- SubnetPrivateA
- CIDR
MapPublicIpOnLaunch: false
AvailabilityZone: !Sub ${AvaibilityZone2}
InternetGatewayA:
Type: AWS::EC2::InternetGateway
VPCGatewayAttachmentA:
Type: AWS::EC2::VPCGatewayAttachment
Properties:
VpcId: !Ref VPCA
InternetGatewayId: !Ref InternetGatewayA
RouteTablePublicA:
Type: AWS::EC2::RouteTable
Properties:
VpcId: !Ref VPCA
PublicInternetRouteA:
Type: AWS::EC2::Route
DependsOn: VPCGatewayAttachmentA
Properties:
DestinationCidrBlock: 0.0.0.0/0
GatewayId: !Ref InternetGatewayA
RouteTableId: !Ref RouteTablePublicA
PublicSubnetRouteTableAssociationA:
Type: AWS::EC2::SubnetRouteTableAssociation
Properties:
RouteTableId: !Ref RouteTablePublicA
SubnetId: !Ref SubnetPublicA
## NAT GATEWAY
NatGatewayA:
Type: AWS::EC2::NatGateway
DependsOn: NatPublicIPA
Properties:
SubnetId: !Ref SubnetPublicA
AllocationId: !GetAtt NatPublicIPA.AllocationId
## ELASTIC IP
NatPublicIPA:
Type: AWS::EC2::EIP
DependsOn: VPCA
Properties:
Domain: vpc
## PRIVATE ROUTING
RouteTablePrivateA:
Type: AWS::EC2::RouteTable
Properties:
VpcId: !Ref VPCA
PrivateRouteA:
Type: AWS::EC2::Route
Properties:
NatGatewayId: !Ref NatGatewayA
RouteTableId: !Ref RouteTablePrivateA
DestinationCidrBlock: 0.0.0.0/0
PrivateSubnetRouteTableAssociationA:
Type: AWS::EC2::SubnetRouteTableAssociation
Properties:
SubnetId: !Ref SubnetPrivateA
RouteTableId: !Ref RouteTablePrivateA
IOTSimA:
Type: AWS::EC2::Instance
Properties:
InstanceType:
Fn::FindInMap:
- EC2InstanceConfig
- InstanceType
- Experiment
ImageId:
Fn::FindInMap:
- EC2InstanceConfig
- ImageId
- Experiment
KeyName: !Ref KeyPair
SubnetId: !Ref SubnetPublicA
SecurityGroupIds:
- Ref: SecurityGroupA
Tags:
- Key: Name
Value: IOT-Sim-A
UserData:
Fn::Base64: !Sub |
#!/bin/bash -ex
sudo yum update -y
sudo yum install git -y
sudo yum install jq -y
curl -sL https://rpm.nodesource.com/setup_16.x | sudo bash -
sudo yum install -y nodejs
aws configure set aws_access_key_id ${AccessKey}
aws configure set aws_secret_access_key ${AccessKey.SecretAccessKey}
aws configure set default.region ${AWS::Region}
aws iot create-thing --thing-name "MyIotThingA"
mkdir ~/certs
sudo su
curl -o ~/certs/Amazon-root-CA-1.pem https://www.amazontrust.com/repository/AmazonRootCA1.pem
Var1=$(aws iot create-keys-and-certificate --set-as-active --certificate-pem-outfile "~/certs/device.pem.crt" --public-key-outfile "~/certs/public.pem.key" --private-key-outfile "~/certs/private.pem.key")
Certificate_Arn=$( jq -r '.certificateArn' <<< $Var1 )
aws iot attach-thing-principal --thing-name "MyIotThingA" --principal $Certificate_Arn
aws iot attach-policy --policy-name ${IoTPolicy} --target $Certificate_Arn
cd ~
git clone https://github.com/aws/aws-iot-device-sdk-js-v2.git
cd aws-iot-device-sdk-js-v2
npm install
cd ~/aws-iot-device-sdk-js-v2/samples/node/pub_sub
npm install
Var2=$(aws iot describe-endpoint --endpoint-type iot:Data-ATS)
Endpoint_Address=$( jq -r '.endpointAddress' <<< $Var2 )
node dist/index.js --topic topic_A --root-ca ~/certs/Amazon-root-CA-1.pem --cert ~/certs/device.pem.crt --key ~/certs/private.pem.key --endpoint $Endpoint_Address
SecurityGroupA:
Type: AWS::EC2::SecurityGroup
Properties:
GroupDescription: "Allow SSH traffic in, all trafic out"
VpcId: !Ref VPCA
# The incoming traffic
SecurityGroupIngress:
- IpProtocol: tcp
FromPort: '22'
ToPort: '22'
# The range of ip address to allow traffic from
CidrIp: 0.0.0.0/0
- IpProtocol: tcp
FromPort: '80'
ToPort: '80'
# The range of ip address to allow traffic from
CidrIp: 0.0.0.0/0
- IpProtocol: tcp
FromPort: '443'
ToPort: '443'
# The range of ip address to allow traffic from
CidrIp: 0.0.0.0/0
- IpProtocol: tcp
FromPort: '8883'
ToPort: '8883'
# The range of ip address to allow traffic from
CidrIp: 0.0.0.0/0
IOTInterfaceEndpoint:
Type: 'AWS::EC2::VPCEndpoint'
Properties:
VpcEndpointType: Interface
ServiceName: !Sub 'com.amazonaws.${AWS::Region}.iot.data'
VpcId: !Ref VPCA
SubnetIds:
- !Ref SubnetPrivateA
SecurityGroupIds:
- !Ref SecurityGroupA
IOTPrivateHostedZone:
Type: "AWS::Route53::HostedZone"
Properties:
HostedZoneConfig:
Comment: 'IOT data private hosted zone'
Name: !Sub 'iot.${AWS::Region}.amazonaws.com'
VPCs:
- VPCId: !Ref VPCA
VPCRegion: !Ref 'AWS::Region'
IOTEndpointRecord:
Type: AWS::Route53::RecordSet
Properties:
HostedZoneId: !Ref IOTPrivateHostedZone
Comment: CNAME record for IOT endpoints
Name: !GetAtt IotEndpoint.IotEndpointAddress
Type: CNAME
TTL: '5'
SetIdentifier: Frontend One
Weight: '4'
ResourceRecords:
- Fn::Select: [1, {Fn::Split: [":", {Fn::Select: [0, {Fn::GetAtt: [IOTInterfaceEndpoint, DnsEntries]}]}]}]
IoTPolicy:
Type: 'AWS::IoT::Policy'
Properties:
PolicyName: !Sub IotPrivateLinkThingPolicy-${Environment}
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action:
- 'iot:Publish'
- 'iot:Subscribe'
- 'iot:Receive'
- 'iot:Connect'
Resource: '*'
VPCB:
Type: AWS::EC2::VPC
Properties:
EnableDnsHostnames: true
EnableDnsSupport: true
CidrBlock:
Fn::FindInMap:
- SubnetConfig
- VPCB
- CIDR
SubnetB:
Type: AWS::EC2::Subnet
Properties:
VpcId: !Ref VPCB
CidrBlock:
Fn::FindInMap:
- SubnetConfig
- SubnetB
- CIDR
MapPublicIpOnLaunch: true
AvailabilityZone: !Sub ${AvaibilityZone1}
InternetGatewayB:
Type: AWS::EC2::InternetGateway
VPCGatewayAttachmentB:
Type: AWS::EC2::VPCGatewayAttachment
Properties:
VpcId: !Ref VPCB
InternetGatewayId: !Ref InternetGatewayB
RouteTableB:
Type: AWS::EC2::RouteTable
Properties:
VpcId: !Ref VPCB
InternetRouteB:
Type: AWS::EC2::Route
DependsOn: VPCGatewayAttachmentB
Properties:
DestinationCidrBlock: 0.0.0.0/0
GatewayId: !Ref InternetGatewayB
RouteTableId: !Ref RouteTableB
SubnetRouteTableAssociationB:
Type: AWS::EC2::SubnetRouteTableAssociation
Properties:
RouteTableId: !Ref RouteTableB
SubnetId: !Ref SubnetB
SecurityGroupB:
Type: AWS::EC2::SecurityGroup
Properties:
GroupDescription: "Allow SSH traffic in, all trafic out"
VpcId: !Ref VPCB
# The incoming traffic
SecurityGroupIngress:
- IpProtocol: tcp
FromPort: '22'
ToPort: '22'
# The range of ip address to allow traffic from
CidrIp: 0.0.0.0/0
IOTSimB:
Type: AWS::EC2::Instance
Properties:
InstanceType:
Fn::FindInMap:
- EC2InstanceConfig
- InstanceType
- Experiment
ImageId:
Fn::FindInMap:
- EC2InstanceConfig
- ImageId
- Experiment
KeyName: !Ref KeyPair
SubnetId: !Ref SubnetB
SecurityGroupIds:
- Ref: SecurityGroupB
Tags:
- Key: Name
Value: IOT-Sim-B
UserData:
Fn::Base64: !Sub |
#!/bin/bash -ex
sudo yum update -y
sudo yum install git -y
sudo yum install jq -y
curl -sL https://rpm.nodesource.com/setup_16.x | sudo bash -
sudo yum install -y nodejs
aws configure set aws_access_key_id ${AccessKey}
aws configure set aws_secret_access_key ${AccessKey.SecretAccessKey}
aws configure set default.region ${AWS::Region}
aws iot create-thing --thing-name "MyIotThingB"
mkdir ~/certs
sudo su
curl -o ~/certs/Amazon-root-CA-1.pem https://www.amazontrust.com/repository/AmazonRootCA1.pem
Var1=$(aws iot create-keys-and-certificate --set-as-active --certificate-pem-outfile "~/certs/device.pem.crt" --public-key-outfile "~/certs/public.pem.key" --private-key-outfile "~/certs/private.pem.key")
Certificate_Arn=$( jq -r '.certificateArn' <<< $Var1 )
aws iot attach-thing-principal --thing-name "MyIotThingB" --principal $Certificate_Arn
aws iot attach-policy --policy-name ${IoTPolicy} --target $Certificate_Arn
cd ~
git clone https://github.com/aws/aws-iot-device-sdk-js-v2.git
cd aws-iot-device-sdk-js-v2
npm install
cd ~/aws-iot-device-sdk-js-v2/samples/node/pub_sub
npm install
Var2=$(aws iot describe-endpoint --endpoint-type iot:Data-ATS)
Endpoint_Address=$( jq -r '.endpointAddress' <<< $Var2 )
node dist/index.js --topic topic_B --root-ca ~/certs/Amazon-root-CA-1.pem --cert ~/certs/device.pem.crt --key ~/certs/private.pem.key --endpoint $Endpoint_Address
IoTEC2Role:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service:
- ec2.amazonaws.com
Action: sts:AssumeRole
Policies:
- PolicyName: aws-iot-access
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: "Allow"
Action:
- "iot:*"
Resource:
- "*"
EC2InstanceProfile:
Type: AWS::IAM::InstanceProfile
Properties:
Path: "/"
Roles:
- !Ref IoTEC2Role
InstanceProfileName: !Sub EC2InstanceProfile-${Environment}
LambdaExecutionRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service:
- lambda.amazonaws.com
Action:
- sts:AssumeRole
Path: "/"
Policies:
- PolicyName: root
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- iot:DescribeEndpoint
Resource:
- '*'
IotEndpointProvider:
Type: AWS::Lambda::Function
Properties:
FunctionName: IotEndpointProvider
Handler: index.handler
Runtime: nodejs16.x
MemorySize: 128
Timeout: 5
Role: !GetAtt LambdaExecutionRole.Arn
Code:
ZipFile: !Sub |
var aws = require("aws-sdk");
exports.handler = function(event, context) {
console.log("REQUEST RECEIVED:\n" + JSON.stringify(event));
// For Delete requests, immediately send a SUCCESS response.
if (event.RequestType == "Delete") {
sendResponse(event, context, "SUCCESS");
return;
}
const iot = new aws.Iot();
iot.describeEndpoint({}, (err, data) => {
let responseData, responseStatus;
if (err) {
responseStatus = "FAILED";
responseData = { Error: "describeEndpoint call failed" };
console.log(responseData.Error + ":\n", err);
} else {
responseStatus = "SUCCESS";
responseData = { IotEndpointAddress: data.endpointAddress };
console.log('response data: ' + JSON.stringify(responseData));
}
sendResponse(event, context, responseStatus, responseData);
});
};
// Send response to the pre-signed S3 URL
function sendResponse(event, context, responseStatus, responseData) {
var responseBody = JSON.stringify({
Status: responseStatus,
Reason: "See the details in CloudWatch Log Stream: " + context.logStreamName,
PhysicalResourceId: context.logStreamName,
StackId: event.StackId,
RequestId: event.RequestId,
LogicalResourceId: event.LogicalResourceId,
Data: responseData
});
console.log("RESPONSE BODY:\n", responseBody);
var https = require("https");
var url = require("url");
var parsedUrl = url.parse(event.ResponseURL);
var options = {
hostname: parsedUrl.hostname,
port: 443,
path: parsedUrl.path,
method: "PUT",
headers: {
"content-type": "",
"content-length": responseBody.length
}
};
console.log("SENDING RESPONSE...\n");
var request = https.request(options, function(response) {
console.log("STATUS: " + response.statusCode);
console.log("HEADERS: " + JSON.stringify(response.headers));
// Tell AWS Lambda that the function execution is done
context.done();
});
request.on("error", function(error) {
console.log("sendResponse Error:" + error);
// Tell AWS Lambda that the function execution is done
context.done();
});
// write data to request body
request.write(responseBody);
request.end();
}
IotEndpoint:
Type: 'Custom::IotEndpoint'
DependsOn: IotEndpointProvider
Properties:
ServiceToken: !GetAtt IotEndpointProvider.Arn
Outputs:
IotEndpointAddress:
Value: !GetAtt IotEndpoint.IotEndpointAddress
Export:
Name: IotEndpointAddress