forked from nccgroup/PMapper
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpmapper.py
executable file
·193 lines (161 loc) · 6.76 KB
/
pmapper.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
#!/usr/bin/env python
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
import argparse
import botocore.session
import logging
import os
import os.path
import sys
import principalmap.enumerator
from principalmap.querying import perform_query
from principalmap.visualizing import perform_visualization
from principalmap.awsgraph import AWSGraph
from principalmap.awsnode import AWSNode
from principalmap.awsedge import AWSEdge
def main():
mainparser = argparse.ArgumentParser()
mainparser.add_argument('--profile', help='Profile stored for the AWS CLI')
mainparser.add_argument('--env-vars', action='store_true', help='Use environment variables for credentials.')
subparsers = mainparser.add_subparsers(
title='subcommands',
description='The different functionalities of this tool.',
dest='picked_cmd',
help='Select one to execute.'
)
graphparser = subparsers.add_parser(
'graph',
help='For pulling information from an AWS account.',
description='Uses the botocore library to query the AWS API and compose a graph of principal relationships. By default, running this command will create a graph.'
)
graphparser.add_argument('--display', action='store_true', help='Displays stored graph rather than composing one.')
queryparser = subparsers.add_parser(
'query',
help='For querying the graph pulled from an AWS account.',
description='Uses a created graph to provide a query interface, executes the passed query. It also will make calls to the AWS API.'
)
queryparser.add_argument('query_string', help='The query to run against the endpoint.')
queryparser.add_argument('-s', '--skip-admin', action='store_true', help='Skip admin principals when running a query.')
visualparser = subparsers.add_parser(
'visualize',
help='For visualizing the pulled graph.',
description='Creates a visualization of the passed graph.'
)
parsed = mainparser.parse_args(sys.argv[1:])
if parsed.profile is not None and parsed.env_vars:
print('Cannot use both a profile and environment variables.')
sys.exit(-1)
session = create_session(parsed)
if session is None:
print('Could not obtain caller identity.')
if parsed.profile is not None:
print('Validate the credentials for profile ' + parsed.profile + '.')
sys.exit(-1)
if parsed.picked_cmd == 'graph':
handle_graph(parsed, session)
elif parsed.picked_cmd == 'query':
handle_query(parsed, session)
elif parsed.picked_cmd == 'visualize':
handle_visualize(parsed, session)
def create_session(parsed):
"""A function to create a botocore session.
Returns None if there aren't any valid creds available."""
result = None
if parsed.env_vars:
access_key_id = os.environ.get('AWS_ACCESS_KEY_ID')
secret_key = os.environ.get('AWS_SECRET_ACCESS_KEY')
session_token = os.environ.get('AWS_SESSION_TOKEN')
result = botocore.session.Session()
if access_key_id is not None and secret_key is not None:
result.set_credentials(access_key_id, secret_key, session_token)
else:
return None
else:
if parsed.profile is None:
result = botocore.session.Session(profile='default')
parsed.profile = 'default'
else:
result = botocore.session.Session(profile=parsed.profile)
result.get_credentials() # trip exception if profile doesn't exist
# Attempt to use the session to validate that it can be used
try:
result.create_client('sts').get_caller_identity()
except:
return None
return result
def get_graph_file(parsed, account, mode):
"""Retrieve file object, handling if it's a principal in the credentials file or environment variables."""
dirpath = ''
filepath = ''
if parsed.env_vars:
dirpath = os.path.join(os.path.expanduser('~'), '.principalmap-acct/')
filepath = os.path.join(dirpath, 'graphfile-' + account)
else:
dirpath = os.path.join(os.path.expanduser('~'), '.principalmap/')
filepath = os.path.join(dirpath, 'graphfile-' + parsed.profile)
if not os.path.exists(dirpath):
os.makedirs(dirpath)
return open(filepath, mode)
def handle_graph(parsed, session):
identity_response = session.create_client('sts').get_caller_identity()
account = identity_response['Account']
caller = identity_response['Arn']
if not parsed.display:
if parsed.profile is not None:
print('Using profile: ' + parsed.profile)
print('Pulling data for account ' + identity_response['Account'])
print('Using principal with ARN ' + identity_response['Arn'])
graph = pull_graph(parsed, session)
print('Created an ' + str(graph))
graphfile = get_graph_file(parsed, account, "w+")
graphfile.write("# Graph file generated by Principal Mapper\n")
graph.write_to_fd(graphfile)
else:
graphfile = get_graph_file(parsed, account, "r")
graph = graph_from_file(graphfile)
print(str(graph))
def handle_query(parsed, session):
identity_response = session.create_client('sts').get_caller_identity()
account = identity_response['Account']
graphfile = get_graph_file(parsed, account, "r")
graph = graph_from_file(graphfile)
perform_query(parsed.query_string, session, graph, parsed.skip_admin)
def handle_visualize(parsed, session):
identity_response = session.create_client('sts').get_caller_identity()
account = identity_response['Account']
graphfile = get_graph_file(parsed, account, "r")
graph = graph_from_file(graphfile)
perform_visualization(parsed, account, session, graph)
def pull_graph(parsed, session):
enumerator = principalmap.enumerator.Enumerator(session)
enumerator.fillOutGraph()
return enumerator.graph
def graph_from_file(graphfile):
result = AWSGraph()
mode = 'headers'
for line in graphfile:
if line == "\n":
break
if mode == 'headers':
if line[0] != '#':
mode = 'nodes'
else:
pass # ignoring headers
if mode == 'nodes':
if "[NODES]" in line:
pass
elif "[EDGES]" in line:
mode = 'edges'
else:
node = eval(line)
result.nodes.append(eval(line))
if mode == 'edges':
if "[EDGES]" in line:
pass
else:
pair = eval(line)
result.edges.append(AWSEdge(result.nodes[pair[0]], result.nodes[pair[1]], pair[2], pair[3]))
return result
if __name__ == '__main__':
main()