com.amazonaws.services.identitymanagement.model.Role Java Examples

The following examples show how to use com.amazonaws.services.identitymanagement.model.Role. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: InventoryUtil.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * Fetch IAM roles.
 *
 * @param temporaryCredentials the temporary credentials
 * @param accountId the accountId
 * @param accountName the account name
 * @return the map
 */
public static  Map<String,List<Role>>  fetchIAMRoles(BasicSessionCredentials temporaryCredentials,String accountId,String accountName) {

	AmazonIdentityManagement iamClient = AmazonIdentityManagementClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(temporaryCredentials)).withRegion(InventoryConstants.REGION_US_WEST_2).build();
	List<Role> roles = new ArrayList<>();
	ListRolesResult rslt;
	String marker = null;
	do{
		rslt =  iamClient.listRoles(new ListRolesRequest().withMarker(marker));
		roles.addAll(rslt.getRoles());
		marker = rslt.getMarker();
	}while(marker!=null);

	log.debug(InventoryConstants.ACCOUNT + accountId +" Type : IAM Roles >> "+roles.size());
	Map<String,List<Role>> iamRoles = new HashMap<>();
	iamRoles.put(accountId+delimiter+accountName, roles);
	return iamRoles;
}
 
Example #2
Source File: AwsIamServiceTest.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetAssumeRolePolicyDocument() throws IOException {
    String assumeRolePolicyDocument = awsIamService.getResourceFileAsString(
            "json/aws-assume-role-policy-document.json");
    String encodedAssumeRolePolicyDocument = URLEncoder.encode(assumeRolePolicyDocument,
            StandardCharsets.UTF_8);


    Statement statement = new Statement(Effect.Allow).withId("1")
            .withPrincipals(new Principal("AWS", "arn:aws:iam::123456890:role/assume-role"))
            .withActions(SecurityTokenServiceActions.AssumeRole);
    Policy expectedAssumeRolePolicy = new Policy().withStatements(statement);

    Role role = mock(Role.class);
    when(role.getAssumeRolePolicyDocument()).thenReturn(encodedAssumeRolePolicyDocument);

    Policy assumeRolePolicy = awsIamService.getAssumeRolePolicy(role);
    assertThat(assumeRolePolicy).isNotNull();
    assertThat(assumeRolePolicy.toJson()).isEqualTo(expectedAssumeRolePolicy.toJson());
}
 
Example #3
Source File: AwsIDBrokerAssumeRoleValidatorTest.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@Test
public void checkCannotAssumeRoles() {
    Role instanceProfileRole = new Role();
    InstanceProfile instanceProfile = new InstanceProfile().withArn("instanceProfileArn")
            .withRoles(instanceProfileRole);

    Role role = new Role().withArn("roleArn");
    Collection<Role> roles = Collections.singletonList(role);

    EvaluationResult evalResult = new EvaluationResult()
            .withEvalDecision(PolicyEvaluationDecisionType.ImplicitDeny);
    when(iam.simulatePrincipalPolicy(any(SimulatePrincipalPolicyRequest.class)))
            .thenReturn(new SimulatePrincipalPolicyResult().withEvaluationResults(evalResult));

    ValidationResultBuilder validationResultBuilder = new ValidationResultBuilder();
    assertThat(awsIDBrokerAssumeRoleValidator.canAssumeRoles(iam, instanceProfile, roles,
            validationResultBuilder)).isFalse();
    ValidationResult validationResult = validationResultBuilder.build();
    assertThat(validationResult.hasError()).isTrue();
    assertThat(validationResult.getErrors()).isEqualTo(Collections.singletonList(
            String.format("IDBroker instance profile (%s) doesn't have permissions to assume the role(s): %s",
                    instanceProfile.getArn(), Collections.singletonList(role.getArn()))));
}
 
Example #4
Source File: AwsIDBrokerAssumeRoleValidatorTest.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@Test
public void checkCanAssumeRoles() {
    Role instanceProfileRole = new Role();
    InstanceProfile instanceProfile = new InstanceProfile().withRoles(instanceProfileRole);

    Role role = new Role().withArn("roleArn");
    Collection<Role> roles = Collections.singletonList(role);

    EvaluationResult evalResult = new EvaluationResult()
            .withEvalDecision(PolicyEvaluationDecisionType.Allowed)
            .withEvalResourceName(role.getArn());
    when(iam.simulatePrincipalPolicy(any(SimulatePrincipalPolicyRequest.class)))
            .thenReturn(new SimulatePrincipalPolicyResult().withEvaluationResults(evalResult));

    ValidationResultBuilder validationResultBuilder = new ValidationResultBuilder();
    assertThat(awsIDBrokerAssumeRoleValidator.canAssumeRoles(iam, instanceProfile, roles,
            validationResultBuilder)).isTrue();
    assertThat(validationResultBuilder.build().hasError()).isFalse();
}
 
