forked from paulbayer/Inventory_Scripts
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRegistrationScript.py
More file actions
executable file
·237 lines (226 loc) · 8.73 KB
/
RegistrationScript.py
File metadata and controls
executable file
·237 lines (226 loc) · 8.73 KB
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
#!/usr/bin/env python3
"""
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
import os, sys, pprint, boto3
import Inventory_Modules
import argparse
from colorama import init,Fore,Back,Style
from botocore.exceptions import ClientError, NoCredentialsError
import logging
init()
parser = argparse.ArgumentParser(
description="We\'re going to find the necessary information to register this account within Isengard.",
prefix_chars='-+/')
parser.add_argument(
"-p", "--profile",
dest="pProfile",
default='default',
metavar="profile to use",
help="To specify a specific profile, use this parameter. Default will be ALL profiles, including those in ~/.aws/credentials and ~/.aws/config")
parser.add_argument(
'-f', '--force',
const=True,
default=False,
dest="pForcedReg",
action="store_const",
help="Force a registration with Isengard")
parser.add_argument(
'-vvv',
help="Print debugging statements",
action="store_const",
dest="loglevel",
const=logging.INFO, # args.loglevel = 20
default=logging.CRITICAL) # args.loglevel = 50
parser.add_argument(
'-d', '--debug',
help="Print lots of debugging statements",
action="store_const",
dest="loglevel",
const=logging.DEBUG, # args.loglevel = 20
default=logging.CRITICAL) # args.loglevel = 50
parser.add_argument(
'-v', '--verbose',
help="Be verbose",
action="store_const",
dest="loglevel",
const=logging.ERROR) # args.loglevel = 40
parser.add_argument(
'-vv',
help="Be MORE verbose",
action="store_const",
dest="loglevel",
const=logging.WARNING) # args.loglevel = 30
args = parser.parse_args()
pProfile=args.pProfile
pForcedReg=args.pForcedReg
verbose=args.loglevel
logging.basicConfig(level=args.loglevel)
ChildAccounts=Inventory_Modules.find_child_accounts2(pProfile)
if len(ChildAccounts) == 0:
print()
print("The profile {} seems to not represent an Org".format(pProfile))
print("This script only works with org accounts. Sorry.")
print()
sys.exit(1)
##########################
ERASE_LINE = '\x1b[2K'
##########################
print()
sts_session = boto3.Session(profile_name=pProfile)
sts_client = sts_session.client('sts')
AccountsToRegister=[]
AccountsRegistered=0
for account in ChildAccounts:
rolenames=['AWSCloudFormationStackSetExecutionRole', 'OrganizationalFullAccess', 'OrganizationAccountAccessRole', 'AWSControlTowerExecution', 'Owner', 'admin-crossAccount','AdministratorAccess']
# role_arn = "arn:aws:iam::{}:role/AWSCloudFormationStackSetExecutionRole".format(account['AccountId'])
# role_arn = "arn:aws:iam::{}:role/OrganizationalFullAccess".format(account['AccountId'])
# role_arn = "arn:aws:iam::{}:role/AWSControlTowerExecution".format(account['AccountId'])
# role_arn = "arn:aws:iam::{}:role/OrganizationAccountAccessRole".format(account['AccountId'])
# role_arn = "arn:aws:iam::{}:role/Owner".format(account['AccountId'])
# role_arn = "arn:aws:iam::{}:role/admin-crossAccount".format(account['AccountId'])
for rolename in rolenames:
role_arn = "arn:aws:iam::{}:role/{}".format(account['AccountId'], rolename)
logging.info("Role ARN: %s" % role_arn)
try:
AccountErrored = False
account_credentials = sts_client.assume_role(
RoleArn=role_arn,
RoleSessionName="RegistrationScript")['Credentials']
except ClientError as my_Error:
if str(my_Error).find("AuthFailure") > 0:
print(pProfile+": Authorization Failure to account {} using {}".format(account['AccountId'], role_arn))
AccountErrored=True
continue # Try the next rolename
elif str(my_Error).find("AccessDenied") > 0:
print(pProfile+": Authentication Denied to account {} using {}".format(account['AccountId'], role_arn))
AccountErrored=True
continue # Try the next rolename
print(my_Error)
AccountErrored=True
continue # Try the next rolename
logging.warning("Accessed Account %s using rolename %s" % (account['AccountId'],rolename))
AccountIsRegistered=Inventory_Modules.find_if_Isengard_registered(account_credentials)
if AccountIsRegistered and not pForcedReg:
AccountsRegistered+=1
if (not AccountIsRegistered and not AccountErrored) or (pForcedReg and not AccountErrored):
AccountsToRegister.append({
'AccountId':account['AccountId'],
'AccountEmail':account['AccountEmail'],
'AccountCredentials':account_credentials,
'RoleName':rolename
})
break
logging.info("There are %s accounts to register",len(AccountsToRegister))
for account in AccountsToRegister:
print(ERASE_LINE,Fore.RED+"Setting up Account with credentials for Isengard registration: ",account['AccountId'],"Email: ",account['AccountEmail'],"using rolename: ",account['RoleName']+Fore.RESET,end='\r')
aws_session=boto3.Session(
aws_access_key_id = account['AccountCredentials']['AccessKeyId'],
aws_secret_access_key = account['AccountCredentials']['SecretAccessKey'],
aws_session_token = account['AccountCredentials']['SessionToken']
)
iam_client=aws_session.client('iam')
print()
CreateUser=False
DeleteUser=False
try:
# See if user already exists
response = iam_client.get_user(
UserName='Alice'
)
print("Alice already exists!!")
AccessKeyMetadata=iam_client.list_access_keys(
UserName='Alice'
)
DeleteUser=True
except ClientError as my_Error:
if str(my_Error).find("NoSuchEntity") > 0:
print("User wasn't found in this account - so they need to be created")
CreateUser=True
if CreateUser:
try:
# Create User
response = iam_client.create_user(
UserName='Alice'
)
# Create Access Key
response = iam_client.create_access_key(
UserName='Alice'
)['AccessKey']
AccessKeyId=response['AccessKeyId']
SecretAccessKey=response['SecretAccessKey']
# Attach Admin User Policy
response = iam_client.attach_user_policy(
UserName='Alice',
PolicyArn='arn:aws:iam::aws:policy/AdministratorAccess'
)
# Echo info to the screen
print('AccountEmail:',account['AccountEmail'])
print('AccountAccessKey',AccessKeyId)
print('SecretKey:',SecretAccessKey)
# Wait for user input that they're registered the account
DeleteUser=True
except ClientError as my_Error:
if str(my_Error).find("AuthFailure") > 0:
print(pProfile+": Authorization Failure for account {}".format(account['AccountId']))
elif str(my_Error).find("NoSuchEntity") > 0:
print("User wasn't found in this account - ")
else:
print(my_Error)
input("Press Return after you've registered the account in Isengard:")
if DeleteUser:
try:
# Detach admin policy from the user
response = iam_client.detach_user_policy(
UserName='Alice',
PolicyArn='arn:aws:iam::aws:policy/AdministratorAccess'
)
# Delete the access key
if not CreateUser: #The scenario where the user already existed
print("AccessKeyMetadata")
pprint.pprint(AccessKeyMetadata)
for y in range(len(AccessKeyMetadata['AccessKeyMetadata'])):
response = iam_client.delete_access_key(
UserName='Alice',
AccessKeyId=AccessKeyMetadata['AccessKeyMetadata'][y]['AccessKeyId']
)
else: # The scenario where the user was created by this script
response = iam_client.delete_access_key(
UserName='Alice',
AccessKeyId=AccessKeyId
)
# Delete the temp user
response = iam_client.delete_user(
UserName='Alice'
)
print("Alice has been deleted. On to the next account...")
except ClientError as my_Error:
if str(my_Error).find("DeleteConflict") > 0:
response = iam_client.detach_user_policy(
UserName='Alice',
PolicyArn='arn:aws:iam::aws:policy/AdministratorAccess'
)
response = iam_client.delete_access_key(
UserName='Alice',
AccessKeyId=AccessKeyId
)
print(my_Error)
print()
print("Thanks for using the tool.")
print("We found {} accounts under your organization".format(len(ChildAccounts)))
if len(ChildAccounts) == AccountsRegistered:
print("All accounts were already registered with Isengard")
else:
print("{} accounts were already registered with Isengard".format(AccountsRegistered))
print("And we registered {} more of them with Isengard".format(len(AccountsToRegister)))