-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathsftp.cfndsl.rb
667 lines (586 loc) · 19.7 KB
/
sftp.cfndsl.rb
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
CloudFormation do
Condition(:TransferServerEnabled, FnEquals(Ref(:EnableTransferServer), 'true'))
Condition(:IfDns, FnAnd([
FnNot(FnEquals(Ref(:DnsDomain), '')),
Condition(:TransferServerEnabled)
]))
if identity_provider.upcase == 'API_GATEWAY' && dynamic_users
Condition(:s3Message, FnNot(FnEquals(Ref(:S3Message), '')))
end
default_tags = []
default_tags << { Key: "Environment", Value: Ref("EnvironmentName") }
default_tags << { Key: "EnvironmentType", Value: Ref("EnvironmentType") }
tags = external_parameters.fetch(:tags, {})
tags.each do |key, value|
default_tags << { Key: key, Value: value }
end
# Create the resources required for the apigateway identity provider
if identity_provider.upcase == 'API_GATEWAY'
ApiGateway_RestApi(:CustomIdentityProviderApi) {
Name FnSub("${EnvironmentName}-sftp-custom-identity-provider")
FailOnWarnings true
EndpointConfiguration({
Types: ['REGIONAL']
})
}
IAM_Role(:TransferIdentityProviderRole) {
AssumeRolePolicyDocument service_role_assume_policy('transfer')
Path '/'
Policies ([
PolicyName: 'transfer-identity',
PolicyDocument: {
Statement: [
{
Effect: "Allow",
Action: [
"apigateway:GET"
],
Resource: "*"
},
{
Effect: "Allow",
Action: [
"execute-api:Invoke"
],
Resource: FnSub("arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${CustomIdentityProviderApi}/${EnvironmentName}/GET/*")
}
]
}])
}
IAM_Role(:ApiGatewayLoggingRole) {
AssumeRolePolicyDocument service_role_assume_policy('apigateway')
Path '/'
Policies ([
PolicyName: 'logging',
PolicyDocument: {
Statement: [
{
Effect: "Allow",
Action: [
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:DescribeLogGroups",
"logs:DescribeLogStreams",
"logs:PutLogEvents",
"logs:GetLogEvents",
"logs:FilterLogEvents"
],
Resource: "*"
}
]
}])
}
ApiGateway_Account(:ApiLoggingAccount) {
CloudWatchRoleArn FnGetAtt(:ApiGatewayLoggingRole, :Arn)
}
Logs_LogGroup(:ApiAccessLogGroup) {
LogGroupName FnSub("/#{server_name}/${EnvironmentName}/ApiAccess")
RetentionInDays 14
}
ApiGateway_Stage(:ApiStage) {
StageName Ref('EnvironmentName')
DeploymentId Ref(:ApiDeployment)
MethodSettings([
{
DataTraceEnabled: true,
HttpMethod: "*",
LoggingLevel: 'INFO',
ResourcePath: "/*"
}
])
RestApiId Ref(:CustomIdentityProviderApi)
AccessLogSetting({
DestinationArn: FnGetAtt(:ApiAccessLogGroup, :Arn),
Format: { "requestId":"$context.requestId",
ip: "$context.identity.sourceIp",
caller: "$context.identity.caller",
user: "$context.identity.user",
requestTime: "$context.requestTime",
httpMethod: "$context.httpMethod",
resourcePath: "$context.resourcePath",
status: "$context.status",
protocol: "$context.protocol",
responseLength: "$context.responseLength"
}.to_json
})
}
ApiGateway_Deployment(:ApiDeployment) {
DependsOn ["GetUserConfigRequest"]
RestApiId Ref('CustomIdentityProviderApi')
StageName FnSub('${EnvironmentName}-deployment')
}
Lambda_Permission(:SftpIdentityProviderLambdaPermission) {
Action 'lambda:invokeFunction'
FunctionName Ref('SftpIdentityProvider')
Principal 'apigateway.amazonaws.com'
SourceArn FnSub("arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${CustomIdentityProviderApi}/*")
}
ApiGateway_Resource(:ServersResource) {
RestApiId Ref(:CustomIdentityProviderApi)
ParentId FnGetAtt(:CustomIdentityProviderApi, :RootResourceId)
PathPart 'servers'
}
ApiGateway_Resource(:ServerIdResource) {
RestApiId Ref(:CustomIdentityProviderApi)
ParentId Ref(:ServersResource)
PathPart "{serverId}"
}
ApiGateway_Resource(:UsersResource) {
RestApiId Ref(:CustomIdentityProviderApi)
ParentId Ref(:ServerIdResource)
PathPart 'users'
}
ApiGateway_Resource(:UserNameResource) {
RestApiId Ref(:CustomIdentityProviderApi)
ParentId Ref(:UsersResource)
PathPart "{username}"
}
ApiGateway_Resource(:GetUserConfigResource) {
RestApiId Ref(:CustomIdentityProviderApi)
ParentId Ref(:UserNameResource)
PathPart "config"
}
ApiGateway_Method(:GetUserConfigRequest) {
AuthorizationType 'AWS_IAM'
HttpMethod 'GET'
Integration({
Type: 'AWS',
IntegrationHttpMethod: 'POST',
Uri: FnJoin('',['arn:aws:apigateway:', Ref('AWS::Region'), ':lambda:path/2015-03-31/functions/', FnGetAtt(:SftpIdentityProvider, :Arn), '/invocations']),
IntegrationResponses: [
{ StatusCode: 200 }
],
RequestTemplates: {
"application/json": {
username: "$input.params('username')",
password: "$input.params('Password')",
serverId: "$input.params('serverId')"
}.to_json
}
})
RequestParameters({
"method.request.header.Password": false
})
ResourceId Ref(:GetUserConfigResource)
RestApiId Ref(:CustomIdentityProviderApi)
MethodResponses([{
StatusCode: 200,
ResponseModels: {
"application/json": Ref(:GetUserConfigResponseModel)
}
}])
}
ApiGateway_Model(:GetUserConfigResponseModel) {
Description "API response for GetUserConfig"
RestApiId Ref(:CustomIdentityProviderApi)
ContentType "application/json"
Schema({
"$schema": "http://json-schema.org/draft-04/schema#",
title: "UserUserConfig",
type: "object",
properties: {
HomeDirectory: { type: "string" },
Role: { type: "string" },
Policy: { type: "string" },
PublicKeys: {
type: "array",
items:{ type: "string" }
}
}
})
}
if dynamic_users
SNS_Topic(:CreateDynamicSftpUserTopic) {
Subscription([{
Protocol: 'lambda',
Endpoint: FnGetAtt(:CreateDynamicSftpUser, :Arn)
}])
}
Output(:CreateDynamicSftpUserTopic) {
Value Ref(:CreateDynamicSftpUserTopic)
Export FnSub("${EnvironmentName}-#{external_parameters[:component_name]}-create-user-topic")
}
SNS_Topic(:DynamicSftpUserCreatedTopic)
Output(:DynamicSftpUserCreatedTopic) {
Value Ref(:DynamicSftpUserCreatedTopic)
Export FnSub("${EnvironmentName}-#{external_parameters[:component_name]}-user-created-topic")
}
Lambda_Permission(:CreateDynamicSftpUserLambdaPermission) {
FunctionName FnGetAtt(:CreateDynamicSftpUser, :Arn)
Action 'lambda:InvokeFunction'
Principal 'sns.amazonaws.com'
SourceArn Ref(:CreateDynamicSftpUserTopic)
}
Events_Rule(:CleanupUsersDailySchedule) {
ScheduleExpression 'rate(1 day)'
Targets([{
Arn: FnGetAtt(:CleanupDynamicSftpUsers, :Arn),
Id: 'cleanup-dyanmic-sftp-users-lambda'
}])
}
Lambda_Permission(:CleanupDynamicSftpUsersLambdaPermission) {
FunctionName FnGetAtt(:CleanupDynamicSftpUsers, :Arn)
Action 'lambda:InvokeFunction'
Principal 'events.amazonaws.com'
SourceArn FnGetAtt(:CleanupUsersDailySchedule, :Arn)
}
end
end
if endpoint.upcase == 'VPC_ENDPOINT' || endpoint.upcase == 'VPC'
ingress = []
ip_whitelisting.each do |wl|
rule = {
Description: FnSub(wl['desc']),
FromPort: 22,
IpProtocol: 'TCP',
ToPort: 22
}
if wl.has_key?('prefix')
rule[:SourcePrefixListId] = wl['prefix']
elsif wl.has_key?('group')
rule[:SourceSecurityGroupId] = wl['group']
else
rule[:CidrIp] = FnSub(wl['ip'])
end
ingress << rule
end if ip_whitelisting.any?
sg_tags = default_tags.map(&:clone)
sg_tags << { Key: "Name", Value: FnSub("#{server_name}-${EnvironmentName}-sftp-access") }
EC2_SecurityGroup(:SftpSecurityGroup) {
VpcId Ref(:VpcId)
GroupDescription FnSub("Controll sftp access to the #{server_name}-${EnvironmentName} aws transfer server vpc endpoint")
SecurityGroupIngress ingress if ingress.any?
Tags sg_tags
Metadata({
cfn_nag: {
rules_to_suppress: [
{ id: 'F1000', reason: 'adding rules using cfn resources' }
]
}
})
}
end
if endpoint.upcase == 'VPC_ENDPOINT'
EC2_VPCEndpoint(:SftpVpcEndpoint) {
VpcId Ref(:VpcId)
ServiceName FnSub("com.amazonaws.${AWS::Region}.transfer.server")
VpcEndpointType "Interface"
PrivateDnsEnabled true
SubnetIds Ref(:SubnetIds)
SecurityGroupIds [
Ref(:SftpSecurityGroup)
]
}
if output_vpc_endpoint_ips
Resource(:GetVpcEndpointIPs) {
Type 'Custom::SftpServer'
Property 'ServiceToken', FnGetAtt(:GetVpcEndpointIPsCR, :Arn)
Property 'NetworkInterfaceIds', FnGetAtt(:SftpVpcEndpoint, :NetworkInterfaceIds)
}
Output(:VpcEndpointIPs) { Value(FnGetAtt(:GetVpcEndpointIPs, :VpcEndpointIPs)) }
end
if apigateway_endpoint.upcase == 'VPC_ENDPOINT' and identity_provider.upcase == 'API_GATEWAY'
api_sg_tags = default_tags.map(&:clone)
api_sg_tags << { Key: "Name", Value: FnSub("${EnvironmentName}-api-gateway-sftp-identidy-provider") }
EC2_SecurityGroup(:ApiGatewaySecurityGroup) {
VpcId Ref(:VpcId)
GroupDescription FnSub("Controll https access to the ${EnvironmentName} api gateway sftp identity provider vpc endpoint")
SecurityGroupIngress [{
SourceSecurityGroupId: Ref(:SftpSecurityGroup),
Description: "SFTP VPC Endpoint Security Group Id",
FromPort: 443,
IpProtocol: 'TCP',
ToPort: 443
}]
Tags api_sg_tags
Metadata({
cfn_nag: {
rules_to_suppress: [
{ id: 'F1000', reason: 'adding rules using cfn resources' }
]
}
})
}
EC2_VPCEndpoint(:ApiGatewayVpcEndpoint) {
VpcId Ref(:VpcId)
ServiceName FnSub("com.amazonaws.${AWS::Region}.apigateway")
VpcEndpointType "Interface"
PrivateDnsEnabled true
SubnetIds Ref(:SubnetIds)
SecurityGroupIds [
Ref(:ApiGatewaySecurityGroup)
]
}
end
elsif endpoint.upcase == 'VPC' && vpc_public == true
Condition(:CreateEIPs, FnEquals(FnJoin("", Ref(:EIPs)), ""))
eip_refs = []
external_parameters[:max_availability_zones].times do |az|
get_az = { AZ: FnSelect(az, FnGetAZs(Ref('AWS::Region'))) }
matches = ((az+1)..external_parameters[:max_availability_zones]).to_a
Condition("CreateEIP#{az}",
if matches.length == 1
FnAnd([
FnEquals(Ref(:AvailabilityZones), external_parameters[:max_availability_zones]),
Condition(:CreateEIPs)
])
else
FnAnd([
FnOr(matches.map { |i| FnEquals(Ref(:AvailabilityZones), i) }),
Condition(:CreateEIPs)
])
end
)
EC2_EIP("SftpEIP#{az}") {
Condition "CreateEIP#{az}"
Domain 'vpc'
Tags [{Key: 'Name', Value: FnSub("${EnvironmentName}-sftp-${AZ}", get_az) }]
}
eip_refs.push(FnGetAtt("SftpEIP#{az}", :AllocationId))
end
eip_condition = ''
external_parameters[:max_availability_zones].times do |az|
eip_condition = FnIf("CreateEIP#{az}", eip_refs[0..az], eip_condition)
end
end
IAM_Role(:SftpServerLoggingRole) {
AssumeRolePolicyDocument service_role_assume_policy('transfer')
Path '/'
Policies ([
PolicyName: 'logging',
PolicyDocument: {
Statement: [
{
Effect: "Allow",
Action: [
"logs:CreateLogStream",
"logs:DescribeLogStreams",
"logs:CreateLogGroup",
"logs:PutLogEvents"
],
Resource: "*"
}
]
}])
}
if identity_provider.upcase == 'API_GATEWAY' && dynamic_users
IAM_Policy(:LambdaRoleCreateDynamicSftpUserS3Policy) {
Condition(:s3Message)
PolicyDocument (
{
Statement: [
{
Effect: "Allow",
Action: [
"s3:GetObject"
],
Resource: "*"
}
]
})
PolicyName 's3get'
Roles [Ref('LambdaRoleCreateDynamicSftpUser')]
}
end
sftp_tags = default_tags.map(&:clone)
sftp_tags << { Key: "Name", Value: FnSub("#{server_name}-${EnvironmentName}") }
storage_type = external_parameters.fetch(:storage_type, nil)
Transfer_Server(:SftpServer) {
Condition(:TransferServerEnabled)
EndpointType endpoint.upcase
if endpoint.upcase == 'VPC_ENDPOINT'
EndpointDetails({
VpcEndpointId: Ref(:SftpVpcEndpoint)
})
elsif endpoint.upcase == 'VPC'
endpoint_details = {
SecurityGroupIds: [
Ref(:SftpSecurityGroup)
],
SubnetIds: Ref(:SubnetIds),
VpcId: Ref(:VpcId)
}
if vpc_public == true
endpoint_details[:AddressAllocationIds] = FnIf(:CreateEIPs, eip_condition, Ref(:EIPs))
end
EndpointDetails(endpoint_details)
end
IdentityProviderType identity_provider.upcase
if identity_provider.upcase == 'API_GATEWAY'
IdentityProviderDetails({
InvocationRole: FnGetAtt(:TransferIdentityProviderRole, :Arn),
Url: FnSub("https://${CustomIdentityProviderApi}.execute-api.${AWS::Region}.amazonaws.com/${ApiStage}")
})
sftp_tags << { Key: 'IdentityProviderUrl', Value: FnSub("https://${CustomIdentityProviderApi}.execute-api.${AWS::Region}.amazonaws.com/${ApiStage}") }
end
LoggingRole FnGetAtt('SftpServerLoggingRole','Arn')
Tags sftp_tags
}
users = external_parameters.fetch(:users, [])
users.each do |user|
if !user['name'].match?(/^[a-zA-Z0-9_][a-zA-Z0-9_-]{2,31}$/)
raise "#{user['name']} is invalid, must comply with `^[a-zA-Z0-9_][a-zA-Z0-9_-]{2,31}$`"
end
user_tags = default_tags.map(&:clone)
user_tags << { Key: "Name", Value: "#{user['name']}" }
IAM_Role("#{user['name']}SftpAccessRole") {
AssumeRolePolicyDocument service_role_assume_policy('transfer')
Path '/'
Policies ([
PolicyName: "sftp-access-for-#{user['name']}",
PolicyDocument: {
Statement: [
{
Sid: "AllowListingOfUserFolder",
Effect: "Allow",
Action: [
"s3:ListBucket",
"s3:GetBucketLocation"
],
Resource: FnSub("arn:aws:s3:::#{user['bucket']}")
},
{
Sid: "HomeDirObjectAccess",
Effect: "Allow",
Action: [
"s3:PutObject",
"s3:GetObject",
"s3:DeleteObjectVersion",
"s3:DeleteObject",
"s3:GetObjectVersion"
],
Resource: FnSub("arn:aws:s3:::#{user['bucket']}/*")
}
]
}
])
}
user_policy = { Version: "2012-10-17", Statement: [] }
if user.has_key?('home') && user['home'] == '/'
user_policy[:Statement] << {
Sid: "AllowListingOfUserFolder",
Action: [ "s3:ListBucket" ],
Effect: "Allow",
Resource: [ "arn:aws:s3:::${!transfer:HomeBucket}" ]
}
else
user_policy[:Statement] << {
Sid: "AllowListingOfUserFolder",
Action: [ "s3:ListBucket" ],
Effect: "Allow",
Resource: [ "arn:aws:s3:::${!transfer:HomeBucket}" ],
Condition: {
StringLike: {
"s3:prefix" => [
"${!transfer:HomeFolder}/*",
"${!transfer:HomeFolder}"
]
}
}
}
end
user_policy[:Statement] << {
Sid: "AWSTransferRequirements",
Effect: "Allow",
Action: [
"s3:ListAllMyBuckets",
"s3:GetBucketLocation"
],
Resource: "*"
}
user_policy[:Statement] << {
Sid: "HomeDirObjectGetAccess",
Effect: "Allow",
Action: [
"s3:GetObject",
"s3:GetObjectVersion",
"s3:GetObjectACL"
],
Resource: "arn:aws:s3:::${!transfer:HomeDirectory}*"
}
if user.has_key? 'access' and user['access'].include? 'put'
user_policy[:Statement] << {
Sid: "HomeDirObjectPutAccess",
Effect: "Allow",
Action: [
"s3:PutObject",
"s3:PutObjectACL"
],
Resource: "arn:aws:s3:::${!transfer:HomeDirectory}*"
}
end
if user.has_key? 'access' and user['access'].include? 'delete'
user_policy[:Statement] << {
Sid: "HomeDirObjectDeleteAccess",
Effect: "Allow",
Action: [
"s3:DeleteObjectVersion",
"s3:DeleteObject"
],
Resource: "arn:aws:s3:::${!transfer:HomeDirectory}*"
}
end
unless user.has_key? 'access' and user['access'].include? 'mkdir'
user_policy[:Statement] << {
Sid: "HomeDirObjectDenyMkdirAccess",
Effect: "Deny",
Action: [
"s3:PutObject"
],
Resource: "arn:aws:s3:::${!transfer:HomeBucket}/*/"
}
end
if identity_provider.upcase == 'API_GATEWAY'
secret_string = { Role: "${Role}" }
secret_string[:HomeDirectory] = user.has_key?('home') ? "/#{user['bucket']}#{user['home']}" : "/#{user['bucket']}/home/#{user['name']}"
secret_string[:Policy] = user_policy.to_json
if user.has_key? 'keys' and user['keys'].any?
secret_string[:PublicKeys] = user['keys']
end
SecretsManager_Secret("#{user['name']}SftpUserSecret") {
Name FnSub("sftp/${EnvironmentName}/#{user['name']}")
Description FnSub("${EnvironmentName} sftp user deatils for #{user['name']}")
SecretString FnSub(secret_string.to_json, { Role: FnGetAtt("#{user['name']}SftpAccessRole", :Arn) })
}
else
home_directory = user.has_key?('home') ? "/#{user['bucket']}#{user['home']}" : "/#{user['bucket']}/home/#{user['name']}"
Transfer_User("#{user['name']}SftpUser") {
Condition(:TransferServerEnabled)
HomeDirectory FnSub(home_directory)
UserName user['name']
ServerId FnGetAtt(:SftpServer, :ServerId)
Role FnGetAtt("#{user['name']}SftpAccessRole", :Arn)
Policy FnSub(user_policy.to_json)
if user.has_key? 'keys' and user['keys'].any?
SshPublicKeys user['keys']
end
Tags user_tags
}
end
end
Route53_RecordSet(:SftpServerRecord) {
Condition('IfDns')
HostedZoneName FnSub("#{dns_format}.")
Name FnSub("#{server_name}.#{dns_format}.")
Type 'CNAME'
TTL '60'
Comment FnJoin("", [Ref('EnvironmentName') ," sftp server ", FnGetAtt(:SftpServer,:ServerId)])
ResourceRecords [ FnJoin('.',[ FnGetAtt(:SftpServer, :ServerId), 'server.transfer', Ref('AWS::Region'), 'amazonaws.com' ]) ]
}
Output(:SftpServerId) {
Value(
FnIf(:TransferServerEnabled,
FnGetAtt(:SftpServer, :ServerId),
""
)
)
}
Output(:SftpServerEndpoint) {
Value(
FnIf(:TransferServerEnabled,
FnJoin('.',[ FnGetAtt(:SftpServer, :ServerId), 'server.transfer', Ref('AWS::Region'), 'amazonaws.com' ]),
""
)
)
}
end