How to use list_entities_for_policy method in localstack

Best Python code snippet using localstack_python

iam.py

Source:iam.py Github

copy

Full Screen

...169 print('[IAM_007] AdministratorAccess 관리형 정책을 가진 관리자용 IAM 사용자가 존재하는지 확인하시오.')170 check = '?'171 data = {'cli': [], 'raw_data': [], 'summary': []}172 administrator_access = [policy for policy in low_data.policies_only_attached if policy['PolicyName'] == 'AdministratorAccess']173 list_entities_for_policy = client.iam_client.list_entities_for_policy(PolicyArn=administrator_access[0]['Arn'])174 append_data(data, 'aws iam list-entities-for-policy --policy-arn arn:aws:iam::aws:policy/AdministratorAccess',175 {'PolicyUsers': list_entities_for_policy['PolicyUsers'], 'PolicyGroups': list_entities_for_policy['PolicyGroups'], 'PolicyRoles': list_entities_for_policy['PolicyRoles']})176 summary = ''177 if administrator_access:178 if list_entities_for_policy['PolicyGroups']:179 summary += 'Group : ' + str([entity['GroupName'] for entity in list_entities_for_policy['PolicyGroups']]) + '\n'180 if list_entities_for_policy['PolicyUsers']:181 summary += 'Users : ' + str([entity['UserName'] for entity in list_entities_for_policy['PolicyUsers']]) + '\n'182 if list_entities_for_policy['PolicyRoles']:183 summary += 'Roles : ' + str([entity['RoleName'] for entity in list_entities_for_policy['PolicyRoles']]) + '\n'184 if summary:185 append_summary(data, 'AdministratorAccess 관리형 정책이 부여된 IAM 개체는 다음과 같습니다.')186 append_summary(data, summary)187 append_summary(data, '올바른 사용자에게 부여된 권한인지 확인하시오.')188 execute_insert_assessment_result_sql((low_data.diagnosis_id, 'IAM', '007', 'IAM', 'IAM', check, str(data)))189 print('[+] Complete!')190 except Exception as e:191 print('[!] Error :', e)192 def iam_008(self):193 try:194 print('[IAM_008] AWS 계정 설정에 대체 연락처 세부 정보가 설정되어있는지 확인하시오.')195 check = '?'196 data = {'cli': [], 'raw_data': [], 'summary': []}197 append_summary(data, 'AWS 계정 설정에 대체 연락처 세부 정보가 설정되어있는지 AWS Management Console을 통해 확인하시오.')198 execute_insert_assessment_result_sql((low_data.diagnosis_id, 'IAM', '008', 'IAM', 'IAM', check, str(data)))199 print('[+] Complete!')200 except Exception as e:201 print('[!] Error :', e)202 def iam_009(self):203 try:204 print('[IAM_009] AWS 계정 설정에 보안 챌린지 질문 구성이 설정되어있는지 확인하시오.')205 check = '?'206 data = {'cli': [], 'raw_data': [], 'summary': []}207 append_summary(data, 'AWS 계정 설정에 보안 챌린지 질문 구성이 설정되어있는지 AWS Management Console을 통해 확인하시오.')208 execute_insert_assessment_result_sql((low_data.diagnosis_id, 'IAM', '009', 'IAM', 'IAM', check, str(data)))209 print('[+] Complete!')210 except Exception as e:211 print('[!] Error :', e)212 def iam_010(self):213 try:214 print('[IAM_010] IAM 암호 정책이 사용중인지 확인하시오.')215 check = 'Y'216 data = {'cli': [], 'raw_data': [], 'summary': []}217 append_data(data, 'aws iam get-account-password-policy', {'PasswordPolicy': low_data.account_password_policy})218 if not low_data.account_password_policy:219 append_summary(data, '해당 AWS 계정에 IAM 암호 정책이 사용되지 않고 있습니다.')220 if len(data['summary']) > 0:221 check = 'N'222 execute_insert_assessment_result_sql((low_data.diagnosis_id, 'IAM', '010', 'IAM', 'IAM', check, str(data)))223 print('[+] Complete!')224 except Exception as e:225 print('[!] Error :', e)226 def iam_011(self):227 try:228 print('[IAM_011] 강력한 IAM 암호 정책을 설정했는지 확인하시오.')229 check = 'Y'230 data = {'cli': [], 'raw_data': [], 'summary': []}231 if low_data.account_password_policy:232 append_data(data, 'aws iam get-account-password-policy --query \"PasswordPolicy.{RequireUppercaseCharacters:RequireUppercaseCharacters, RequireLowercaseCharacters:RequireLowercaseCharacters, RequireNumbers:RequireNumbers, RequireSymbols:RequireSymbols}\"',233 {'RequireUppercaseCharacters': low_data.account_password_policy['RequireUppercaseCharacters'], 'RequireLowercaseCharacters': low_data.account_password_policy['RequireLowercaseCharacters'],234 'RequireNumbers': low_data.account_password_policy['RequireNumbers'], 'RequireSymbols': low_data.account_password_policy['RequireSymbols']})235 if not low_data.account_password_policy['RequireUppercaseCharacters']:236 append_summary(data, '\"1개 이상의 라틴 알파벨 대문자(A-Z) 필수\" IAM 암호 정책이 설정되어있지 않습니다.')237 if not low_data.account_password_policy['RequireLowercaseCharacters']:238 append_summary(data, '\"1개 이상의 라틴 알파벨 소문자(a-z) 필수\" IAM 암호 정책이 설정되어있지 않습니다.')239 if not low_data.account_password_policy['RequireNumbers']:240 append_summary(data, '\"1개 이상의 숫자 필수\" IAM 암호 정책이 설정되어있지 않습니다.')241 if not low_data.account_password_policy['RequireSymbols']:242 append_summary(data, '\"영숫자를 제외한 문자 1개 이상 필수(!@#$%^&*()_+-=[]{}|)\" IAM 암호 정책이 설정되어있지 않습니다.')243 if len(data['summary']) > 0:244 check = 'N'245 execute_insert_assessment_result_sql((low_data.diagnosis_id, 'IAM', '011', 'IAM', 'IAM', check, str(data)))246 print('[+] Complete!')247 except Exception as e:248 print('[!] Error :', e)249 def iam_012(self):250 try:251 print('[IAM_012] IAM 암호 정책이 14자 이상의 암호를 요구하도록 설정되어있는지 확인하시오.')252 check = 'Y'253 data = {'cli': [], 'raw_data': [], 'summary': []}254 if low_data.account_password_policy:255 append_data(data, 'aws iam get-account-password-policy --query \"PasswordPolicy.{MinimumPasswordLength:MinimumPasswordLength}\"',256 {'MinimumPasswordLength': low_data.account_password_policy['MinimumPasswordLength']})257 if low_data.account_password_policy['MinimumPasswordLength'] < 14:258 append_summary(data, 'IAM 암호 정책이 14자 이상의 암호를 요구하도록 설정되어있지 않습니다.')259 append_summary(data, '현재 최소 암호 길이 : ' + str(low_data.account_password_policy['MinimumPasswordLength']))260 if len(data['summary']) > 0:261 check = 'N'262 execute_insert_assessment_result_sql((low_data.diagnosis_id, 'IAM', '012', 'IAM', 'IAM', check, str(data)))263 print('[+] Complete!')264 except Exception as e:265 print('[!] Error :', e)266 def iam_013(self):267 try:268 print('[IAM_013] IAM 암호 정책이 암호 재사용을 방지하도록 설정되어있는지 확인하시오.')269 check = 'Y'270 data = {'cli': [], 'raw_data': [], 'summary': []}271 if low_data.account_password_policy:272 append_data(data, 'aws iam get-account-password-policy --query \"PasswordPolicy.{PasswordReusePrevention:PasswordReusePrevention}\"',273 {'PasswordReusePrevention': (low_data.account_password_policy['PasswordReusePrevention'] if 'PasswordReusePrevention' in low_data.account_password_policy else 'null')})274 if 'PasswordReusePrevention' not in low_data.account_password_policy:275 append_summary(data, 'IAM 암호 정책이 암호 재사용을 방지하도록 설정되어있지 않습니다.')276 if len(data['summary']) > 0:277 check = 'N'278 execute_insert_assessment_result_sql((low_data.diagnosis_id, 'IAM', '013', 'IAM', 'IAM', check, str(data)))279 print('[+] Complete!')280 except Exception as e:281 print('[!] Error :', e)282 def iam_014(self):283 try:284 print('[IAM_014] IAM 암호 정책이 암호를 90일 이내에 만료하도록 설정했는지 확인하시오.')285 check = 'Y'286 data = {'cli': [], 'raw_data': [], 'summary': []}287 if low_data.account_password_policy:288 append_data(data, 'aws iam get-account-password-policy --query \"PasswordPolicy.{MaxPasswordAge:MaxPasswordAge}\"',289 {'MaxPasswordAge': (low_data.account_password_policy['MaxPasswordAge'] if 'MaxPasswordAge' in low_data.account_password_policy else 'null')})290 if 'MaxPasswordAge' not in low_data.account_password_policy:291 append_summary(data, 'IAM 암호 정책이 암호를 만료하도록 설정되어있지 않습니다.')292 elif low_data.account_password_policy['MaxPasswordAge'] > 90:293 append_summary(data, 'IAM 암호 정책이 90일 이내에 만료하도록 설정되어있지 않습니다.')294 append_summary(data, '현재 암호 만료일 : ' + str(low_data.account_password_policy['MaxPasswordAge']) + '일')295 if len(data['summary']) > 0:296 check = 'N'297 execute_insert_assessment_result_sql((low_data.diagnosis_id, 'IAM', '014', 'IAM', 'IAM', check, str(data)))298 print('[+] Complete!')299 except Exception as e:300 print('[!] Error :', e)301 def iam_016(self):302 try:303 print('[IAM_016] 암호가 만료되거나 만료일이 7일 이내인 IAM 사용자가 존재하는지 확인하시오.')304 for credential in low_data.credential_report:305 if credential['user'] == '<root_account>':306 continue307 if credential['password_last_changed'] == 'N/A' or credential['password_next_rotation'] == 'N/A':308 continue309 check = 'Y'310 data = {'cli': [], 'raw_data': [], 'summary': []}311 append_data(data, 'aws iam generate-credential-report', {})312 append_data(data, 'aws iam get-credential-report', {'user': credential['user'], 'password_next_rotation': credential['password_next_rotation']})313 if (maya.parse(credential['password_next_rotation']).datetime() - datetime.datetime.now(timezone('Asia/Seoul'))).days < 0:314 append_summary(data, credential['user'] + ' 의 암호가 만료된지 ' + str((maya.parse(credential['password_next_rotation']).datetime() - datetime.datetime.now(timezone('Asia/Seoul'))).days * -1) + '일 경과했습니다.')315 elif (maya.parse(credential['password_next_rotation']).datetime() - datetime.datetime.now(timezone('Asia/Seoul'))).days < 7:316 append_summary(data, credential['user'] + ' 의 암호의 만료일이 7일 이내입니다.')317 if len(data['summary']) > 0:318 check = 'N'319 execute_insert_assessment_result_sql((low_data.diagnosis_id, 'IAM', '016', credential['user'], credential['arn'], check, str(data)))320 print('[+] Complete!')321 except Exception as e:322 print('[!] Error :', e)323 def iam_017(self):324 try:325 print('[IAM_017] 사용하지 않는(90일 이내) IAM 자격증명이 존재하는지 확인하시오.')326 for credential in low_data.credential_report:327 check = 'Y'328 data = {'cli': [], 'raw_data': [], 'summary': []}329 append_data(data, 'aws iam generate-credential-report', {})330 append_data(data, 'aws iam get-credential-report', {'user': credential['user'], 'password_enabled': credential['password_enabled'], 'password_last_used': credential['password_last_used'], 'password_last_changed': credential['password_last_changed'],331 'access_key_1_active': credential['access_key_1_active'], 'access_key_1_last_used_date': credential['access_key_1_last_used_date'], 'access_key_1_last_rotated': credential['access_key_1_last_rotated'],332 'access_key_2_active': credential['access_key_2_active'], 'access_key_2_last_used_date': credential['access_key_2_last_used_date'], 'access_key_2_last_rotated': credential['access_key_2_last_rotated']})333 if credential['password_enabled'] == 'true':334 if credential['password_last_used'] == 'no_information':335 if from_now(maya.parse(credential['password_last_changed']).datetime()) > 90:336 append_summary(data, credential['user'] + ' 의 암호가 사용되지 않습니다.')337 else:338 if from_now(maya.parse(credential['password_last_used']).datetime()) > 90:339 append_summary(data, credential['user'] + ' 의 암호가 사용된지가 ' + str(from_now(maya.parse(credential['password_last_used']).datetime())) + '일 경과했습니다.')340 if credential['access_key_1_active'] == 'true':341 if credential['access_key_1_last_used_date'] == 'N/A':342 if from_now(maya.parse(credential['access_key_1_last_rotated']).datetime()) > 90:343 append_summary(data, credential['user'] + ' 의 액세스 키 1번이 사용되지 않습니다.')344 else:345 if from_now(maya.parse(credential['access_key_1_last_used_date']).datetime()) > 90:346 append_summary(data, credential['user'] + ' 의 액세스 키 1번이 사용된지' + str(from_now(maya.parse(credential['access_key_1_last_used_date']).datetime())) + '일 경과했습니다.')347 if credential['access_key_2_active'] == 'true':348 if credential['access_key_2_last_used_date'] == 'N/A':349 if from_now(maya.parse(credential['access_key_2_last_rotated']).datetime()) > 90:350 append_summary(data, credential['user'] + ' 의 액세스 키 2번이 사용되지 않습니다.')351 else:352 if from_now(maya.parse(credential['access_key_2_last_used_date']).datetime()) > 90:353 append_summary(data, credential['user'] + ' 의 액세스 키 2번이 사용된지' + str(from_now(maya.parse(credential['access_key_2_last_used_date']).datetime())) + '일 경과했습니다.')354 if len(data['summary']) > 0:355 check = 'N'356 execute_insert_assessment_result_sql((low_data.diagnosis_id, 'IAM', '017', credential['user'], credential['arn'], check, str(data)))357 print('[+] Complete!')358 except Exception as e:359 print('[!] Error :', e)360 def iam_018(self):361 try:362 print('[IAM_018] IAM 사용자 생성과정에서 액세스 키가 생성되는지 확인하시오.')363 for credential in low_data.credential_report:364 if credential['user'] == '<root_account>':365 continue366 check = 'Y'367 data = {'cli': [], 'raw_data': [], 'summary': []}368 append_data(data, 'aws iam generate-credential-report', {})369 append_data(data, 'aws iam get-credential-report', {'user': credential['user'], 'user_creation_time': credential['user_creation_time'], 'access_key_1_last_rotated': credential['access_key_1_last_rotated'],370 'access_key_2_last_rotated': credential['access_key_2_last_rotated']})371 if credential['access_key_1_last_rotated'] != 'N/A':372 if (maya.parse(credential['access_key_1_last_rotated']) - maya.parse(credential['user_creation_time'])).seconds <= 1:373 append_summary(data, credential['user'] + ' 의 액세스 키 1번이 IAM 사용자 생성과정에서 생성되었습니다.')374 if credential['access_key_2_last_rotated'] != 'N/A':375 if (maya.parse(credential['access_key_2_last_rotated']) - maya.parse(credential['user_creation_time'])).seconds <= 1:376 append_summary(data, credential['user'] + ' 의 액세스 키 2번이 IAM 사용자 생성과정에서 생성되었습니다.')377 if len(data['summary']) > 0:378 check = 'N'379 execute_insert_assessment_result_sql((low_data.diagnosis_id, 'IAM', '018', credential['user'], credential['arn'], check, str(data)))380 print('[+] Complete!')381 except Exception as e:382 print('[!] Error :', e)383 def iam_019(self):384 try:385 print('[IAM_019] IAM 사용자의 액세스 키가 30일 이내에 재발급되었는지 확인하시오.')386 for credential in low_data.credential_report:387 if credential['user'] == '<root_account>':388 continue389 check = 'Y'390 data = {'cli': [], 'raw_data': [], 'summary': []}391 append_data(data, 'aws iam generate-credential-report', {})392 append_data(data, 'aws iam get-credential-report', {'user': credential['user'], 'access_key_1_active': credential['access_key_1_active'], 'access_key_1_last_rotated': credential['access_key_1_last_rotated'],393 'access_key_2_active': credential['access_key_2_active'], 'access_key_2_last_rotated': credential['access_key_2_last_rotated']})394 if credential['access_key_1_active'] == 'true' and from_now(maya.parse(credential['access_key_1_last_rotated']).datetime()) >= 30:395 append_summary(data, credential['user'] + ' 의 액세스 키 1번이 30일 이내에 재발급되지 않았습니다.')396 if credential['access_key_2_active'] == 'true' and from_now(maya.parse(credential['access_key_2_last_rotated']).datetime()) >= 30:397 append_summary(data, credential['user'] + ' 의 액세스 키 2번이 30일 이내에 재발급되지 않았습니다.')398 if len(data['summary']) > 0:399 check = 'N'400 execute_insert_assessment_result_sql((low_data.diagnosis_id, 'IAM', '019', credential['user'], credential['arn'], check, str(data)))401 print('[+] Complete!')402 except Exception as e:403 print('[!] Error :', e)404 def iam_020(self):405 try:406 print('[IAM_020] 2개의 액세스 키가 활성화된 IAM 사용자가 존재하는지 확인하시오.')407 for credential in low_data.credential_report:408 check = 'Y'409 data = {'cli': [], 'raw_data': [], 'summary': []}410 append_data(data, 'aws iam generate-credential-report', {})411 append_data(data, 'aws iam get-credential-report', {'user': credential['user'], 'access_key_1_active': credential['access_key_1_active'], 'access_key_2_active': credential['access_key_2_active']})412 if credential['access_key_1_active'] == 'true' and credential['access_key_2_active'] == 'true':413 append_summary(data, credential['user'] + ' 의 2개의 액세스 키가 활성화되어 있습니다.')414 if len(data['summary']) > 0:415 check = 'N'416 execute_insert_assessment_result_sql((low_data.diagnosis_id, 'IAM', '020', credential['user'], credential['arn'], check, str(data)))417 print('[+] Complete!')418 except Exception as e:419 print('[!] Error :', e)420 def iam_021(self):421 try:422 print('[IAM_021] 2개의 SSH Public Key가 활성화된 IAM 사용자가 존재하는지 확인하시오.')423 for user in low_data.users:424 check = 'Y'425 data = {'cli': [], 'raw_data': [], 'summary': []}426 append_data(data, 'aws iam list-ssh-public-keys --user-name ' + user['UserName'], {'SSHPublicKeys': low_data.ssh_public_keys[user['UserName']]})427 active_count = 0428 if len([ssh_public_key for ssh_public_key in low_data.ssh_public_keys[user['UserName']] if ssh_public_key['Status'] == 'Active']) > 1:429 append_summary(data, user['UserName'] + ' 이 SSH Public Key가 ' + str(active_count) + '개 활성화되어 있습니다.')430 if len(data['summary']) > 0:431 check = 'N'432 execute_insert_assessment_result_sql((low_data.diagnosis_id, 'IAM', '021', user['UserName'], user['Arn'], check, str(data)))433 print('[+] Complete!')434 except Exception as e:435 print('[!] Error :', e)436 def iam_022(self):437 try:438 print('[IAM_022] SSH Public Key가 90일 이내에 재발급되었는지 확인하시오.')439 for user in low_data.users:440 check = 'Y'441 data = {'cli': [], 'raw_data': [], 'summary': []}442 append_data(data, 'aws iam list-ssh-public-keys --user-name ' + user['UserName'], {'SSHPublicKeys': low_data.ssh_public_keys[user['UserName']]})443 for ssh_public_key in low_data.ssh_public_keys[user['UserName']]:444 if from_now(ssh_public_key['UploadDate']) >= 90:445 append_summary(data, user['UserName'] + ' 의 SSH Public Key(' + ssh_public_key['SSHPublicKeyId'] + ' )가 재발급된지 ' + str(from_now(ssh_public_key['UploadDate'])) + '일 경과했습니다.')446 if len(data['summary']) > 0:447 check = 'N'448 execute_insert_assessment_result_sql((low_data.diagnosis_id, 'IAM', '022', user['UserName'], user['Arn'], check, str(data)))449 print('[+] Complete!')450 except Exception as e:451 print('[!] Error :', e)452 def iam_023(self):453 try:454 print('[IAM_023] 모든 IAM 사용자의 MFA가 활성화되어 있는지 확인하시오.')455 for credential in low_data.credential_report:456 if credential['user'] == '<root_account>':457 continue458 check = 'Y'459 data = {'cli': [], 'raw_data': [], 'summary': []}460 append_data(data, 'aws iam generate-credential-report', {})461 append_data(data, 'aws iam get-credential-report', {'user': credential['user'], 'mfa_active': credential['mfa_active']})462 if credential['mfa_active'] == 'false':463 append_summary(data, credential['user'] + ' 의 MFA가 비활성화되어 있습니다.')464 if len(data['summary']) > 0:465 check = 'N'466 execute_insert_assessment_result_sql((low_data.diagnosis_id, 'IAM', '023', credential['user'], credential['arn'], check, str(data)))467 print('[+] Complete!')468 except Exception as e:469 print('[!] Error :', e)470 def iam_024(self):471 try:472 print('[IAM_024] IAM 사용자에 연결된 IAM 정책이 존재하는지 확인하시오.')473 for user in low_data.users:474 check = 'Y'475 data = {'cli': [], 'raw_data': [], 'summary': []}476 append_data(data, 'aws iam list-attached-user-policies --user-name ' + user['UserName'], {'AttachedPolicies': low_data.attached_user_policies[user['UserName']]})477 if low_data.attached_user_policies[user['UserName']]:478 append_summary(data, user['UserName'] + ' 에 연결된 IAM 정책이 ' + str(len(low_data.attached_user_policies[user['UserName']])) + '개 있습니다.')479 if len(data['summary']) > 0:480 check = 'N'481 execute_insert_assessment_result_sql((low_data.diagnosis_id, 'IAM', '024', user['UserName'], user['Arn'], check, str(data)))482 print('[+] Complete!')483 except Exception as e:484 print('[!] Error :', e)485 def iam_025(self):486 try:487 print('[IAM_025] 사용하지 않는 IAM 사용자가 존재하는지 확인하시오.')488 for user in low_data.users:489 check = 'Y'490 data = {'cli': [], 'raw_data': [], 'summary': []}491 append_data(data, 'aws iam list_users --filter Name=user-name,Values=' + user['UserName'], {'UserName': user['UserName'], 'PasswordLastUsed': (str(user['PasswordLastUsed']) if 'PasswordLastUsed' in user else 'null')})492 if 'PasswordLastUsed' not in user or from_now(user['PasswordLastUsed']) >= 90:493 active_access_keys = list(filter(lambda access_key: access_key['Status'] == 'Active', low_data.access_keys[user['UserName']]))494 append_data(data, 'aws iam list-access-keys --user-name=' + user['UserName'] + ' --query \"{AccessKeyMetadata:AccessKeyMetadata[*].{UserName:UserName, Status:Status, AccessKeyId:AccessKeyId}}\"',495 {'AccessKeyMetadata': [{'UserName': active_access_key['UserName'], 'Status': active_access_key['Status'], 'AccessKeyId': active_access_key['AccessKeyId']} for active_access_key in active_access_keys]})496 active_count = 0497 for active_access_key in active_access_keys:498 access_key_last_used = client.iam_client.get_access_key_last_used(AccessKeyId=active_access_key['AccessKeyId'])499 append_data(data, 'aws iam get-access-key-last-used --access-key-id=' + active_access_key['AccessKeyId'], {'UserName': access_key_last_used['UserName'],500 'AccessKeyLastUsed': {'Region': access_key_last_used['AccessKeyLastUsed']['Region'], 'ServiceName': access_key_last_used['AccessKeyLastUsed']['ServiceName'],501 'LastUsedDate': str(access_key_last_used['AccessKeyLastUsed']['LastUsedDate'])}})502 if 'LastUsedDate' in access_key_last_used['AccessKeyLastUsed'] and \503 from_now(access_key_last_used['AccessKeyLastUsed']['LastUsedDate']) < 90:504 active_count += 1505 if active_count == 0:506 append_summary(data, user['UserName'] + ' 은 사용되지 않습니다.')507 if len(data['summary']) > 0:508 check = 'N'509 execute_insert_assessment_result_sql((low_data.diagnosis_id, 'IAM', '025', user['UserName'], user['Arn'], check, str(data)))510 print('[+] Complete!')511 except Exception as e:512 print('[!] Error :', e)513 def iam_026(self):514 try:515 print('[IAM_026] 인라인 정책이 있는 IAM 사용자 혹은 그룹이 존재하는지 확인하시오.')516 for user in low_data.users:517 check = 'Y'518 data = {'cli': [], 'raw_data': [], 'summary': []}519 append_data(data, 'aws iam list-user-policies --user-name ' + user['UserName'], {'AttachedPolicies': low_data.user_policies[user['UserName']]})520 if low_data.user_policies[user['UserName']]:521 append_summary(data, 'IAM 사용자 ' + user['UserName'] + ' 에 인라인 정책이 ' + str(len(low_data.user_policies[user['UserName']])) + '개 연결되어 있습니다.')522 if len(data['summary']) > 0:523 check = 'N'524 execute_insert_assessment_result_sql((low_data.diagnosis_id, 'IAM', '026', user['UserName'], user['Arn'], check, str(data)))525 for group in low_data.groups:526 check = 'Y'527 data = {'cli': [], 'raw_data': [], 'summary': []}528 append_data(data, 'aws iam list-group-policies --group-name ' + group['GroupName'], {'AttachedPolicies': low_data.group_policies[group['GroupName']]})529 if low_data.group_policies[group['GroupName']]:530 append_summary(data, 'IAM 그룹 ' + group['GroupName'] + ' 에 인라인 정책이 ' + str(len(low_data.group_policies[group['GroupName']])) + '개 연결되어 있습니다.')531 if len(data['summary']) > 0:532 check = 'N'533 execute_insert_assessment_result_sql((low_data.diagnosis_id, 'IAM', '026', group['GroupName'], group['Arn'], check, str(data)))534 for role in low_data.roles:535 check = 'Y'536 data = {'cli': [], 'raw_data': [], 'summary': []}537 append_data(data, 'aws iam list-role-policies --role-name ' + role['RoleName'], {'AttachedPolicies': low_data.role_policies[role['RoleName']]})538 if low_data.role_policies[role['RoleName']]:539 append_summary(data, 'IAM 역할 ' + role['RoleName'] + ' 에 인라인 정책이 ' + str(len(low_data.role_policies[role['RoleName']])) + '개 연결되어 있습니다.')540 if len(data['summary']) > 0:541 check = 'N'542 execute_insert_assessment_result_sql((low_data.diagnosis_id, 'IAM', '026', role['RoleName'], role['Arn'], check, str(data)))543 print('[+] Complete!')544 except Exception as e:545 print('[!] Error :', e)546 def iam_027(self):547 try:548 print('[IAM_027] 사용하지 않는 IAM 그룹이 존재하는지 확인하시오.')549 for group in low_data.groups:550 check = 'Y'551 data = {'cli': [], 'raw_data': [], 'summary': []}552 get_group = client.iam_client.get_paginator('get_group').paginate(GroupName=group['GroupName'])553 users_in_group = [group_user for group_info in get_group for group_user in group_info['Users']]554 append_data(data, 'aws iam get-group --group-name ' + group['GroupName'] + ' --query \"{Users:Users[*].{UserName:UserName, UserId:UserId}}\"',555 {'Users': [{'UserName': user_in_group['UserName'], 'UserId': user_in_group['UserId']} for user_in_group in users_in_group]})556 if not users_in_group:557 append_summary(data, group['GroupName'] + ' 은 사용되지 않습니다.')558 if len(data['summary']) > 0:559 check = 'N'560 execute_insert_assessment_result_sql((low_data.diagnosis_id, 'IAM', '027', group['GroupName'], group['Arn'], check, str(data)))561 print('[+] Complete!')562 except Exception as e:563 print('[!] Error :', e)564 def iam_028(self):565 try:566 print('[IAM_028] IAM 정책을 수정/삭제할 수 있는 비인가된 IAM 사용자가 존재하는지 확인하시오.')567 policies = ['iam:CreatePolicy', 'iam:CreatePolicyVersion', 'iam:DeleteGroupPolicy', 'iam:DeletePolicy', 'iam:DeleteRolePolicy', 'iam:DeleteUserPolicy', 'iam:DetachGroupPolicy',568 'iam:DetachRolePolicy', 'iam:DetachUserPolicy', 'iam:PutGroupPolicy', 'iam:PutRolePolicy', 'iam:PutUserPolicy', 'iam:UpdateAssumeRolePolicy']569 check = 'Y'570 data = {'cli': [], 'raw_data': [], 'summary': []}571 # 구현 방법에 대해 이야기572 print('[+] Complete!')573 except Exception as e:574 print('[!] Error :', e)575 def iam_029(self):576 try:577 print('[IAM_029] AWSCloudTrail_FullAccess 정책이 한 개 이상의 IAM Entity에 부여되어있는지 확인하시오.')578 check = 'Y'579 data = {'cli': [], 'raw_data': [], 'summary': []}580 aws_cloudtrail_full_access = list(filter(lambda policy: policy['PolicyName'] == 'AWSCloudTrail_FullAccess', low_data.policies_only_attached))581 summary = ''582 if aws_cloudtrail_full_access:583 list_entities_for_policy = client.iam_client.list_entities_for_policy(PolicyArn=aws_cloudtrail_full_access[0]['Arn'])584 append_data(data, 'aws iam list-entries-for-policy --policy-arn ' + aws_cloudtrail_full_access[0]['Arn'],585 {'PolicyGroups': list_entities_for_policy['PolicyGroups'], 'PolicyUsers': list_entities_for_policy['PolicyUsers'], 'PolicyRoles': list_entities_for_policy['PolicyRoles']})586 if list_entities_for_policy['PolicyGroups']:587 summary += 'Group : ' + str([entity['GroupName'] for entity in list_entities_for_policy['PolicyGroups']]) + '\n'588 if list_entities_for_policy['PolicyUsers']:589 summary += 'Users : ' + str([entity['UserName'] for entity in list_entities_for_policy['PolicyUsers']]) + '\n'590 if list_entities_for_policy['PolicyRoles']:591 summary += 'Roles : ' + str([entity['RoleName'] for entity in list_entities_for_policy['PolicyRoles']]) + '\n'592 if summary:593 append_summary(data, 'AWSCloudTrail_FullAccess 관리형 정책이 부여된 IAM 개체는 다음과 같습니다.')594 append_summary(data, summary)595 append_summary(data, '올바르게 부여된 권한인지 확인하시오.')596 execute_insert_assessment_result_sql((low_data.diagnosis_id, 'IAM', '029', 'IAM', 'IAM', check, str(data)))597 print('[+] Complete!')598 except Exception as e:599 print('[!] Error :', e)600 def iam_030(self):601 try:602 print('[IAM_030] 모든 Action(*)를 허용하는 IAM 정책이 존재하는지 확인하시오.')603 for policy in low_data.policies_local:604 check = 'Y'605 data = {'cli': [], 'raw_data': [], 'summary': []}606 append_data(data, 'aws iam list-policies --scope Local --query \"Policies[*].{PolicyName:PolicyName, PolicyId:PolicyId, DefaultVersionId:DefaultVersionId, Arn:Arn}\"',607 {'PolicyName': policy['PolicyName'], 'PolicyId': policy['PolicyId'], 'DefaultVersionId': policy['DefaultVersionId'], 'Arn':policy['Arn']})608 get_policy_version = client.iam_client.get_policy_version(PolicyArn=policy['Arn'], VersionId=policy['DefaultVersionId'])609 append_data(data, 'aws iam get-policy-version --policy-arn ' + policy['Arn'] + ' --version-id ' + policy['DefaultVersionId'] + ' --query \"PolicyVersion.{VersionId:VersionId, Document:Document}\"',610 {'VersionId': get_policy_version['PolicyVersion']['VersionId'], 'Document': get_policy_version['PolicyVersion']['Document']})611 if type(get_policy_version['PolicyVersion']['Document']['Statement']) == list:612 if [statement for statement in get_policy_version['PolicyVersion']['Document']['Statement'] if statement['Effect'] == 'Allow' and '*' in statement['Action']]:613 append_summary(data, policy['PolicyName'] + ' 정책에서 모든 Action(*)을 허용합니다.')614 elif type(get_policy_version['PolicyVersion']['Document']['Statement']) == dict:615 if get_policy_version['PolicyVersion']['Document']['Statement']['Effect'] == 'Allow' and '*' in get_policy_version['PolicyVersion']['Document']['Statement']['Action']:616 append_summary(data, policy['PolicyName'] + ' 정책에서 모든 Action(*)을 허용합니다.')617 if len(data['summary']) > 0:618 check = 'N'619 execute_insert_assessment_result_sql((low_data.diagnosis_id, 'IAM', '030', policy['PolicyName'], policy['Arn'], check, str(data)))620 print('[+] Complete!')621 except Exception as e:622 print('[!] Error :', e)623 def iam_031(self):624 try:625 print('[IAM_031] Effect:"Allow"와 "NotAction"을 함께 사용하는 IAM 정책이 존재하는지 확인하시오.')626 for policy in low_data.policies_local:627 check = 'Y'628 data = {'cli': [], 'raw_data': [], 'summary': []}629 append_data(data, 'aws iam list-policies --scope Local --query \"Policies[*].{PolicyName:PolicyName, PolicyId:PolicyId, DefaultVersionId:DefaultVersionId, Arn:Arn}\"',630 {'PolicyName': policy['PolicyName'], 'PolicyId': policy['PolicyId'], 'DefaultVersionId': policy['DefaultVersionId'], 'Arn': policy['Arn']})631 get_policy_version = client.iam_client.get_policy_version(PolicyArn=policy['Arn'], VersionId=policy['DefaultVersionId'])632 append_data(data, 'aws iam get-policy-version --policy-arn ' + policy['Arn'] + ' --version-id ' + policy['DefaultVersionId'] + ' --query \"PolicyVersion.{VersionId:VersionId, Document:Document}\"',633 {'VersionId': get_policy_version['PolicyVersion']['VersionId'], 'Document': get_policy_version['PolicyVersion']['Document']})634 document = get_policy_version['PolicyVersion']['Document']635 if type(document['Statement']) == list:636 if [statement for statement in document['Statement'] if statement['Effect'] == 'Allow' and 'NotAction' in statement]:637 append_summary(data, policy['PolicyName'] + ' 정책에 \"Effect\":\"Allow\"와 \"NotAction\"을 함께 사용합니다.')638 elif type(document['Statement']) == dict:639 if document['Statement']['Effect'] == 'Allow' and 'NotAction' in document['Statement']:640 append_summary(data, policy['PolicyName'] + ' 정책에 \"Effect\":\"Allow\"와 \"NotAction\"을 함께 사용합니다.')641 if len(data['summary']) > 0:642 check = 'N'643 execute_insert_assessment_result_sql((low_data.diagnosis_id, 'IAM', '031', policy['PolicyName'], policy['Arn'], check, str(data)))644 for user in low_data.users:645 check = 'Y'646 data = {'cli': [], 'raw_data': [], 'summary': []}647 append_data(data, 'aws iam list-user-policies --user-name ' + user['UserName'], {'PolicyNames': low_data.user_policies[user['UserName']]})648 for user_policy in low_data.user_policies[user['UserName']]:649 statements = client.iam_client.get_user_policy(UserName=user['UserName'], PolicyName=user_policy)650 append_data(data, 'aws iam get-user-policy --user-name ' + user['UserName'] + ' --policy-name ' + user_policy,651 {'UserName': statements['UserName'], 'PolicyName': statements['PolicyName'], 'PolicyDocument': statements['PolicyDocument']})652 if [statement for statement in statements['PolicyDocument']['Statement'] if statement['Effect'] == 'Allow' and 'NotAction' in statement]:653 append_summary(data, user['UserName'] + ' 사용자의 ' + user_policy + ' 인라인정책에 \"Effect\":\"Allow\"와 \"NotAction\"을 함께 사용합니다.')654 if len(data['summary']) > 0:655 check = 'N'656 execute_insert_assessment_result_sql((low_data.diagnosis_id, 'IAM', '031', user['UserName'], user['Arn'], check, str(data)))657 for group in low_data.groups:658 check = 'Y'659 data = {'cli': [], 'raw_data': [], 'summary': []}660 append_data(data, 'aws iam list-group-policies --group-name ' + group['GroupName'], {'PolicyNames': low_data.group_policies[group['GroupName']]})661 for group_policy in low_data.group_policies[group['GroupName']]:662 statements = client.iam_client.get_group_policy(GroupName=group['GroupName'], PolicyName=group_policy)663 append_data(data, 'aws iam get-group-policy --group-name ' + group['GroupName'] + ' --policy-name ' + group_policy,664 {'GroupName': statements['GroupName'], 'PolicyName': statements['PolicyName'], 'PolicyDocument': statements['PolicyDocument']})665 if [statement for statement in statements['PolicyDocument']['Statement'] if statement['Effect'] == 'Allow' and 'NotAction' in statement]:666 append_summary(data, group['GroupName'] + ' 그룹의 ' + group_policy + ' 인라인정책에 \"Effect\":\"Allow\"와 \"NotAction\"을 함께 사용합니다.')667 if len(data['summary']) > 0:668 check = 'N'669 execute_insert_assessment_result_sql((low_data.diagnosis_id, 'IAM', '031', group['GroupName'], group['Arn'], check, str(data)))670 for role in low_data.roles:671 check = 'Y'672 data = {'cli': [], 'raw_data': [], 'summary': []}673 append_data(data, 'aws iam list-role-policies --role-name ' + role['RoleName'], {'PolicyNames': low_data.role_policies[role['RoleName']]})674 for role_policy in low_data.role_policies[role['RoleName']]:675 statements = client.iam_client.get_role_policy(RoleName=role['RoleName'], PolicyName=role_policy)676 append_data(data, 'aws iam get-role-policy --role-name ' + role['RoleName'] + ' --policy-name ' + role_policy,677 {'RoleName': statements['RoleName'], 'PolicyName': statements['PolicyName'], 'PolicyDocument': statements['PolicyDocument']})678 if [statement for statement in statements['PolicyDocument']['Statement'] if statement['Effect'] == 'Allow' and 'NotAction' in statement]:679 append_summary(data, role['RoleName'] + ' 역할의 ' + role_policy + ' 인라인정책에 \"Effect\":\"Allow\"와 \"NotAction\"을 함께 사용합니다.')680 if len(data['summary']) > 0:681 check = 'N'682 execute_insert_assessment_result_sql((low_data.diagnosis_id, 'IAM', '031', role['RoleName'], role['Arn'], check, str(data)))683 print('[+] Complete!')684 except Exception as e:685 print('[!] Error :', e)686 def iam_032(self):687 try:688 print('[IAM_032] AWSSupportAccess 정책을 가지는 IAM 역할이 존재하는지 확인하시오.')689 check = 'Y'690 data = {'cli': [], 'raw_data': [], 'summary': []}691 aws_support_access = [policy for policy in low_data.policies_only_attached if policy['PolicyName'] == 'AWSSupportAccess']692 if aws_support_access:693 list_entities_for_policy = client.iam_client.list_entities_for_policy(PolicyArn=aws_support_access[0]['Arn'])694 append_data(data, 'aws iam list-entries-for-policy --policy-arn ' + aws_support_access[0]['Arn'] + ' --query \"{PolicyRoles:PolicyRoles}\"',695 {'PolicyRoles': list_entities_for_policy['PolicyRoles']})696 if not list_entities_for_policy['PolicyRoles']:697 append_summary(data, 'AWSSupportAccess 관리형 정책이 부여된 IAM 역할이 존재하지 않습니다.')698 if len(data['summary']) > 0:699 check = 'N'700 execute_insert_assessment_result_sql((low_data.diagnosis_id, 'IAM', '032', 'IAM', 'IAM', check, str(data)))701 print('[+] Complete!')702 except Exception as e:703 print('[!] Error :', e)704 def iam_033(self):705 try:706 print('[IAM_033] 보안그룹, NACL, 흐름로그를 생성하고 관리할 수 있는 권한이 과도하게 부여되어있지 않은지 확인하시오.')707 policies = ['ec2:CreateSecurityGroup', 'ec2:DeleteSecurityGroup', 'ec2:AuthorizeSecurityGroupIngress', 'ec2:AuthorizeSecurityGroupEgress',...