Example #5
Source File: AwsIamService.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the role assume role policy document as a Policy object
 *
 * @param role Role to evaluate
 * @return assume role Policy object
 */
public Policy getAssumeRolePolicy(Role role) {
    Policy policy = null;
    String assumeRolePolicyDocument = role.getAssumeRolePolicyDocument();
    if (assumeRolePolicyDocument != null) {
        try {
            String decodedAssumeRolePolicyDocument = URLDecoder.decode(assumeRolePolicyDocument,
                    StandardCharsets.UTF_8);
            policy = Policy.fromJson(decodedAssumeRolePolicyDocument);
        } catch (IllegalArgumentException e) {
            LOGGER.error(String.format("Unable to get policy from role (%s)", role.getArn()), e);
        }
    }

    return policy;
}
 
Example #6
Source File: AwsIamService.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
/**
 * Validates role ARN and returns an Role object if valid
 *
 * @param iam                     AmazonIdentityManagement client
 * @param roleArn                 role ARN
 * @param validationResultBuilder builder for any errors encountered
 * @return Role if role ARN is valid otherwise null
 */
public Role getRole(AmazonIdentityManagement iam, String roleArn,
        ValidationResultBuilder validationResultBuilder) {
    Role role = null;
    if (roleArn != null && roleArn.contains("/")) {
        String roleName = roleArn.split("/", 2)[1];
        GetRoleRequest roleRequest = new GetRoleRequest().withRoleName(roleName);
        try {
            role = iam.getRole(roleRequest).getRole();
        } catch (NoSuchEntityException | ServiceFailureException e) {
            String msg = String.format("Role (%s) doesn't exist.", roleArn);
            LOGGER.debug(msg, e);
            validationResultBuilder.error(msg);
        }
    }
    return role;
}
 
Example #7
Source File: AwsInstanceProfileEC2TrustValidator.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
public boolean isTrusted(InstanceProfile instanceProfile, ValidationResultBuilder resultBuilder) {
    List<Role> instanceProfileRoles = instanceProfile.getRoles();
    for (Role role : instanceProfileRoles) {
        Policy assumeRolePolicy = awsIamService.getAssumeRolePolicy(role);
        if (assumeRolePolicy != null) {
            for (Statement statement : assumeRolePolicy.getStatements()) {
                if (checkAssumeRoleInActions(statement.getActions()) &&
                        checkEC2InPrincipals(statement.getPrincipals())) {
                    return true;
                }
            }
        }
    }
    resultBuilder.error(
            String.format("The instance profile (%s) doesn't have an EC2 trust relationship.",
                    instanceProfile.getArn()));
    return false;
}
 
Example #8
Source File: PrincipalAutoSuggestionTest.java    From strongbox with Apache License 2.0 6 votes vote down vote up
@Test
public void testAutoSuggestionCaseInsensitive() throws Exception {
    ListRolesRequest request = new ListRolesRequest().withMaxItems(1000);

    Role lowercase = new Role().withRoleName("foobar");
    Role uppercase = new Role().withRoleName("FOOBAR");
    Role mixedCase = new Role().withRoleName("FooBar");
    ListRolesResult mockResult = new ListRolesResult();
    mockResult.withRoles(lowercase, uppercase, mixedCase);

    when(mockClient.listRoles(request)).thenReturn(mockResult);

    List<Principal> list = partiallyMockedPrincipalAutoSuggestion.autoSuggestion("fOOb");
    assertEquals(list.size(), 3);
    assertEquals(list.get(0).name, "foobar");
    assertEquals(list.get(1).name, "FOOBAR");
    assertEquals(list.get(2).name, "FooBar");
}
 
