forked from Qualys-Public/aws-cv-connector-cf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathqualys_cf_aws_connectors_app.yml
316 lines (285 loc) · 12.7 KB
/
qualys_cf_aws_connectors_app.yml
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
AWSTemplateFormatVersion: '2010-09-09'
Description: Template to automatically setup Qualys AWS Connector for Asset Scanning
Metadata:
Author: "Nischay Sinha"
Version: "1.0"
Updated: "09/19/2022"
Version Comments: "Added ability to create CloudView and AssetView AWS Connectors from the same CloudFormation Template. Initial release, based off https://github.com/snicholson-qualys/aws-ec2-cloudformation-connector"
Parameters:
UserName:
Default: <supply_Qualys_user_name>
Description: User Authorized to Create a Qualys AWS Connector
Type: String
Password:
Default: <supply_Qualys_user_password>
Description: Password of the User Authorized to Create an Qualys AWS Connector
Type: String
NoEcho: true
BaseApiUrl:
Default: <supply_Qualys_Platform_API_URL>
Description: Qualys platform API Server URL. Find the Platform API url at https://www.qualys.com/platform-identification/
Type: String
ExternalId:
Description: Specify an External ID using the format of PodID-CustomerId-{random_string_between_1_and_512_characters}
Type: String
AllowedPattern : ([a-zA-Z0-9_\-\.]+)-([a-zA-Z0-9_\-\.]+)-([a-zA-Z0-9_\-\.]+)
ConstraintDescription : External ID can't be emplty and should follow the format PodID-CustomerId-{random_string_between_1_and_512_characters}
BaseAccountId:
Default: Empty
Description: Qualys AWS ID
Type: String
RoleName:
Default: CF-QualysAWSConnectorRole
Description: Name of the Role to Create
Type: String
RunFrequency:
Default: 240
Description: Frequency at which the connector should poll the cloud provider and fetch data (minutes), Default - 240 (4 hours)
Type: Number
Resources:
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:
- logs:CreateLogGroup
- logs:CreateLogStream
- logs:PutLogEvents
Resource: arn:aws:logs:*:*:*
- Effect: Allow
Action:
- iam:CreateRole
- iam:ListAccountAliases
Resource: '*'
ConnectorFunction:
Type: AWS::Lambda::Function
DependsOn: QualysConnectorRole
Properties:
Environment:
Variables:
BaseApiUrl: !Ref BaseApiUrl
USERNAME: !Ref UserName
PASSWORD: !Ref Password
EXTERNALID: !Ref ExternalId
ROLENAME: !Ref RoleName
RUNFREQUENCY: !Ref RunFrequency
Code:
ZipFile: !Sub |
import json
import traceback
import os
import urllib3
import boto3
import cfnresponse
def lambda_handler(event,context):
EXTERNALID = os.getenv('EXTERNALID')
ROLENAME = os.getenv('ROLENAME')
RUNFREQUENCY = os.getenv('RUNFREQUENCY')
responseData = {}
dataConnectorId = 1
qualysAccountId = 1
try:
if os.getenv('BaseApiUrl').endswith('/'):
os.getenv('BaseApiUrl')[:-1]
else:
os.getenv('BaseApiUrl')
print('BaseApiUrl: {}'.format(os.getenv('BaseApiUrl')))
data = []
api_endpoint_create_connector="{}/qps/rest/3.0/create/am/awsassetdataconnector".format(os.getenv('BaseApiUrl'))
api_endpoint_run_connector="{}/qps/rest/3.0/run/am/awsassetdataconnector/".format(os.getenv('BaseApiUrl'))
ACCOUNT_ID = context.invoked_function_arn.split(":")[4]
client = boto3.client('iam')
paginator = client.get_paginator('list_account_aliases')
for response in paginator.paginate():
if 'AccountAliases' in response:
if len(response['AccountAliases']) != 0:
print(response['AccountAliases'])
print(type(response['AccountAliases'][0]))
accountName = str(response['AccountAliases'][0])
break
else:
accountName = ACCOUNT_ID
else:
accountName = ACCOUNT_ID
data = {
"ServiceRequest": {
"data": {
"AwsAssetDataConnector": {
"name":"{}".format(accountName),
"arn": "arn:aws:iam::{}:role/{}".format(ACCOUNT_ID,ROLENAME),
"externalId": "{}".format(EXTERNALID),
"allRegions": "true",
"disabled": "false",
"description": "Connector created through API automation",
"connectorAppInfos": {
"set": {
"ConnectorAppInfoQList": [
{
"set": {
"ConnectorAppInfo": [
{
"name": "AI",
"identifier": "arn:aws:iam::{}:role/{}".format(ACCOUNT_ID,ROLENAME)
}
]
}
},
{
"set": {
"ConnectorAppInfo": [
{
"name": "CI",
"identifier": "arn:aws:iam::{}:role/{}".format(ACCOUNT_ID,ROLENAME)
}
]
}
},
{
"set": {
"ConnectorAppInfo": [
{
"name": "CSA",
"identifier": "arn:aws:iam::{}:role/{}".format(ACCOUNT_ID,ROLENAME)
}
]
}
}
]
}
},
"runFrequency": RUNFREQUENCY
}
}
}
}
encoded_data = json.dumps(data).encode('utf-8')
auth=os.getenv('USERNAME')+":"+os.getenv('PASSWORD')
headers = urllib3.make_headers(basic_auth=auth)
print("DATA: {}".format(data))
print("URL for run request {}".format(api_endpoint_create_connector))
headers['X-Requested-With'] = "Qualys CloudFormation (python)"
headers['Accept'] = 'application/json'
headers['Content-Type'] = 'application/json'
avheaders = headers.copy()
avheaders['Content-Type'] = "text/xml"
print("DATA: {}".format(data))
http = urllib3.PoolManager()
r = http.request('POST', api_endpoint_create_connector, body=encoded_data, headers=headers, timeout=180)
print("Status: {}".format(r.status))
print(r.data.decode('utf-8'))
print(type(r.data.decode('utf-8')))
data = json.loads(r.data.decode('utf-8'))
if 'id' in data['ServiceResponse']['data'][0]['AwsAssetDataConnector']:
dataConnectorId = data['ServiceResponse']['data'][0]['AwsAssetDataConnector']['id']
data2 = json.loads(r.data.decode('utf-8'))
print("DATA: {}".format(data2))
if data2['ServiceResponse']['count'] > 0:
for connector in data2['ServiceResponse']['data']:
run_connector_url = api_endpoint_run_connector + str(connector['AwsAssetDataConnector']['id'])
print(run_connector_url)
r2 = http.request('POST', run_connector_url, headers=avheaders, timeout=180)
print(r2.data.decode('utf-8'))
d = json.loads(r2.data.decode('utf-8'))
print('r2: {}'.format(d))
print("Run Connector ID: {} status code {}".format(str(connector['AwsAssetDataConnector']['id']),r2.status))
except Exception as e:
traceback.print_exc()
print("Response - {}".format(e))
responseData['Error Reponse'] = {"r": r.status, "r2": r2.status}
responseData['responseErrorDetails'] = e
cfnresponse.send(event, context, cfnresponse.FAILED, responseData)
responseData['RunConnector'] = r.status
responseData['DataConnectorId'] = dataConnectorId
responseData['ExternalId'] = EXTERNALID
cfnresponse.send(event, context, cfnresponse.SUCCESS, responseData)
Description: Lambda Function to run AWS connector after creation of the IAM Role for the connector
Handler: index.lambda_handler
Role: !GetAtt 'LambdaExecutionRole.Arn'
Runtime: python3.9
Timeout: '600'
QualysConnectorRole:
Type: AWS::IAM::Role
Properties:
RoleName: !Ref RoleName
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
AWS: !Sub 'arn:aws:iam::${BaseAccountId}:root'
Condition:
StringEquals:
sts:ExternalId: !Ref ExternalId
Action:
- sts:AssumeRole
Path: /
ManagedPolicyArns:
- arn:aws:iam::aws:policy/SecurityAudit
CreateQualysCustomPolicy:
Type: AWS::IAM::ManagedPolicy
Properties:
Description: This policy contains additional permissions for fetching resource
details.
ManagedPolicyName: !Sub 'QualysReadOnlyPolicy-${RoleName}'
PolicyDocument:
Version: '2012-10-17'
Statement:
- Sid: QualysReadOnlyPermissions
Effect: Allow
Action:
- eks:ListFargateProfiles
- eks:DescribeFargateProfile
Resource: "*"
- Sid: QualysCustomPolicyPermissions
Effect: Allow
Action:
- states:DescribeStateMachine
- elasticfilesystem:DescribeFileSystemPolicy
- qldb:ListLedgers
- qldb:DescribeLedger
- kafka:ListClusters
- codebuild:BatchGetProjects
- wafv2:GetWebACLForResource
- backup:ListBackupVaults
- backup:DescribeBackupVault
- ec2:GetEbsEncryptionByDefault
- ec2:GetEbsDefaultKmsKeyId
- guardduty:ListDetectors
- guardduty:GetDetector
- glue:GetDataCatalogEncryptionSettings
- elasticmapreduce:GetBlockPublicAccessConfiguration
- lambda:GetFunctionConcurrency
- ds:ListLogSubscriptions
Resource: "*"
- Sid: QualysAPIGatewayGetPermissions
Effect: Allow
Action: apigateway:GET
Resource: arn:aws:apigateway:*::/restapis/*
Roles:
- Ref: QualysConnectorRole
CustomResource:
Type: Custom::CustomResource
Properties:
ServiceToken: !GetAtt 'ConnectorFunction.Arn'
Outputs:
ExternalId:
Description: ExternalId generated (or passed) required by the Qualys Role.
Value: !GetAtt 'CustomResource.ExternalId'
DataConnectorId:
Description: The Qualys Id of the configured Connector
Value: !GetAtt 'CustomResource.DataConnectorId'