-
Notifications
You must be signed in to change notification settings - Fork 0
/
load_data.py
380 lines (302 loc) · 15.2 KB
/
load_data.py
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
from py2neo import Graph
from tqdm import tqdm
import json
import pandas as pd
import sys
import warnings
def load_excel(file_path):
"""Load pandas dataframes from stored Excel files.
Parameters
----------
file_path : string
File path from which to load data.
Returns
-------
policies : pd.DataFrame
DataFrame listing all policies.
users : pd.DataFrame
DataFrame listing all users.
groups : pd.DataFrame
DataFrame listing all groups.
roles : pd.DataFrame
DataFrame listing all roles.
"""
# Read from input file
df_policies = pd.read_excel(file_path, sheet_name='policies', index_col=0)
df_users = pd.read_excel(file_path, sheet_name='users' , index_col=0)
df_groups = pd.read_excel(file_path, sheet_name='groups' , index_col=0)
df_roles = pd.read_excel(file_path, sheet_name='roles' , index_col=0)
# Fill NaN (Not a Number) field with an empty string
df_policies.fillna('', inplace=True)
df_roles.columns = df_roles.columns.str.replace('.', '', regex=False)
# Check if extra space was needed for the policy object, if so merge it again
if 'ExtraPolicySpace' in df_policies.columns:
for index, row in df_policies.iterrows():
if row.ExtraPolicySpace != '':
df_policies.at[index, 'PolicyObject'] = row.PolicyObject + row.ExtraPolicySpace
# Return result
return df_policies, df_users, df_groups, df_roles
def create_policy_nodes(gr, policies):
"""Create policy nodes for given graph.
Parameters
----------
gr : Graph
Graph for which to create nodes.
policies : pd.DataFrame
Policies for which to create nodes.
"""
tx = gr.begin()
for index, row in tqdm(policies.iterrows(), desc="Loading policies"):
tx.evaluate('''
CREATE (policy:Policy {name: $name, id: $id, arn: $arn, policyObject: $policyObject}) RETURN policy
''', parameters={
'name' : row.PolicyName,
'id' : row.PolicyId,
'arn' : row.Arn,
'policyObject': row.PolicyObject,
})
gr.commit(tx)
def create_resource_nodes(gr, resources):
"""Create resource nodes for given graph.
Parameters
----------
gr : Graph
Graph for which to create nodes.
resources : pd.DataFrame
Resources for which to create nodes.
"""
tx = gr.begin()
for index, row in tqdm(resources.iterrows(), desc="Loading resources"):
policy_object = row.PolicyObject.replace("\'", "\"")
policy_object = policy_object.replace("True", "true")
policy_object = policy_object.replace("False", "false")
try:
policy_list = json.loads(policy_object)
if not isinstance(policy_list, list):
tmp = [policy_list]
policy_list = tmp
for policy in policy_list:
# Check whether the policy actually contains resources
if 'Resource' in policy:
resource_list = policy['Resource']
if not isinstance(resource_list, list):
tmp = [resource_list]
resource_list = tmp
for resource in resource_list:
tx.evaluate('''
MERGE (resource:Resource {name: $name, forPolicy: $policy})
''', parameters={'name': resource, 'policy': row.PolicyName})
elif 'NotResource' in policy:
not_resource_list = policy['NotResource']
if not isinstance(not_resource_list, list):
tmp = [not_resource_list]
not_resource_list = tmp
for not_resource in not_resource_list:
tx.evaluate('''
MERGE (notresource:NotResource {name: $name, forPolicy: $policy})
''', parameters={'name': not_resource, 'policy': row.PolicyName})
except json.decoder.JSONDecodeError as e:
warnings.warn("Error in row '{}': '{}', skipping row...".format(row.PolicyName, e))
gr.commit(tx)
def create_action_nodes(gr, actions):
"""Create action nodes for given graph.
Parameters
----------
gr : Graph
Graph for which to create nodes.
actions : pd.DataFrame
Actions for which to create nodes.
"""
tx = gr.begin()
for index, row in tqdm(actions.iterrows(), desc="Loading actions"):
# Replace single quote with double quote for json parsing
policy_object = row.PolicyObject.replace("\'", "\"")
policy_object = policy_object.replace("True", "true")
policy_object = policy_object.replace("False", "false")
try:
policy_list = json.loads(policy_object)
if not isinstance(policy_list, list):
tmp = [policy_list]
policy_list = tmp
for policy in policy_list:
resource_list = []
not_resource_list = []
action_list = []
not_action_list = []
if 'Resource' in policy:
resource_list = policy['Resource']
elif 'NotResource' in policy:
resource_list = policy['NotResource']
if not isinstance(resource_list, list):
tmp = [resource_list]
resource_list = tmp
if not isinstance(not_resource_list, list):
tmp = [not_resource_list]
not_resource_list = tmp
if 'Action' in policy:
action_list = policy['Action']
elif 'NotAction' in policy:
not_action_list = policy['NotAction']
if not isinstance(action_list, list):
tmp = [action_list]
action_list = tmp
if not isinstance(not_action_list, list):
tmp = [not_action_list]
not_action_list = tmp
if resource_list and action_list:
for resource in resource_list:
for action in action_list:
tx.evaluate('''
MATCH (p:Policy), (res:Resource)
WHERE p.name = $policyName AND res.name = $resourceName AND res.forPolicy = $policy
CREATE (p)-[:CONTAINS]->(action:Action {name: $name})-[:WORKS_ON]->(res)
RETURN action
''', parameters={'policyName': row.PolicyName, 'resourceName': resource, 'name': action,
'policy': row.PolicyName})
if not_resource_list and action_list:
for resource in not_resource_list:
for action in action_list:
tx.evaluate('''
MATCH (p:Policy), (res:NotResource)
WHERE p.name = $policyName AND res.name = $resourceName AND res.forPolicy = $policy
CREATE (p)-[:CONTAINS]->(action:NotAction {name: $name})-[:WORKS_NOT_ON]->(res)
RETURN action
''', parameters={'policyName': row.PolicyName, 'resourceName': resource, 'name': action,
'policy': row.PolicyName})
if not_resource_list and not_action_list:
for resource in not_resource_list:
for action in not_action_list:
tx.evaluate('''
MATCH (p:Policy), (res:NotResource)
WHERE p.name = $policyName AND res.name = $resourceName AND res.forPolicy = $policy
CREATE (p)-[:CONTAINS]->(action:notAction {name: $name})-[:WORKS_NOT_ON]->(res)
RETURN action
''', parameters={'policyName': row.PolicyName, 'resourceName': resource, 'name': action,
'policy': row.PolicyName})
if resource_list and not_action_list:
for resource in resource_list:
for action in not_action_list:
tx.evaluate('''
MATCH (p:Policy), (res:Resource)
WHERE p.name = $policyName AND res.name = $resourceName AND res.forPolicy = $policy
CREATE (p)-[:CONTAINS]->(action:NotAction {name: $name})-[:WORKS_NOT_ON]->(res)
RETURN action
''', parameters={'policyName': row.PolicyName, 'resourceName': resource, 'name': action,
'policy': row.PolicyName})
except json.decoder.JSONDecodeError as e:
warnings.warn("Error in row '{}': '{}', skipping row...".format(row.PolicyName, e))
gr.commit(tx)
def create_user_nodes(gr, users):
"""Create user nodes for given graph.
Parameters
----------
gr : Graph
Graph for which to create nodes.
users : pd.DataFrame
Users for which to create nodes.
"""
tx = gr.begin()
for index, row in tqdm(users.iterrows(), desc="Loading users"):
tx.evaluate('''
CREATE (user:User {name: $name, id: $id, arn: $arn, attachedPolicies: $attachedPolicies}) RETURN user
''', parameters={'name': row.UserName, 'id': row.UserId, 'arn': row.Arn,
'attachedPolicies': row.AttachedPolicies})
gr.commit(tx)
tx = gr.begin()
for index, row in tqdm(users.iterrows(), desc="Attaching user policies"):
attached_policies = row.AttachedPolicies.replace("\'", "\"")
attached_policies_list = json.loads(attached_policies)
for policy in attached_policies_list:
tx.evaluate('''
MATCH (u:User), (p:Policy)
WHERE u.name = $userName AND p.name = $policyName
CREATE (p)-[:IS_ATTACHED_TO]->(u)
''', parameters={'userName': row.UserName, 'policyName': policy['PolicyName']})
gr.commit(tx)
def create_group_nodes(gr, groups):
"""Create group nodes for given graph.
Parameters
----------
gr : Graph
Graph for which to create nodes.
groups : pd.DataFrame
Groups for which to create nodes.
"""
tx = gr.begin()
for index, row in tqdm(groups.iterrows(), desc="Loading groups"):
tx.evaluate('''
CREATE (group:Group {name: $name, id: $id, arn: $arn, attachedPolicies: $attachedPolicies, user: $users}) RETURN group
''', parameters={'name': row.GroupName, 'id': row.GroupId, 'arn': row.Arn,
'attachedPolicies': row.AttachedPolicies, 'users': row.Users})
gr.commit(tx)
tx = gr.begin()
for index, row in tqdm(groups.iterrows(), desc="Attaching group policies"):
attached_policies = row.AttachedPolicies.replace("\'", "\"")
attached_policies_list = json.loads(attached_policies)
for policy in attached_policies_list:
tx.evaluate('''
MATCH (g:Group), (p:Policy)
WHERE g.name = $groupName AND p.name = $policyName
CREATE (p)-[:IS_ATTACHED_TO]->(g)
''', parameters={'groupName': row.GroupName, 'policyName': policy['PolicyName']})
gr.commit(tx)
tx = gr.begin()
users = row.Users.replace("\'", "\"")
users_list = json.loads(users)
for user in users_list:
tx.evaluate('''
MATCH (u:User), (g:Group)
WHERE u.name = $userName AND g.name = $groupName
CREATE (u)-[:PART_OF]->(g)
''', parameters={'userName': user['UserName'], 'groupName': row.GroupName})
gr.commit(tx)
def create_role_nodes(gr, roles):
"""Create role nodes for given graph.
Parameters
----------
gr : Graph
Graph for which to create nodes.
roles : pd.DataFrame
Roles for which to create nodes.
"""
tx = gr.begin()
for index, row in tqdm(roles.iterrows(), desc="Loading roles"):
try:
tx.evaluate('''
CREATE (role:Role {name: $name, id: $id, arn: $arn, attachedPolicies: $attachedPolicies, assumeRolePolicyDocumentVersion: $assumeRolePolicyDocumentVersion ,assumeRolePolicyDocumentStatement: $assumeRolePolicyDocumentStatement}) RETURN role
''', parameters={'name': row.RoleName, 'id': row.RoleId, 'arn': row.Arn,
'attachedPolicies': row.AttachedPolicies,
'assumeRolePolicyDocumentVersion': row.AssumeRolePolicyDocumentStatement,
'assumeRolePolicyDocumentStatement': row.AssumeRolePolicyDocumentStatement})
except AttributeError as e:
# Print warning
warnings.warn("Error in row '{}': '{}', trying to load as json...".format(row.RoleName, e))
policy_document = json.loads(row.AssumeRolePolicyDocument)
tx.evaluate('''
CREATE (role:Role {name: $name, id: $id, arn: $arn, attachedPolicies: $attachedPolicies, assumeRolePolicyDocumentVersion: $assumeRolePolicyDocumentVersion ,assumeRolePolicyDocumentStatement: $assumeRolePolicyDocumentStatement}) RETURN role
''', parameters={'name': row.RoleName, 'id': row.RoleId, 'arn': row.Arn,
'attachedPolicies': row.AttachedPolicies,
'assumeRolePolicyDocumentVersion': policy_document.get('Version', 'N/A'),
'assumeRolePolicyDocumentStatement': str(policy_document.get('Statement', 'N/A'))})
gr.commit(tx)
tx = gr.begin()
for index, row in tqdm(roles.iterrows(), desc="Attaching role policies"):
attached_policies = row.AttachedPolicies.replace("\'", "\"")
attached_policies_list = json.loads(attached_policies)
for policy in attached_policies_list:
tx.evaluate('''
MATCH (r:Role), (p:Policy)
WHERE r.name = $roleName AND p.name = $policyName
CREATE (p)-[:IS_ATTACHED_TO]->(r)
''', parameters={'roleName': row.RoleName, 'policyName': policy['PolicyName']})
gr.commit(tx)
if __name__ == "__main__":
# Create connection with Graph
graph = Graph("bolt://localhost:7687", user="neo4j", password="password")
# Load data from stored files
df_policies, df_users, df_groups, df_roles = load_excel("../collector/example/iam_policy_data_2021-03-26_14:11.xlsx")
# Create relevant nodes
create_policy_nodes (graph, df_policies)
create_resource_nodes(graph, df_policies)
create_action_nodes (graph, df_policies)
create_role_nodes (graph, df_roles)