Example #9
Source File: PrincipalAutoSuggestionTest.java    From strongbox with Apache License 2.0 6 votes vote down vote up
@Test
public void testAutoSuggestion() throws Exception {
    ListRolesRequest request = new ListRolesRequest().withMaxItems(1000);

    Role role1 = new Role().withRoleName("foobar1");
    Role role2 = new Role().withRoleName("afoobar");
    Role role3 = new Role().withRoleName("foooobar");
    ListRolesResult mockResult = new ListRolesResult();
    mockResult.withRoles(role1, role2, role3);

    when(mockClient.listRoles(request)).thenReturn(mockResult);
    List<Principal> list = partiallyMockedPrincipalAutoSuggestion.autoSuggestion("foobar");
    assertEquals(list.size(), 2);
    assertEquals(list.get(0).name, "foobar1");
    assertEquals(list.get(1).name, "afoobar");

    verify(mockClient, times(1)).listRoles(request);
}
 
Example #10
Source File: InventoryUtilTest.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * Fetch IAM roles test.
 *
 * @throws Exception the exception
 */
@SuppressWarnings("static-access")
@Test
public void fetchIAMRolesTest() throws Exception {
    
    mockStatic(AmazonIdentityManagementClientBuilder.class);
    AmazonIdentityManagement iamClient = PowerMockito.mock(AmazonIdentityManagement.class);
    AmazonIdentityManagementClientBuilder amazonIdentityManagementClientBuilder = PowerMockito.mock(AmazonIdentityManagementClientBuilder.class);
    AWSStaticCredentialsProvider awsStaticCredentialsProvider = PowerMockito.mock(AWSStaticCredentialsProvider.class);
    PowerMockito.whenNew(AWSStaticCredentialsProvider.class).withAnyArguments().thenReturn(awsStaticCredentialsProvider);
    when(amazonIdentityManagementClientBuilder.standard()).thenReturn(amazonIdentityManagementClientBuilder);
    when(amazonIdentityManagementClientBuilder.withCredentials(anyObject())).thenReturn(amazonIdentityManagementClientBuilder);
    when(amazonIdentityManagementClientBuilder.withRegion(anyString())).thenReturn(amazonIdentityManagementClientBuilder);
    when(amazonIdentityManagementClientBuilder.build()).thenReturn(iamClient);
    
    ListRolesResult listRolesResult = new ListRolesResult();
    List<Role> roles = new ArrayList<>();
    roles.add(new Role());
    listRolesResult.setRoles(roles);
    when(iamClient.listRoles(anyObject())).thenReturn(listRolesResult);
    assertThat(inventoryUtil.fetchIAMRoles(new BasicSessionCredentials("awsAccessKey", "awsSecretKey", "sessionToken"),"account","accountName").size(), is(1));
}
 
Example #11
Source File: AwsIDBrokerMappedRolePermissionValidator.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
/**
 * Finds all the denied results and generates a set of failed actions
 *
 * @param role              Role that was being evaluated
 * @param evaluationResults result of simulating the policy
 */
SortedSet<String> getFailedActions(Role role, List<EvaluationResult> evaluationResults) {
    return evaluationResults.stream()
            .filter(evaluationResult -> evaluationResult.getEvalDecision().toLowerCase().contains("deny"))
            .map(evaluationResult -> String.format("%s:%s:%s", role.getArn(),
                    evaluationResult.getEvalActionName(), evaluationResult.getEvalResourceName()))
            .collect(Collectors.toCollection(TreeSet::new));
}
 
Example #12
Source File: FileManager.java    From pacbot with Apache License 2.0 5 votes vote down vote up
/**
 * Generate iam role files.
 *
 * @param iamRoleMap the iam role map
 * @throws IOException Signals that an I/O exception has occurred.
 */
public static void generateIamRoleFiles(Map<String, List<Role>> iamRoleMap) throws IOException {
	String fieldNames;
	String keys;
	fieldNames = "roleName`roleId`arn`description`path`createDate`assumeRolePolicyDocument";
	keys = "discoverydate`accountid`accountname`rolename`roleid`rolearn`description`path`createdate`assumedpolicydoc";
	FileGenerator.generateJson(iamRoleMap, fieldNames, "aws-iamrole.data",keys);
}
 
