-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathMetaDefenderWindows.template
426 lines (422 loc) · 21 KB
/
MetaDefenderWindows.template
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
{
"AWSTemplateFormatVersion": "2010-09-09",
"Description": "Template to launch MetaDefender Windows",
"Parameters" : {
"InstanceType": {
"Type": "String",
"Default": "m4.xlarge",
"AllowedValues": ["m4.xlarge", "m4.2xlarge", "m4.4xlarge", "c4.2xlarge", "c4.4xlarge", "c4.8xlarge"],
"Description": "Select desired instance type"
},
"AMI" : {
"Type": "AWS::EC2::Image::Id",
"Description": "Specify the MetaDefender AMI."
},
"VPC" : {
"Type": "AWS::EC2::VPC::Id",
"Description": "Specify the desired Virtual Private Cloud."
},
"Subnet": {
"Description": "Specify the subnet",
"Type": "AWS::EC2::Subnet::Id"
},
"ActivationKey" : {
"Type": "String",
"Description": "MetaDefender Windows License key - please note that same key might have multiple activations."
},
"KeyName": {
"Type": "AWS::EC2::KeyPair::KeyName",
"Description": "Specify key pair name used to connect to this instance"
}
},
"Resources": {
"MetaDefenderWindowsEC2": {
"Type": "AWS::EC2::Instance",
"Properties": {
"ImageId": {"Ref": "AMI"},
"IamInstanceProfile": {"Ref": "LambdaInstanceProfile"},
"InstanceType": {"Ref": "InstanceType"},
"KeyName": {"Ref": "KeyName"},
"NetworkInterfaces": [ {
"AssociatePublicIpAddress": "true",
"DeviceIndex": "0",
"GroupSet": [{ "Ref" : "MetaDefenderSecurityGroup" }],
"SubnetId": { "Ref" : "Subnet" }
}
],
"UserData": { "Fn::Base64": { "Fn::Join":
[
"\n",
[
"<powershell>",
"$lock = \"C:\\Program Files\\OPSWAT\\pwd_ch_lock\"",
{"Fn::Join": ["", ["$ActivationKey = ", "\"", {"Ref": "ActivationKey"}, "\""]]},
{"Fn::Join": ["", ["$LambdaFnName = ", "\"", {"Ref": "DeactivateLambda"}, "\""]]},
{"Fn::Join": ["", ["$CWEventRule = ", "\"", {"Ref": "DeactivateEventRule"}, "\""]]},
"$restUrl = \"http://localhost:8008\"",
"",
"function MetaDefenderLogin() {",
" Param",
" (",
" [Parameter(Mandatory=$true, Position=0)]",
" [string] $username,",
" [Parameter(Mandatory=$true, Position=1)]",
" [string] $password",
" )",
" $body = @{",
" \"user\"=\"$username\";",
" \"password\"=\"$password\";",
" } | ConvertTo-Json",
"",
" $loginUrl = $restUrl + \"/login\"",
" $response = Invoke-WebRequest -UseBasicParsing -Uri $loginUrl -Method POST -Body $body -ContentType \"application/json\" | ConvertFrom-Json ",
" return $response.session_id ",
"}",
"",
"function MetaDefenderChangePassword() {",
" Param",
" (",
" [Parameter(Mandatory=$true, Position=0)]",
" [string] $apikey ",
" )",
"",
" #Set session id as apikey header",
" $headers = @{",
" \"apikey\"=\"$apikey\";",
" }",
" ",
" #Create new password body",
" $body = @{",
" \"old_password\"=\"admin\";",
" \"new_password\"=\"$instance\";",
" } | ConvertTo-Json",
" ",
" $changePassUrl = $restUrl + \"/user/changepassword\"",
"",
" #Change password",
" return Invoke-WebRequest -UseBasicParsing -Uri $changePassUrl -Method POST -Headers $headers -Body $body -ContentType \"application/json\" | ",
" ConvertFrom-Json ",
"}",
"",
"function MetaDefenderActivateLicense () {",
" Param",
" (",
" [Parameter(Mandatory=$true, Position=0)]",
" [string] $apikey ",
" )",
" $Comment = \"MetaDefender AWS Instance: $instance\"",
" ",
" #Set session id as apikey header",
" $headers = @{",
" \"apikey\"=\"$apikey\";",
" }",
" ",
" $body = @{",
" \"activationKey\" = \"$ActivationKey\"; ",
" \"quantity\" = \"1\"; ",
" \"comment\" = \"$Comment\";",
" } | ConvertTo-Json",
"",
" $activationUrl = $restUrl + \"/admin/license/activation\"",
" return Invoke-WebRequest -UseBasicParsing $activationUrl -Headers $headers -ContentType \"application/json\" -Method POST -Body $body ",
"}",
"",
"function MetaDefenderLicenseDetails () {",
" Param",
" (",
" [Parameter(Mandatory=$true, Position=0)]",
" [string] $apikey ",
" )",
" ",
" #Set session id as apikey header",
" $headers = @{",
" \"apikey\"=\"$apikey\";",
" }",
" ",
" $licenseUrl = $restUrl + \"/admin/license\"",
" $ActivationDetails = Invoke-WebRequest -UseBasicParsing $licenseUrl -Headers $headers -ContentType \"application/json\" -Method GET ",
" return $ActivationDetails",
"}",
"",
"function AWSGetInstanceId() {",
" #Get instance name",
" return Invoke-WebRequest -UseBasicParsing -Uri http://169.254.169.254/latest/meta-data/instance-id -Method GET ",
"}",
"",
"function AWSUpdateLambdaVariables() {",
" Param",
" (",
" [Parameter(Mandatory=$true, Position=0)]",
" [string] $FunctionName, ",
" [Parameter(Mandatory=$true, Position=1)]",
" [hashtable] $EnvironmentVariables, ",
" [Parameter(Mandatory=$true, Position=2)]",
" [String] $InstanceID ",
" )",
"",
" $configuration = Get-LMFunctionConfiguration -FunctionName $FunctionName",
" $existingVars = $configuration.Environment.Variables",
"",
" $keys = $existingVars.getenumerator() | foreach-object {$_.key} ",
" $keys | foreach-object {",
" $key = $_",
" if ($EnvironmentVariables.containskey($key))",
" {",
" $existingVars.remove($key) ",
" }",
" }",
"",
" $allVars = $existingVars + $EnvironmentVariables ",
" ",
" Update-LMFunctionConfiguration -FunctionName $FunctionName -Environment_Variable $allVars",
"",
" #update event rule to limit lambda function to this instance",
" $eventRule = Get-CWERule -NamePrefix $CWEventRule",
" $pattern = $eventRule.EventPattern | ConvertFrom-Json ",
" $ruleDetails = $pattern.detail",
" ",
" $instanceIds = @($InstanceID)",
" if ($ruleDetails | Get-Member -Name 'instance-id') {",
" $existingIds = $ruleDetails | Get-Member -Name 'instance-id' ",
" $instanceIds = @($InstanceID) + $existingIds",
" }",
" ",
" $ruleDetails | Add-Member -Force -Name 'instance-id' -Type NoteProperty -Value $instanceIds ",
" $new_pattern = $pattern | ConvertTo-Json",
"",
" # update the rule",
" Write-CWERule -Name $CWEventRule -EventPattern $new_pattern",
"}",
"",
"function HandleException() {",
" Param",
" (",
" [Parameter(Mandatory=$true, Position=0)]",
" [System.Exception] $exception ",
" )",
"",
" $resp = $exception.Response",
"",
" if ($resp -eq $null)",
" {",
" Write-host $exception",
" }",
" else",
" {",
" $responseStream = $resp.GetResponseStream()",
" $streamReader = new-object System.IO.StreamReader $responseStream",
" $errorStackTrace = $streamReader.ReadToEnd() ",
" $errorMessage = [string]$Exception.Message",
" $statusCode = $Exception.Response.StatusCode.Value__",
" $errorMessage = \"Unable to activate license $ActivationKey :`nReason: [$statusCode] $errorMessage`n$errorStackTrace\" ",
" Write-Error -message $errorMessage -exception $exception ",
" }",
"}",
"",
"$instance = AWSGetInstanceId",
"",
"#Test for lock",
"if (Test-Path $lock) {",
" ",
" $credentials = @{",
" \"user\"=\"admin\";",
" \"password\"=\"$instance\";",
" }",
" $shouldChangePassword = $false",
"} else {",
" $credentials = @{ \"user\"=\"admin\"; \"password\"=\"admin\";}",
" $shouldChangePassword = $true",
"}",
"",
"#check if MetaDefender service is up",
"while (-not (Test-NetConnection localhost -Port 8008 | ? { $_.TcpTestSucceeded } )) {",
" #retry every 3 seconds",
" sleep 3",
"}",
"",
"Try",
"{ ",
" $sessionId = MetaDefenderLogin -username $credentials.user -password $credentials.password",
"",
" if ($shouldChangePassword) {",
" $response = MetaDefenderChangePassword -apikey $sessionId",
" if ($response) {",
" #Create passwd change lock",
" New-Item \"$lock\" -ItemType file",
" }",
" }",
" ",
" $ActivationDetails = MetaDefenderLicenseDetails -apikey $sessionId | ConvertFrom-Json",
" ",
" $deploymentID = $ActivationDetails.deployment",
" $envVarInstanceId = \"$instance\".replace('-', '_')",
"",
" $environmentVariables = @{",
" \"$envVarInstanceId\" = \"$deploymentID\"; ",
" } ",
"",
" AWSUpdateLambdaVariables -FunctionName $LambdaFnName -EnvironmentVariables $environmentVariables -InstanceID $instance",
"",
" MetaDefenderActivateLicense -apikey $sessionId",
"}",
"Catch",
"{",
" HandleException -exception $_.Exception ",
"}",
"</powershell>",
"<persist>true</persist>"
]
]}
}
},
"DependsOn": ["DeactivateLambda", "PermissionForEventsToInvokeLambda"]
},
"MetaDefenderSecurityGroup": {
"Type" : "AWS::EC2::SecurityGroup",
"Properties" : {
"GroupDescription": "Generated security group to allow traffic to MetaDefender REST API",
"GroupName": "MetaDefenderSecurityGroup",
"VpcId": { "Ref": "VPC" },
"SecurityGroupIngress": [
{
"IpProtocol": "tcp",
"FromPort": "8008",
"ToPort": "8008",
"Description": "REST API",
"CidrIp": "0.0.0.0/0"
}
]
}
},
"LambdaAccessRole" : {
"Type" : "AWS::IAM::Role",
"Properties" : {
"AssumeRolePolicyDocument" : {
"Statement" : [ {
"Effect" : "Allow",
"Principal" : {
"Service" : [ "ec2.amazonaws.com" ]
},
"Action" : [ "sts:AssumeRole" ]
} ]
},
"Path" : "/"
}
},
"LambdaRolePolicies" : {
"Type" : "AWS::IAM::Policy",
"Properties" : {
"PolicyName" : "lambdaaccess",
"PolicyDocument" : {
"Statement" : [ {
"Effect" : "Allow",
"Action" : ["lambda:*", "events:*"],
"Resource" : "*"
}]
},
"Roles" : [ { "Ref" : "LambdaAccessRole" } ]
}
},
"LambdaInstanceProfile" : {
"Type" : "AWS::IAM::InstanceProfile",
"Properties" : {
"Path" : "/",
"Roles" : [ { "Ref" : "LambdaAccessRole" } ]
}
},
"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": "deactivateMetaDefender",
"PolicyDocument": {
"Version": "2012-10-17",
"Statement": [{ "Effect": "Allow", "Action": ["logs:*"], "Resource": "*" }]
}
}]
}
},
"DeactivateLambda": {
"Type": "AWS::Lambda::Function",
"Properties": {
"Handler": "index.handler",
"Role": { "Fn::GetAtt" : ["LambdaExecutionRole", "Arn"] },
"Environment": {
"Variables": {
"ActivationKey": {"Ref": "ActivationKey"},
}
},
"Code": {
"ZipFile": {
"Fn::Join": [
"\n",
[
"var https = require('https');",
"exports.handler = (event, context, callback) => {",
" ",
" var instance = event['detail']['instance-id'].replace(\"-\", \"_\")",
" var licenseKey = process.env.ActivationKey",
" var deploymentID = process.env[instance]",
" ",
" var deactivateURL = `https://activation.dl.opswat.com/deactivation?key=${licenseKey}&deployment=${deploymentID}`",
" ",
" console.log('deactivateURL: ' + deactivateURL)",
" https.get(deactivateURL, function(res) {",
" console.log(\"Deactivate response: \" + res.statusCode);",
" context.succeed(); ",
" })",
" callback(null, 'success');",
"};"
]
]
}
},
"Runtime": "nodejs6.10"
},
"DependsOn": "LambdaExecutionRole"
},
"DeactivateEventRule": {
"Type": "AWS::Events::Rule",
"Properties": {
"Description": "MetaDefender Instance stopping or shutting down rule",
"EventPattern": {
"source": [ "aws.ec2" ],
"detail-type": [ "EC2 Instance State-change Notification" ],
"detail": {
"state": [
"shutting-down",
"stopping"
]
}
},
"State": "ENABLED",
"Targets": [{
"Arn": { "Fn::GetAtt": ["DeactivateLambda", "Arn"] },
"Id": "deactivateMetaDefender"
}]
},
"DependsOn": "DeactivateLambda"
},
"PermissionForEventsToInvokeLambda": {
"Type": "AWS::Lambda::Permission",
"Properties": {
"FunctionName": { "Ref": "DeactivateLambda" },
"Action": "lambda:InvokeFunction",
"Principal": "events.amazonaws.com",
"SourceArn": { "Fn::GetAtt": ["DeactivateEventRule", "Arn"] }
},
"DependsOn": "DeactivateEventRule"
}
},
"Outputs": {
"InstanceId": {
"Description": "MetaDefender Instance Identifier",
"Value": { "Ref": "MetaDefenderWindowsEC2" }
}
}
}