-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathqualys_cf_ec2_connector.yml
207 lines (198 loc) · 8.25 KB
/
qualys_cf_ec2_connector.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
AWSTemplateFormatVersion: '2010-09-09'
Description: Template to automatically setup Qualys AWS EC2 Connector for Asset Scanning
Metadata:
Author: "Sean Nicholson"
Version: "1.3"
Updated: "06/13/2019"
Version Comments: "Template will create the AssetView and CloudView Connectors"
Parameters:
UserName:
Default: <ENTER QUALYS ACCOUNT NAME>
Description: User Authorized to Create a Qualys AWS Connector
Type: String
Password:
Default: <ENTER QUALYS API ACOUNT PASSWORD>
Description: Password of the User Authorized to Create an Qualys AWS Connector
Type: String
NoEcho: true
BaseUrl:
Default: <ENTER QUALYS API URL>
Description: Base URL of the Qualys Server
Type: String
ExternalId:
Default: Empty
Description: (Optional) ExternalId to embed in role, one will be generated if empty
Type: String
CreateCloudViewConn:
Default: true
Description: (Optional) Create CloudView Connector when creating AV Connector
Type: String
RoleName:
Default: CF-QualysConnectorRole
Description: Name of the Role to Create
Type: String
Resources:
ConnectorFunction:
Type: AWS::Lambda::Function
Properties:
Environment:
Variables:
BASEURL: !Ref BaseUrl
EXTERNALID: !Ref ExternalId
USERNAME: !Ref UserName
PASSWORD: !Ref Password
ROLENAME: !Ref RoleName
CLOUDVIEW: !Ref CreateCloudViewConn
Code:
ZipFile: !Sub |
import json
import traceback
import os
import boto3
import urllib3
import cfnresponse
from random import randint
def lambda_handler(event,context):
EXTERNALID = os.getenv('EXTERNALID')
ROLENAME = os.getenv('ROLENAME')
CLOUDVIEW = os.getenv('CLOUDVIEW')
dataConnectorId = 1 #setting variable type - variable set for logging
qualysAccountId = 1 #setting variable type - account ID for trust relationship is set by create connector API response
try:
api_endpoint="{}/qps/rest/2.0/create/am/awsassetdataconnector".format(os.getenv('BASEURL'))
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:
print(response['AccountAliases'])
print(type(response['AccountAliases'][0]))
accountName = str(response['AccountAliases'][0])
break
else:
accountName = ACCOUNT_ID
EXTERNALID = randint(1000000000000000000,999999999999999999999999999999999) if EXTERNALID == "Empty" else EXTERNALID
data= {
"ServiceRequest":{
"data":{
"AwsAssetDataConnector":{
"name":"{0}".format(accountName),
"description": "Account Name: {0} - Connector for AWS Account {1}".format(accountName, ACCOUNT_ID),
"arn":"arn:aws:iam::{}:role/{}".format(ACCOUNT_ID, ROLENAME),
"externalId":"{}".format(EXTERNALID),
"allRegions":"true",
"disabled":"false",
"useForCloudView": CLOUDVIEW,
"activation": {
"set": {
"ActivationModule": [
"VM",
"PC"
]
}
}
}
}
}
}
encoded_data = json.dumps(data).encode('utf-8')
auth=os.getenv('USERNAME')+":"+os.getenv('PASSWORD')
print("DATA: {}".format(data))
headers = urllib3.make_headers(basic_auth=auth) # added basic auth in headers
headers['X-Requested-With'] = 'Qualys CloudFormation (python)'
headers['Accept'] = 'application/json'
headers['Content-Type'] = 'application/json'
http = urllib3.PoolManager()
print("API URL = {}".format(api_endpoint))
r = http.request('POST', api_endpoint, body=encoded_data, headers=headers, timeout=180)
#print("RESPONSE: {}".format(r.data.decode('utf-8')))
print("Status: {}".format(r.status))
data = json.loads(r.data.decode('utf-8'))
print("DATA: {}".format(data))
responseData = {}
if 'ServiceResponse' in data:
if 'responseCode' in data['ServiceResponse']:
responseData['responseCode'] = data['ServiceResponse']['responseCode']
if 'responseErrorDetails' in data['ServiceResponse']:
responseData['responseErrorDetails'] = data['ServiceResponse']['responseErrorDetails']['errorMessage']
cfnresponse.send(event, context, cfnresponse.FAILED, responseData)
if 'data' in data['ServiceResponse']:
if 'AwsAssetDataConnector' in data['ServiceResponse']['data'][0]:
record = data['ServiceResponse']['data'][0]['AwsAssetDataConnector']
if 'id' in record:
dataConnectorId = record['id']
if 'qualysAwsAccountId' in record:
qualysAccountId = record['qualysAwsAccountId']
except Exception as e:
responseData = {}
traceback.print_exc()
print("Response - {}".format(e))
responseData['responseErrorDetails'] = e
cfnresponse.send(event, context, cfnresponse.FAILED, responseData)
responseData['DataConnectorId'] = dataConnectorId
responseData['AccountId'] = qualysAccountId
responseData['ExternalId'] = EXTERNALID
cfnresponse.send(event, context, cfnresponse.SUCCESS, responseData)
Description: Lambda Function to Register Qualys AWS EC2 Connector and Create associated Role
Handler: index.lambda_handler
Role: !GetAtt 'LambdaExecutionRole.Arn'
Runtime: python3.6
Timeout: '600'
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: '*'
QualysConnectorRole:
Type: AWS::IAM::Role
Properties:
RoleName: !Ref RoleName
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
AWS: !GetAtt 'CustomResource.AccountId'
Condition:
StringEquals:
sts:ExternalId: !GetAtt 'CustomResource.ExternalId'
Action:
- sts:AssumeRole
Path: /
ManagedPolicyArns:
- arn:aws:iam::aws:policy/SecurityAudit
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'