Example #13
Source File: AwsIamServiceTest.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Test
public void validRole() {
    String roleArn = "account/validRole";

    Role expectedRole = new Role().withArn(roleArn);
    GetRoleResult getRoleResult = mock(GetRoleResult.class);
    when(getRoleResult.getRole()).thenReturn(expectedRole);
    when(iam.getRole(any(GetRoleRequest.class))).thenReturn(getRoleResult);

    ValidationResultBuilder validationRequestBuilder = new ValidationResultBuilder();
    Role role = awsIamService.getRole(iam, roleArn, validationRequestBuilder);

    assertThat(role.getArn()).isEqualTo(roleArn);
    assertThat(validationRequestBuilder.build().hasError()).isFalse();
}
 
Example #14
Source File: AwsIamServiceTest.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Test
public void roleServiceFailureException() {
    when(iam.getRole(any(GetRoleRequest.class))).thenThrow(ServiceFailureException.class);

    String roleArn = "account/potentialRole";
    ValidationResultBuilder validationRequestBuilder = new ValidationResultBuilder();
    Role role = awsIamService.getRole(iam, roleArn, validationRequestBuilder);

    assertThat(role).isNull();
    ValidationResult validationResult = validationRequestBuilder.build();
    assertThat(validationResult.hasError()).isTrue();
    assertThat(validationResult.getErrors()).isEqualTo(
            Collections.singletonList(String.format("Role (%s) doesn't exist.", roleArn)));
}
 
Example #15
Source File: AwsIamServiceTest.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Test
public void missingRole() {
    when(iam.getRole(any(GetRoleRequest.class))).thenThrow(NoSuchEntityException.class);

    String roleArn = "account/missingRole";
    ValidationResultBuilder validationRequestBuilder = new ValidationResultBuilder();
    Role role = awsIamService.getRole(iam, roleArn, validationRequestBuilder);

    assertThat(role).isNull();
    ValidationResult validationResult = validationRequestBuilder.build();
    assertThat(validationResult.hasError()).isTrue();
    assertThat(validationResult.getErrors()).isEqualTo(
            Collections.singletonList(String.format("Role (%s) doesn't exist.", roleArn)));
}
 
Example #16
Source File: AwsIDBrokerMappedRolePermissionValidatorTest.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetFailedActions() {
    Role role = new Role().withArn("testRole");
    EvaluationResult allowEvalResult = new EvaluationResult()
            .withEvalActionName("doAction")
            .withEvalResourceName("goodResource")
            .withEvalDecision(PolicyEvaluationDecisionType.Allowed);
    EvaluationResult denyEvalResult = new EvaluationResult()
            .withEvalActionName("doAction")
            .withEvalResourceName("badResource")
            .withEvalDecision(PolicyEvaluationDecisionType.ImplicitDeny);

    assertThat(getValidator().getFailedActions(role,
            Collections.emptyList())).isEqualTo(Collections.emptySortedSet());

    List<EvaluationResult> allowEvalResults = Collections.singletonList(allowEvalResult);
    assertThat(getValidator().getFailedActions(role,
            allowEvalResults)).isEqualTo(Collections.emptySortedSet());

    SortedSet<String> expectedFailedActions = new TreeSet<>();
    expectedFailedActions.add(String.format("%s:%s:%s", role.getArn(),
            denyEvalResult.getEvalActionName(), denyEvalResult.getEvalResourceName()));
    List<EvaluationResult> denyEvalResults = Collections.singletonList(denyEvalResult);
    assertThat(getValidator().getFailedActions(role, denyEvalResults))
            .isEqualTo(expectedFailedActions);

    List<EvaluationResult> multipleEvalResults = Arrays.asList(denyEvalResult,
            allowEvalResult, denyEvalResult, denyEvalResult, allowEvalResult);
    assertThat(getValidator().getFailedActions(role, multipleEvalResults))
            .isEqualTo(expectedFailedActions);
}
 
Example #17
Source File: AwsInstanceProfileEC2TrustValidatorTest.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Test
public void validInstanceProfileTrustMultipleRolesTrusted() {
    Policy untrustedPolicy = new Policy();
    Role role1 = new Role().withArn("roleArn").withAssumeRolePolicyDocument(untrustedPolicy.toJson());
    Policy trustedPolicy = getTrustedPolicy();
    Role role2 = new Role().withArn("roleArn").withAssumeRolePolicyDocument(trustedPolicy.toJson());
    InstanceProfile instanceProfile = new InstanceProfile().withArn("multipleRolesTrusted")
            .withRoles(role1, role2);
    checkValidInstanceProfileTrust(instanceProfile);
}
 
Example #18
Source File: AwsInstanceProfileEC2TrustValidatorTest.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Test
public void validInstanceProfileTrustOneRoleTrusted() {
    Policy trustedPolicy = getTrustedPolicy();
    Role role = new Role().withArn("roleArn").withAssumeRolePolicyDocument(trustedPolicy.toJson());
    InstanceProfile instanceProfile = new InstanceProfile().withArn("oneRoleTrusted")
            .withRoles(role);
    checkValidInstanceProfileTrust(instanceProfile);
}
 
Example #19
Source File: AwsInstanceProfileEC2TrustValidatorTest.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Test
public void invalidInstanceProfileTrustMultipleRolesNoTrustPolicy() {
    Role role1 = new Role().withArn("roleArn").withAssumeRolePolicyDocument(new Policy().toJson());
    Role role2 = new Role().withArn("roleArn").withAssumeRolePolicyDocument(new Policy().toJson());
    InstanceProfile instanceProfile = new InstanceProfile().withArn("multipleRolesNoTrustPolicy")
            .withRoles(role1, role2);
    checkInvalidInstanceProfileTrust(instanceProfile);
}
 
Example #20
Source File: AwsInstanceProfileEC2TrustValidatorTest.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Test
public void invalidInstanceProfileTrustOneRoleNoTrustPolicy() {
    Role role = new Role().withArn("roleArn").withAssumeRolePolicyDocument(new Policy().toJson());
    InstanceProfile instanceProfile = new InstanceProfile().withArn("oneRoleNoTrustPolicy")
            .withRoles(role);
    checkInvalidInstanceProfileTrust(instanceProfile);
}
 
Example #21
Source File: AwsInstanceProfileEC2TrustValidatorTest.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Test
public void invalidInstanceProfileTrustOneRoleBadPolicy() {
    Role role = new Role().withArn("roleArn").withAssumeRolePolicyDocument("");
    InstanceProfile instanceProfile = new InstanceProfile().withArn("oneRoleBadPolicy")
            .withRoles(role);
    checkInvalidInstanceProfileTrust(instanceProfile);
}
 
Example #22
Source File: AwsInstanceProfileEC2TrustValidatorTest.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Test
public void invalidInstanceProfileTrustOneRoleNoPolicy() {
    Role role = new Role().withArn("roleArn");
    InstanceProfile instanceProfile = new InstanceProfile().withArn("oneRoleNoPolicy")
            .withRoles(role);
    checkInvalidInstanceProfileTrust(instanceProfile);
}
 
Example #23
Source File: AwsIDBrokerAssumeRoleValidatorTest.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Test
public void checkCannotAssumeOneOfTheRoles() {
    Role instanceProfileRole = new Role();
    InstanceProfile instanceProfile = new InstanceProfile().withArn("instanceProfileArn")
            .withRoles(instanceProfileRole);

    Role role1 = new Role().withArn("role1Arn");
    Role role2 = new Role().withArn("role2Arn");
    Collection<Role> roles = Arrays.asList(role1, role2);

    EvaluationResult evalResult1 = new EvaluationResult()
            .withEvalDecision(PolicyEvaluationDecisionType.Allowed)
            .withEvalResourceName(role1.getArn());
    EvaluationResult evalResult2 = new EvaluationResult()
            .withEvalDecision(PolicyEvaluationDecisionType.ImplicitDeny)
            .withEvalResourceName(role2.getArn());
    when(iam.simulatePrincipalPolicy(any(SimulatePrincipalPolicyRequest.class)))
            .thenReturn(new SimulatePrincipalPolicyResult().withEvaluationResults(evalResult1))
            .thenReturn(new SimulatePrincipalPolicyResult().withEvaluationResults(evalResult2));

    ValidationResultBuilder validationResultBuilder = new ValidationResultBuilder();
    assertThat(awsIDBrokerAssumeRoleValidator.canAssumeRoles(iam, instanceProfile, roles,
            validationResultBuilder)).isFalse();
    ValidationResult validationResult = validationResultBuilder.build();
    assertThat(validationResult.hasError()).isTrue();
    assertThat(validationResult.getErrors()).isEqualTo(Collections.singletonList(
            String.format("IDBroker instance profile (%s) doesn't have permissions to assume the role(s): %s",
                    instanceProfile.getArn(), Collections.singletonList(role2.getArn()))));
}
 