Full Screen

Full Screen

test_list_entities_for_policy.py

Source:test_list_entities_for_policy.py Github

copy

Full Screen

...36 # mock API list_entities_for_policy37 with patch.object(client_connect_iam,38 'list_entities_for_policy') as mock_method:39 mock_method.return_value = {}40 actual_list_entities_for_policy = IAMUtils.list_entities_for_policy(41 trace_id, session, aws_account, policy_arn)42 # check response43 self.assertEqual(expected_list_entities_for_policy,44 actual_list_entities_for_policy)45 # check connect client46 mock_method_client.assert_any_call(service_name="iam")47 def test_list_entities_for_policy_success_response_is_truncated_false(self):48 expected_list_entities_for_policy = copy.deepcopy(49 DataTestIAM.DATA_LIST_ENTITIES_FOR_POLICY_IS_TRUNCATED_FALSE)50 # mock client51 with patch.object(session, 'client') as mock_method_client:52 mock_method_client.return_value = client_connect_iam53 # mock response API list_entities_for_policy54 with patch.object(client_connect_iam,55 'list_entities_for_policy') as mock_method:56 mock_method.return_value = expected_list_entities_for_policy57 actual_list_entities_for_policy = IAMUtils.list_entities_for_policy(58 trace_id, session, aws_account, policy_arn)59 # check response60 self.assertEqual(expected_list_entities_for_policy['PolicyGroups'],61 actual_list_entities_for_policy['PolicyGroups'])62 self.assertEqual(expected_list_entities_for_policy['PolicyUsers'],63 actual_list_entities_for_policy['PolicyUsers'])64 self.assertEqual(expected_list_entities_for_policy['PolicyRoles'],65 actual_list_entities_for_policy['PolicyRoles'])66 # check connect client67 mock_method_client.assert_any_call(service_name="iam")68 # check call API list_entities_for_policy69 mock_method.assert_any_call(PolicyArn=policy_arn)70 def test_list_entities_for_policy_success_response_is_truncated_true(self):71 expected_list_entities_for_policy = copy.deepcopy(72 DataTestIAM.LIST_ENTITIES_FOR_POLICY_DATA)73 # mock client74 with patch.object(session, 'client') as mock_method_client:75 mock_method_client.return_value = client_connect_iam76 # mock response API list_entities_for_policy77 with patch.object(client_connect_iam,78 'list_entities_for_policy') as mock_method:79 mock_method.side_effect = iam_utils.side_effect_list_entities_for_policy80 actual_list_entities_for_policy = IAMUtils.list_entities_for_policy(81 trace_id, session, aws_account, policy_arn)82 # check response83 self.assertEqual(expected_list_entities_for_policy['PolicyGroups'],84 actual_list_entities_for_policy['PolicyGroups'])85 self.assertEqual(expected_list_entities_for_policy['PolicyUsers'],86 actual_list_entities_for_policy['PolicyUsers'])87 self.assertEqual(expected_list_entities_for_policy['PolicyRoles'],88 actual_list_entities_for_policy['PolicyRoles'])89 # check connect client90 mock_method_client.assert_any_call(service_name="iam")91 # check call API list_entities_for_policy92 mock_method.assert_any_call(PolicyArn=policy_arn)93 def test_list_entities_for_policy_error_connect_iam(self):94 expected_error_response = copy.deepcopy(DataCommon.ERROR_RESPONSE)95 expected_operation_name = copy.deepcopy(DataCommon.OPERATION_NAME)96 # mock error client97 with patch.object(session, 'client') as mock_method:98 mock_method.side_effect = ClientError(99 error_response=expected_error_response,100 operation_name=expected_operation_name)101 with patch.object(102 PmLogAdapter, 'error',103 return_value=None) as mock_method_error:104 with self.assertRaises(PmError) as exception:105 IAMUtils.list_entities_for_policy(trace_id, session,106 aws_account, policy_arn)107 # check error108 actual_cause_error = exception.exception.cause_error109 self.assertEqual(expected_error_response['Error'],110 actual_cause_error.response['Error'])111 self.assertEqual(expected_operation_name,112 actual_cause_error.operation_name)113 # check message log error114 mock_method_error.assert_any_call("[%s] IAMクライアント作成に失敗しました。",115 aws_account)116 def test_list_entities_for_policy_error_call_list_entities_for_policy(self):117 expected_error_response = copy.deepcopy(DataCommon.ERROR_RESPONSE)118 expected_operation_name = copy.deepcopy(DataCommon.OPERATION_NAME)119 # mock client120 with patch.object(session, 'client') as mock_client:121 mock_client.return_value = client_connect_iam122 # mock error call API list_entities_for_policy123 with patch.object(client_connect_iam,124 'list_entities_for_policy') as mock_method:125 mock_method.side_effect = ClientError(126 error_response=expected_error_response,127 operation_name=expected_operation_name)128 with patch.object(129 PmLogAdapter, 'error',130 return_value=None) as mock_method_error:131 with self.assertRaises(PmError) as exception:132 IAMUtils.list_entities_for_policy(133 trace_id, session, aws_account, policy_arn)134 # check error135 actual_cause_error = exception.exception.cause_error136 self.assertEqual(expected_error_response['Error'],137 actual_cause_error.response['Error'])138 self.assertEqual(expected_operation_name,139 actual_cause_error.operation_name)140 # check message log error141 mock_method_error.assert_any_call("[%s]ポリシーエンティティ情報の取得に失敗しました。(%s)",...

Full Screen

Full Screen

breakglass_aws_detach_policy.py

Source:breakglass_aws_detach_policy.py Github

copy

Full Screen

1# Author Jason Little2# Quick and simple script to detach the AdministratorAccess policy from all users3import boto34client = boto3.client('iam')5users = client.list_entities_for_policy(PolicyArn="arn:aws:iam::aws:policy/AdministratorAccess")6for i in users["PolicyUsers"]:...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run localstack automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful