-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathglobal.yaml
520 lines (490 loc) · 17.9 KB
/
global.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
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: AWS CloudFormation template for Gateflag global config (gateway, networking, IAM, key rotator) deployment.
Parameters:
EnvironmentName:
Type: String
Default: Gateflag
Description: A friendly environment name that will be used for namespacing all cluster resources.
FlagServerHost:
Type: String
Default: https://flaggy.free.beeceptor.com
Description: The URL of host server that will emit the CTF flag upon request.
CTFTickDuration:
Type: Number
Description: Minute definition of a 'tick' on the CTF competition.
Default: 5
MinValue: 1
MaxValue: 59
Resources:
# API Gateway Establishment.
RestApi:
Type: AWS::ApiGateway::RestApi
Properties:
Name: !Ref EnvironmentName
FailOnWarnings: 'true'
EndpointConfiguration:
Types:
- PRIVATE
Policy: !Sub |
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Deny",
"Principal": "*",
"Action": "execute-api:Invoke",
"Resource": "execute-api:/*/*/*",
"Condition": {
"StringNotEquals": {
"aws:sourceVpce": "${RestApiVpcEndpoint}"
}
}
},
{
"Effect": "Allow",
"Principal": "*",
"Action": "execute-api:Invoke",
"Resource": "execute-api:/*/*/*"
}
]
}
RestApiUserFlagResource:
Type: AWS::ApiGateway::Resource
Properties:
ParentId: !GetAtt RestApi.RootResourceId
RestApiId: !Ref RestApi
PathPart: user_flag
RestApiRootFlagResource:
Type: AWS::ApiGateway::Resource
Properties:
ParentId: !GetAtt RestApi.RootResourceId
RestApiId: !Ref RestApi
PathPart: root_flag
RestApiUserFlagMethod:
Type: AWS::ApiGateway::Method
Properties:
AuthorizationType: AWS_IAM
HttpMethod: GET
ResourceId: !Ref RestApiUserFlagResource
RestApiId: !Ref RestApi
Integration:
IntegrationHttpMethod: POST
Type: HTTP
Uri: !Sub ${FlagServerHost}/api/v1/flagserver/user_flag
IntegrationResponses:
- StatusCode: 200
RequestParameters:
integration.request.header.x-adce-secret: '__GATEFLAG_SECRET__'
integration.request.header.x-source-ip: context.identity.sourceIp
integration.request.header.x-user-arn: context.identity.userArn
MethodResponses:
- StatusCode: "200"
ResponseModels:
application/json: !Ref FlagModel
RestApiRootFlagMethod:
Type: AWS::ApiGateway::Method
Properties:
AuthorizationType: AWS_IAM
HttpMethod: GET
ResourceId: !Ref RestApiRootFlagResource
RestApiId: !Ref RestApi
Integration:
IntegrationHttpMethod: POST
Type: HTTP
Uri: !Sub ${FlagServerHost}/api/v1/flagserver/root_flag
IntegrationResponses:
- StatusCode: 200
RequestParameters:
integration.request.header.x-adce-secret: '__GATEFLAG_SECRET__'
integration.request.header.x-source-ip: context.identity.sourceIp
integration.request.header.x-user-arn: context.identity.userArn
MethodResponses:
- StatusCode: "200"
ResponseModels:
application/json: !Ref FlagModel
RestApiDeployment:
Type: AWS::ApiGateway::Deployment
DependsOn:
- RestApiUserFlagMethod
- RestApiRootFlagMethod
Properties:
RestApiId: !Ref RestApi
Description: Deployment of Gateflag.
RestApiStage:
Type: AWS::ApiGateway::Stage
Properties:
StageName: stable
RestApiId: !Ref RestApi
DeploymentId: !Ref RestApiDeployment
Description: Stage marked as stable for Gateflag deployment.
FlagModel:
Type: AWS::ApiGateway::Model
Properties:
ContentType: application/json
Name: FlagModel
RestApiId: !Ref RestApi
Schema:
"$schema": http://json-schema.org/draft-04/schema#
title: Flag
type: object
additionalProperties: false
properties:
status:
type: string
message:
type: string
data:
type: object
properties:
flag:
type: string
type:
type: string
generated_at:
type: string
required:
- status
# Lambda & CloudWatch Establishment for Periodic Key Rotation
RotateIAMKeysLambda:
Type: 'AWS::Serverless::Function'
Properties:
FunctionName: __GATEFLAG__RotateIAMKeysLambda
Runtime: nodejs14.x
Handler: index.handler
Timeout: 60
Role: !GetAtt RotateIAMKeysLambdaRole.Arn
Policies:
- AWSLambdaBasicExecutionRole
- AWSLambdaIAMPolicy
CodeUri: .
InlineCode: |
const AWS = require('aws-sdk');
const iam = new AWS.IAM();
const ec2 = new AWS.EC2();
const ssm = new AWS.SSM();
async function updateCliConfiguration(instanceId, username, accessKey, secretKey) {
const result = await ssm.sendCommand({
InstanceIds: [instanceId],
DocumentName: "AWS-RunShellScript",
Parameters: {
commands: [
`su ${username} -c "echo '[default]' > ~/.aws/credentials"`,
`su ${username} -c "echo 'aws_access_key_id=${accessKey}' >> ~/.aws/credentials"`,
`su ${username} -c "echo 'aws_secret_access_key=${secretKey}' >> ~/.aws/credentials"`
],
},
}).promise();
console.log("Rotation command has been executed via SSM. Result: ", result);
}
exports.handler = async (event, context) => {
try {
const { Users } = await iam.listUsers().promise();
for (const user of Users) {
console.log(user);
const userTags = await iam.listUserTags({ UserName: user.UserName }).promise();
console.log(userTags);
if (!userTags.Tags.some(tag => tag.Key === 'ManagedBy' && tag.Value === '__GATEFLAG__')) {
console.log(`The user: ${user.UserName} is not managed by Gateflag and is skipped.`)
continue;
}
var gateflagSpecificName = userTags.Tags.find(item => item.Key === 'GateflagSpecificName');
gateflagSpecificName = gateflagSpecificName ? gateflagSpecificName.Value : undefined;
var boxLocalUser = userTags.Tags.find(item => item.Key === 'BoxLocalUserName');
boxLocalUser = boxLocalUser ? boxLocalUser.Value : undefined;
if (!gateflagSpecificName || !boxLocalUser) {
console.log(`Failed to get some box information from the tags. Skipping...`)
continue;
}
const { AccessKeyMetadata } = await iam.listAccessKeys({ UserName: user.UserName }).promise();
if (AccessKeyMetadata.length > 0) {
if (AccessKeyMetadata.length == 2) {
const currentAccessKeyId = AccessKeyMetadata[1].AccessKeyId;
await iam.deleteAccessKey({ UserName: user.UserName, AccessKeyId: currentAccessKeyId }).promise();
console.log(`There are already two access keys for user: ${user.UserName}. One of the access key has been deleted successfully.`);
}
const currentAccessKeyId = AccessKeyMetadata[0].AccessKeyId;
var newKey = await iam.createAccessKey({ UserName: user.UserName }).promise();
newKey = newKey ? newKey.AccessKey : undefined;
if (!newKey) {
console.log(`Failed to new key for user: ${user.UserName}. Skipping...`)
continue;
}
console.log(newKey);
const response = await ec2.describeInstances({
Filters: [
{
Name: 'tag:ManagedBy',
Values: ['__GATEFLAG__']
},
{
Name: 'tag:Name',
Values: [gateflagSpecificName]
},
{
Name: 'instance-state-name',
Values: ['running']
}
]
}).promise();
const instances = response.Reservations.flatMap(reservation =>
reservation.Instances.map(instance => {
return {
InstanceId: instance.InstanceId,
InstanceType: instance.InstanceType,
}
})
);
// Rotate the access keys inside EC2 using AWS Systems Manager (SSM)
for (instance of instances) {
console.log(`Rotating access keys in instance: ${instance.InstanceId} with new keys: ${newKey.AccessKeyId} & ${newKey.SecretAccessKey}`);
await updateCliConfiguration(instance.InstanceId, boxLocalUser, newKey.AccessKeyId, newKey.SecretAccessKey);
}
await iam.deleteAccessKey({ UserName: user.UserName, AccessKeyId: currentAccessKeyId }).promise();
console.log(`Access key rotated for user: ${user.UserName}`);
} else {
console.log(`No access keys found for user: ${user.UserName}`);
}
}
return {
statusCode: 200,
body: JSON.stringify({ message: 'Access key rotation completed.' }),
};
} catch (error) {
console.error('Error:', error);
return {
statusCode: 500,
body: JSON.stringify({ error: 'Internal server error' }),
};
}
};
RotateIAMKeysEventBridgeRule:
Type: AWS::Events::Rule
Properties:
Description: 'Run __GATEFLAG__RotateIAMKeysLambda fuction every N minutes'
ScheduleExpression: !Sub 'rate(${CTFTickDuration} minutes)'
State: ENABLED
Targets:
- Arn: !GetAtt RotateIAMKeysLambda.Arn
Id: RotateIAMKeysLambda
RotateIAMKeysEventBridgePermission:
Type: AWS::Lambda::Permission
Properties:
Action: lambda:InvokeFunction
FunctionName: !Ref RotateIAMKeysLambda
Principal: 'events.amazonaws.com'
SourceArn: !GetAtt RotateIAMKeysEventBridgeRule.Arn
# IAM and Policy Establishment.
CTFUserRole:
Type: AWS::IAM::Role
Properties:
RoleName: __GATEFLAG__CTFUserRole
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service: apigateway.amazonaws.com
Action: sts:AssumeRole
ManagedPolicyArns:
- !Ref CTFUserGetFlagThroughAPIGateway
DependsOn: "CTFUserGetFlagThroughAPIGateway"
CTFRootRole:
Type: AWS::IAM::Role
Properties:
RoleName: __GATEFLAG__CTFRootRole
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service: apigateway.amazonaws.com
Action: sts:AssumeRole
ManagedPolicyArns:
- !Ref CTFRootGetFlagThroughAPIGateway
DependsOn: "CTFRootGetFlagThroughAPIGateway"
CTFUserGetFlagThroughAPIGateway:
Type: AWS::IAM::ManagedPolicy
Properties:
ManagedPolicyName: __GATEFLAG__CTFUserGetFlagThroughAPIGateway
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action:
- execute-api:Invoke
Resource: !Sub arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${RestApi}/*/GET/user_flag
CTFRootGetFlagThroughAPIGateway:
Type: AWS::IAM::ManagedPolicy
Properties:
ManagedPolicyName: __GATEFLAG__CTFRootGetFlagThroughAPIGateway
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action:
- execute-api:Invoke
Resource: !Sub arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${RestApi}/*/GET/root_flag
RotateIAMKeysLambdaRole:
Type: 'AWS::IAM::Role'
Properties:
RoleName: __GATEFLAG__RotateIAMKeysLambdaRole
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service: lambda.amazonaws.com
Action: sts:AssumeRole
Policies:
- PolicyName: LambdaExecutionPolicy
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- iam:ListUsers
- iam:ListAccessKeys
- iam:CreateAccessKey
- iam:DeleteAccessKey
- iam:ListUserTags
Resource: '*'
- Effect: Allow
Action:
- sts:AssumeRole
- ec2:DescribeInstances
- ssm:PutParameter
- ssm:SendCommand
- ssm:StartSession
- ssm:AssumeRole
Resource: '*'
- Effect: Allow
Action:
- lambda:InvokeFunction
Resource: '*'
- Effect: 'Allow'
Action:
- 'logs:CreateLogGroup'
- 'logs:CreateLogStream'
- 'logs:PutLogEvents'
Resource: 'arn:aws:logs:*:*:*'
# EC2 Networking Establishment
Vpc:
Type: AWS::EC2::VPC
Properties:
CidrBlock: 10.0.0.0/16
EnableDnsSupport: true
EnableDnsHostnames: true
InstanceTenancy: default
Tags:
- Key: ManagedBy
Value: !Ref EnvironmentName
InternetGateway:
Type: AWS::EC2::InternetGateway
Properties:
Tags:
- Key: ManagedBy
Value: !Ref EnvironmentName
AttachGateway:
Type: AWS::EC2::VPCGatewayAttachment
Properties:
VpcId: !Ref Vpc
InternetGatewayId: !Ref InternetGateway
PublicRouteTable:
Type: AWS::EC2::RouteTable
Properties:
VpcId: !Ref Vpc
Tags:
- Key: ManagedBy
Value: !Ref EnvironmentName
PublicRoute:
Type: AWS::EC2::Route
Properties:
RouteTableId: !Ref PublicRouteTable
DestinationCidrBlock: 0.0.0.0/0
GatewayId: !Ref InternetGateway
EC2Subnet:
Type: AWS::EC2::Subnet
Properties:
CidrBlock: 10.0.1.0/24
MapPublicIpOnLaunch: true
VpcId: !Ref Vpc
Tags:
- Key: ManagedBy
Value: !Ref EnvironmentName
EC2SubnetRouteTableAssociation:
Type: AWS::EC2::SubnetRouteTableAssociation
Properties:
RouteTableId: !Ref PublicRouteTable
SubnetId: !Ref EC2Subnet
EC2SecurityGroup:
Type: AWS::EC2::SecurityGroup
Properties:
GroupDescription: Security Group for Gateflag CTFBox
VpcId: !Ref Vpc
SecurityGroupIngress:
- CidrIp: 0.0.0.0/0
IpProtocol: tcp
FromPort: 80
ToPort: 80
- CidrIp: 0.0.0.0/0
IpProtocol: tcp
FromPort: 443
ToPort: 443
- CidrIp: 0.0.0.0/0
IpProtocol: tcp
FromPort: 22
ToPort: 22
Tags:
- Key: ManagedBy
Value: !Ref EnvironmentName
EC2SSMRole:
Type: "AWS::IAM::Role"
Properties:
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: "Allow"
Principal:
Service: ["ec2.amazonaws.com"]
Action: "sts:AssumeRole"
Path: "/"
ManagedPolicyArns:
- 'arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore'
- 'arn:aws:iam::aws:policy/CloudWatchAgentServerPolicy'
EC2InstanceProfile:
Type: AWS::IAM::InstanceProfile
Properties:
Path: '/'
Roles:
- !Ref EC2SSMRole
RestApiVpcEndpoint:
Type: 'AWS::EC2::VPCEndpoint'
Properties:
ServiceName: !Sub com.amazonaws.${AWS::Region}.execute-api
PrivateDnsEnabled: true
VpcId: !Ref Vpc
SecurityGroupIds:
- !GetAtt EC2SecurityGroup.GroupId
SubnetIds:
- !Ref EC2Subnet
VpcEndpointType: Interface
Outputs:
GateflagRestApiUrl:
Description: URL of the Gateflag REST API
Value: !Sub "https://${RestApi}.execute-api.${AWS::Region}.amazonaws.com/${RestApiStage}"
CTFUserGetFlagThroughAPIGateway:
Description: CTFUserGetFlagThroughAPIGateway
Value: !Ref CTFUserGetFlagThroughAPIGateway
CTFRootGetFlagThroughAPIGateway:
Description: CTFRootGetFlagThroughAPIGateway
Value: !Ref CTFRootGetFlagThroughAPIGateway
EC2InstanceProfile:
Description: EC2InstanceProfile
Value: !Ref EC2InstanceProfile
EC2SecurityGroupGroupId:
Description: EC2SecurityGroupGroupId
Value: !GetAtt EC2SecurityGroup.GroupId
EC2Subnet:
Description: EC2Subnet
Value: !Ref EC2Subnet