Example #24
Source File: IntegrationTestHelper.java    From strongbox with Apache License 2.0 5 votes vote down vote up
private static void cleanUpIAM(Regions testRegion, String testResourcePrefix, Date createdBeforeThreshold,
                               AWSCredentialsProvider awsCredentials) {
    AmazonIdentityManagement iamClient = AmazonIdentityManagementClientBuilder.standard()
        .withCredentials(awsCredentials)
        .withRegion(testRegion)
        .build();
    IAMPolicyManager iamPolicyManager = IAMPolicyManager.fromCredentials(awsCredentials, new ClientConfiguration());

    LOG.info("Cleaning IAM policies...");
    ListPoliciesRequest listPoliciesRequest = new ListPoliciesRequest().withPathPrefix(IAMPolicyManager.PATH_PREFIX);
    List<Policy> policies = iamClient.listPolicies(listPoliciesRequest).getPolicies();
    for (Policy policy: policies) {
        if (policy.getPolicyName().startsWith(testResourcePrefix) &&
                policy.getCreateDate().before(createdBeforeThreshold)) {
            LOG.info("Cleaning up policy: " + policy.getPolicyName());

            IAMPolicyName iamPolicyName = IAMPolicyName.fromString(policy.getPolicyName());
            iamPolicyManager.detachAllPrincipals(iamPolicyName.group);

            DeletePolicyRequest deletePolicyRequest = new DeletePolicyRequest().withPolicyArn(policy.getArn());
            iamClient.deletePolicy(deletePolicyRequest);
        }
    }

    LOG.info("Cleaning IAM roles created for the assume role tests...");
    ListRolesRequest listRolesRequest = new ListRolesRequest().withPathPrefix(IAMHelper.PATH);
    List<Role> roles = iamClient.listRoles(listRolesRequest).getRoles();
    for (Role role: roles) {
        if (role.getRoleName().startsWith(AssumedRoleTestContext.ROLE_PREFIX) &&
                role.getCreateDate().before(createdBeforeThreshold)) {
            LOG.info("Cleaning up role: " + role.getRoleName());
            DeleteRoleRequest deleteRoleRequest = new DeleteRoleRequest().withRoleName(role.getRoleName());
            iamClient.deleteRole(deleteRoleRequest);
        }
    }

}
 
Example #25
Source File: AwsIamService.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
/**
 * Validates the given roles against the policies
 *
 * @param iam      AmazonIdentityManagement client
 * @param role     Role object to check
 * @param policies collection of Policy objects to check
 * @return list of evaluation results
 */
public List<EvaluationResult> validateRolePolicies(AmazonIdentityManagement iam, Role role,
        Collection<Policy> policies) throws AmazonIdentityManagementException {
    List<EvaluationResult> evaluationResults = new ArrayList<>();
    for (Policy policy : policies) {
        for (Statement statement : policy.getStatements()) {
            SortedSet<String> actions = getStatementActions(statement);
            SortedSet<String> resources = getStatementResources(statement);
            List<EvaluationResult> results = simulatePrincipalPolicy(iam, role.getArn(), actions, resources);
            evaluationResults.addAll(results);
        }
    }
    return evaluationResults;
}
 
Example #26
Source File: AwsPlatformResources.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private Set<CloudAccessConfig> getAccessConfigByRole(AmazonIdentityManagement client) {
    LOGGER.info("Get all Roles from Amazon");
    String queryFailedMessage = "Could not get roles from Amazon: ";
    try {
        boolean finished = false;
        String marker = null;
        List<Role> roles = new LinkedList<>();
        while (!finished) {
            ListRolesRequest listRolesRequest = new ListRolesRequest();
            listRolesRequest.setMaxItems(fetchMaxItems);
            if (isNotEmpty(marker)) {
                listRolesRequest.setMarker(marker);
            }
            LOGGER.debug("About to fetch roles...");
            ListRolesResult listRolesResult = client.listRoles(listRolesRequest);
            roles.addAll(listRolesResult.getRoles());
            if (listRolesResult.isTruncated()) {
                marker = listRolesResult.getMarker();
            } else {
                finished = true;
            }
        }
        return roles.stream().map(this::roleToCloudAccessConfig).collect(Collectors.toSet());
    } catch (AmazonServiceException ase) {
        if (ase.getStatusCode() == UNAUTHORIZED) {
            String policyMessage = "Could not get roles because the user does not have enough permission. ";
            LOGGER.error(policyMessage + ase.getMessage(), ase);
            throw new CloudUnauthorizedException(ase.getErrorMessage(), ase);
        } else {
            LOGGER.info(queryFailedMessage + ase.getMessage(), ase);
            throw new CloudConnectorException(ase.getMessage(), ase);
        }
    } catch (Exception e) {
        LOGGER.warn(queryFailedMessage + e.getMessage(), e);
        throw new CloudConnectorException(e.getMessage(), e);
    }
}
 
Example #27
Source File: AwsIDBrokerObjectStorageValidator.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private Set<Role> getAllMappedRoles(AmazonIdentityManagement iam, CloudFileSystemView cloudFileSystemView,
        ValidationResultBuilder resultBuilder) {
    Set<Role> roles = Collections.emptySet();
    AccountMappingBase accountMappings = cloudFileSystemView.getAccountMapping();
    if (accountMappings != null) {
        SortedSet<String> roleArns = new TreeSet<>();
        roleArns.addAll(accountMappings.getUserMappings().values());
        roleArns.addAll(accountMappings.getGroupMappings().values());
        roles = awsIamService.getValidRoles(iam, roleArns, resultBuilder);
    }
    return roles;
}
 
Example #28
Source File: AwsIDBrokerObjectStorageValidator.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private void validateIDBroker(AmazonIdentityManagement iam, InstanceProfile instanceProfile,
        CloudS3View cloudFileSystem, ValidationResultBuilder resultBuilder) {
    awsInstanceProfileEC2TrustValidator.isTrusted(instanceProfile, resultBuilder);

    Set<Role> allMappedRoles = getAllMappedRoles(iam, cloudFileSystem, resultBuilder);
    awsIDBrokerAssumeRoleValidator.canAssumeRoles(iam, instanceProfile, allMappedRoles, resultBuilder);

    awsDataAccessRolePermissionValidator.validate(iam, cloudFileSystem, resultBuilder);

    awsRangerAuditRolePermissionValidator.validate(iam, cloudFileSystem, resultBuilder);
}
 
Example #29
Source File: AwsLogRolePermissionValidator.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
/**
 * Finds all the denied results and generates a set of failed actions
 *
 * @param role              Role that was being evaluated
 * @param evaluationResults result of the simulate policy
 */
SortedSet<String> getFailedActions(Role role, List<EvaluationResult> evaluationResults) {
    return evaluationResults.stream()
            .filter(evaluationResult -> evaluationResult.getEvalDecision().toLowerCase().contains("deny"))
            .map(evaluationResult -> String.format("%s:%s:%s", role.getArn(),
                    evaluationResult.getEvalActionName(), evaluationResult.getEvalResourceName()))
            .collect(Collectors.toCollection(TreeSet::new));
}
 
Example #30
Source File: AwsLogRolePermissionValidator.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
public void validate(AmazonIdentityManagement iam, InstanceProfile instanceProfile,
        CloudS3View cloudFileSystem, ValidationResultBuilder validationResultBuilder) {
    SortedSet<String> failedActions = new TreeSet<>();

    // TODO need to figure out how to get LOGS_LOCATION_BASE value
    Map<String, String> replacements = Map.ofEntries(
            Map.entry("${LOGS_LOCATION_BASE}", "")
    );

    Policy policy = awsIamService.getPolicy("aws-cdp-log-policy.json", replacements);
    List<Role> roles = instanceProfile.getRoles();
    List<Policy> policies = Collections.singletonList(policy);
    for (Role role : roles) {
        try {
            List<EvaluationResult> evaluationResults = awsIamService.validateRolePolicies(iam,
                    role, policies);
            failedActions.addAll(getFailedActions(role, evaluationResults));
        } catch (AmazonIdentityManagementException e) {
            // Only log the error and keep processing. Failed actions won't be added, but
            // processing doesn't get stopped either. This can happen due to rate limiting.
            LOGGER.error("Unable to validate role policies for role {} due to {}", role.getArn(),
                    e.getMessage(), e);
        }
    }

    if (!failedActions.isEmpty()) {
        validationResultBuilder.error(String.format("The log role (%s) don't have the required permissions: %n%s",
                String.join(", ", roles.stream().map(Role::getArn).collect(Collectors.toCollection(TreeSet::new))),
                String.join("\n", failedActions)));
    }
}