Search in sources :

Example 1 with EvaluationResult

use of com.amazonaws.services.identitymanagement.model.EvaluationResult in project cloudbreak by hortonworks.

the class AwsCredentialVerifierTest method verifyCredentialAndThrowFailExceptionBecauseOrganizatioRuleTest.

@Test
public void verifyCredentialAndThrowFailExceptionBecauseOrganizatioRuleTest() throws IOException {
    URL url = Resources.getResource("definitions/aws-environment-minimal-policy.json");
    String awsEnvPolicy = Resources.toString(url, Charsets.UTF_8);
    String encodedAwsEnvPolicy = Base64.getEncoder().encodeToString(awsEnvPolicy.getBytes());
    Map<String, Object> awsParameters = new HashMap<>();
    awsParameters.put("accessKey", "a");
    awsParameters.put("secretKey", "b");
    CloudCredential cloudCredential = new CloudCredential("id", "name", awsParameters, "acc", false);
    AmazonIdentityManagementClient amazonIdentityManagement = mock(AmazonIdentityManagementClient.class);
    when(awsClient.createAmazonIdentityManagement(any(AwsCredentialView.class))).thenReturn(amazonIdentityManagement);
    AmazonSecurityTokenServiceClient awsSecurityTokenService = mock(AmazonSecurityTokenServiceClient.class);
    GetCallerIdentityResult getCallerIdentityResult = new GetCallerIdentityResult();
    getCallerIdentityResult.setArn("arn");
    when(awsSecurityTokenService.getCallerIdentity(any(GetCallerIdentityRequest.class))).thenReturn(getCallerIdentityResult);
    when(awsClient.createSecurityTokenService(any(AwsCredentialView.class))).thenReturn(awsSecurityTokenService);
    ArgumentCaptor<SimulatePrincipalPolicyRequest> requestArgumentCaptor = ArgumentCaptor.forClass(SimulatePrincipalPolicyRequest.class);
    AtomicInteger i = new AtomicInteger();
    when(amazonIdentityManagement.simulatePrincipalPolicy(requestArgumentCaptor.capture())).thenAnswer(invocation -> {
        SimulatePrincipalPolicyResult simulatePrincipalPolicyResult = new SimulatePrincipalPolicyResult();
        ArrayList<EvaluationResult> evaluationResults = new ArrayList<>();
        evaluationResults.add(new EvaluationResult().withEvalDecision("deny").withOrganizationsDecisionDetail(new OrganizationsDecisionDetail().withAllowedByOrganizations(true)).withEvalActionName("denied_action1_" + i).withEvalResourceName("aws:ec2"));
        evaluationResults.add(new EvaluationResult().withEvalDecision("deny").withOrganizationsDecisionDetail(new OrganizationsDecisionDetail().withAllowedByOrganizations(false)).withEvalActionName("denied_action2_" + i).withEvalResourceName("aws:ec2"));
        evaluationResults.add(new EvaluationResult().withEvalDecision("deny").withOrganizationsDecisionDetail(new OrganizationsDecisionDetail().withAllowedByOrganizations(false)).withEvalActionName("denied_action3_" + i).withEvalResourceName("aws:ec2"));
        evaluationResults.add(new EvaluationResult().withEvalDecision("accept").withOrganizationsDecisionDetail(new OrganizationsDecisionDetail().withAllowedByOrganizations(true)).withEvalActionName("accepted_action_" + i).withEvalResourceName("*"));
        simulatePrincipalPolicyResult.setEvaluationResults(evaluationResults);
        i.getAndIncrement();
        return simulatePrincipalPolicyResult;
    });
    try {
        awsCredentialVerifier.validateAws(new AwsCredentialView(cloudCredential), encodedAwsEnvPolicy);
        fail("It shoud throw verification exception");
    } catch (AwsPermissionMissingException e) {
        assertThat(e.getMessage(), CoreMatchers.containsString("denied_action1_0 : aws:ec2,"));
        assertThat(e.getMessage(), CoreMatchers.containsString("denied_action2_0 : aws:ec2 -> Denied by Organization Rule,"));
        assertThat(e.getMessage(), CoreMatchers.containsString("denied_action3_0 : aws:ec2 -> Denied by Organization Rule,"));
        assertThat(e.getMessage(), not(CoreMatchers.containsString("accepted_action")));
    }
    List<SimulatePrincipalPolicyRequest> allSimulatePrincipalPolicyRequest = requestArgumentCaptor.getAllValues();
    int simulateRequestNumber = 5;
    assertEquals("expect if " + simulateRequestNumber + " simulate request has been sent", simulateRequestNumber, allSimulatePrincipalPolicyRequest.size());
    allSimulatePrincipalPolicyRequest.forEach(simulatePrincipalPolicyRequest -> assertEquals("arn", simulatePrincipalPolicyRequest.getPolicySourceArn()));
}
Also used : AwsPermissionMissingException(com.sequenceiq.cloudbreak.cloud.aws.common.exception.AwsPermissionMissingException) AmazonIdentityManagementClient(com.sequenceiq.cloudbreak.cloud.aws.common.client.AmazonIdentityManagementClient) HashMap(java.util.HashMap) CloudCredential(com.sequenceiq.cloudbreak.cloud.model.CloudCredential) OrganizationsDecisionDetail(com.amazonaws.services.identitymanagement.model.OrganizationsDecisionDetail) ArrayList(java.util.ArrayList) URL(java.net.URL) EvaluationResult(com.amazonaws.services.identitymanagement.model.EvaluationResult) AwsCredentialView(com.sequenceiq.cloudbreak.cloud.aws.common.view.AwsCredentialView) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) SimulatePrincipalPolicyRequest(com.amazonaws.services.identitymanagement.model.SimulatePrincipalPolicyRequest) GetCallerIdentityRequest(com.amazonaws.services.securitytoken.model.GetCallerIdentityRequest) AmazonSecurityTokenServiceClient(com.sequenceiq.cloudbreak.cloud.aws.common.client.AmazonSecurityTokenServiceClient) SimulatePrincipalPolicyResult(com.amazonaws.services.identitymanagement.model.SimulatePrincipalPolicyResult) GetCallerIdentityResult(com.amazonaws.services.securitytoken.model.GetCallerIdentityResult) Test(org.junit.Test)

Example 2 with EvaluationResult

use of com.amazonaws.services.identitymanagement.model.EvaluationResult in project cloudbreak by hortonworks.

the class AwsCredentialVerifierTest method verifyCredentialTest.

@Test
public void verifyCredentialTest() throws IOException, AwsPermissionMissingException {
    URL url = Resources.getResource("definitions/aws-environment-minimal-policy.json");
    String awsEnvPolicy = Resources.toString(url, Charsets.UTF_8);
    String encodedAwsEnvPolicy = Base64.getEncoder().encodeToString(awsEnvPolicy.getBytes());
    Map<String, Object> awsParameters = new HashMap<>();
    awsParameters.put("accessKey", "a");
    awsParameters.put("secretKey", "b");
    CloudCredential cloudCredential = new CloudCredential("id", "name", awsParameters, "acc", false);
    AmazonIdentityManagementClient amazonIdentityManagement = mock(AmazonIdentityManagementClient.class);
    when(awsClient.createAmazonIdentityManagement(any(AwsCredentialView.class))).thenReturn(amazonIdentityManagement);
    AmazonSecurityTokenServiceClient awsSecurityTokenService = mock(AmazonSecurityTokenServiceClient.class);
    GetCallerIdentityResult getCallerIdentityResult = new GetCallerIdentityResult();
    getCallerIdentityResult.setArn("arn");
    when(awsSecurityTokenService.getCallerIdentity(any(GetCallerIdentityRequest.class))).thenReturn(getCallerIdentityResult);
    when(awsClient.createSecurityTokenService(any(AwsCredentialView.class))).thenReturn(awsSecurityTokenService);
    ArgumentCaptor<SimulatePrincipalPolicyRequest> requestArgumentCaptor = ArgumentCaptor.forClass(SimulatePrincipalPolicyRequest.class);
    SimulatePrincipalPolicyResult simulatePrincipalPolicyResult = new SimulatePrincipalPolicyResult();
    ArrayList<EvaluationResult> evaluationResults = new ArrayList<>();
    evaluationResults.add(new EvaluationResult().withEvalDecision("accept").withOrganizationsDecisionDetail(new OrganizationsDecisionDetail().withAllowedByOrganizations(true)).withEvalActionName("accepted_action1").withEvalResourceName("aws:ec2"));
    evaluationResults.add(new EvaluationResult().withEvalDecision("accept").withOrganizationsDecisionDetail(new OrganizationsDecisionDetail().withAllowedByOrganizations(true)).withEvalActionName("accepted_action2").withEvalResourceName("aws:ec2"));
    evaluationResults.add(new EvaluationResult().withEvalDecision("accept").withOrganizationsDecisionDetail(new OrganizationsDecisionDetail().withAllowedByOrganizations(true)).withEvalActionName("accepted_action3").withEvalResourceName("aws:ec2"));
    evaluationResults.add(new EvaluationResult().withEvalDecision("accept").withOrganizationsDecisionDetail(new OrganizationsDecisionDetail().withAllowedByOrganizations(true)).withEvalActionName("accepted_action4").withEvalResourceName("*"));
    simulatePrincipalPolicyResult.setEvaluationResults(evaluationResults);
    when(amazonIdentityManagement.simulatePrincipalPolicy(requestArgumentCaptor.capture())).thenReturn(simulatePrincipalPolicyResult);
    awsCredentialVerifier.validateAws(new AwsCredentialView(cloudCredential), encodedAwsEnvPolicy);
}
Also used : AmazonIdentityManagementClient(com.sequenceiq.cloudbreak.cloud.aws.common.client.AmazonIdentityManagementClient) HashMap(java.util.HashMap) CloudCredential(com.sequenceiq.cloudbreak.cloud.model.CloudCredential) OrganizationsDecisionDetail(com.amazonaws.services.identitymanagement.model.OrganizationsDecisionDetail) ArrayList(java.util.ArrayList) URL(java.net.URL) EvaluationResult(com.amazonaws.services.identitymanagement.model.EvaluationResult) AwsCredentialView(com.sequenceiq.cloudbreak.cloud.aws.common.view.AwsCredentialView) SimulatePrincipalPolicyRequest(com.amazonaws.services.identitymanagement.model.SimulatePrincipalPolicyRequest) GetCallerIdentityRequest(com.amazonaws.services.securitytoken.model.GetCallerIdentityRequest) AmazonSecurityTokenServiceClient(com.sequenceiq.cloudbreak.cloud.aws.common.client.AmazonSecurityTokenServiceClient) SimulatePrincipalPolicyResult(com.amazonaws.services.identitymanagement.model.SimulatePrincipalPolicyResult) GetCallerIdentityResult(com.amazonaws.services.securitytoken.model.GetCallerIdentityResult) Test(org.junit.Test)

Example 3 with EvaluationResult

use of com.amazonaws.services.identitymanagement.model.EvaluationResult in project cloudbreak by hortonworks.

the class AwsLogRolePermissionValidator method validate.

public void validate(AmazonIdentityManagementClient iam, InstanceProfile instanceProfile, CloudS3View cloudFileSystem, String logLocationBase, ValidationResultBuilder validationResultBuilder) {
    SortedSet<String> failedActions = new TreeSet<>();
    SortedSet<String> warnings = new TreeSet<>();
    Arn instanceProfileArn = Arn.of(instanceProfile.getArn());
    if (logLocationBase == null) {
        return;
    }
    Map<String, String> replacements = Map.ofEntries(Map.entry("${ARN_PARTITION}", instanceProfileArn.getPartition()), Map.entry("${LOGS_LOCATION_BASE}", removeProtocol(logLocationBase)), Map.entry("${LOGS_BUCKET}", locationHelper.parseS3BucketName(logLocationBase)));
    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));
            warnings.addAll(getWarnings(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 (!warnings.isEmpty()) {
        String validationWarningMessage = String.format("The validation of the Logger Instance Profile (%s) was not successful" + " because there are missing context values (%s). This is not an issue in itself you might have an SCPs configured" + " in your aws account and the system couldn't guess these extra parameters.", String.join(", ", instanceProfile.getArn()), String.join(", ", warnings));
        LOGGER.info(validationWarningMessage);
        validationResultBuilder.warning(validationWarningMessage);
    }
    if (!failedActions.isEmpty()) {
        String validationErrorMessage = String.format("Logger Instance Profile (%s) is not set up correctly. " + "Please follow the official documentation on required policies for Logger Instance Profile.\n" + "Missing policies:%n%s", String.join(", ", instanceProfile.getArn()), String.join("\n", failedActions));
        LOGGER.info(validationErrorMessage);
        validationResultBuilder.error(validationErrorMessage);
    }
}
Also used : Policy(com.amazonaws.auth.policy.Policy) Role(com.amazonaws.services.identitymanagement.model.Role) TreeSet(java.util.TreeSet) AmazonIdentityManagementException(com.amazonaws.services.identitymanagement.model.AmazonIdentityManagementException) Arn(com.sequenceiq.cloudbreak.cloud.aws.common.util.Arn) EvaluationResult(com.amazonaws.services.identitymanagement.model.EvaluationResult)

Example 4 with EvaluationResult

use of com.amazonaws.services.identitymanagement.model.EvaluationResult in project cloudbreak by hortonworks.

the class AwsIamServiceTest method testInvalidValidateRolePolicies.

@Test
public void testInvalidValidateRolePolicies() {
    when(iam.simulatePrincipalPolicy(any())).thenReturn(new SimulatePrincipalPolicyResult().withEvaluationResults(new EvaluationResult().withEvalDecision(PolicyEvaluationDecisionType.ExplicitDeny)));
    Policy policy = new Policy().withStatements(createStatement(Set.of(S3Actions.GetObject), Set.of(new Resource("resource1"))));
    List<EvaluationResult> evaluationResults = awsIamService.validateRolePolicies(iam, createRole(), Set.of(policy));
    assertThat(evaluationResults).hasSize(1);
    EvaluationResult evaluationResult = evaluationResults.get(0);
    assertEquals("explicitDeny", evaluationResult.getEvalDecision());
    verify(iam, times(1)).simulatePrincipalPolicy(any());
}
Also used : Policy(com.amazonaws.auth.policy.Policy) Resource(com.amazonaws.auth.policy.Resource) SimulatePrincipalPolicyResult(com.amazonaws.services.identitymanagement.model.SimulatePrincipalPolicyResult) EvaluationResult(com.amazonaws.services.identitymanagement.model.EvaluationResult) Test(org.junit.jupiter.api.Test)

Example 5 with EvaluationResult

use of com.amazonaws.services.identitymanagement.model.EvaluationResult in project cloudbreak by hortonworks.

the class AwsIamServiceTest method testValidateRolePolicies.

@Test
public void testValidateRolePolicies() {
    ArgumentCaptor<SimulatePrincipalPolicyRequest> simulatePolicyRequestCaptor = ArgumentCaptor.forClass(SimulatePrincipalPolicyRequest.class);
    when(iam.simulatePrincipalPolicy(simulatePolicyRequestCaptor.capture())).thenReturn(new SimulatePrincipalPolicyResult().withEvaluationResults(new EvaluationResult().withEvalDecision(PolicyEvaluationDecisionType.Allowed)));
    Policy policy1 = new Policy();
    Set<Statement> statements1 = Set.of(createStatement(Set.of(AutoScalingActions.CreateAutoScalingGroup, AutoScalingActions.DeleteAutoScalingGroup), Set.of(new Resource("resource1"), new Resource("resource2"))), createStatement(Set.of(S3Actions.GetObject, S3Actions.PutObject), Set.of(new Resource("resource1"), new Resource("resource2"), new Resource("resource3"), new Resource("resource4"))));
    policy1.getStatements().addAll(statements1);
    Policy policy2 = new Policy();
    Set<Statement> statements2 = Set.of(createStatement(Set.of(AutoScalingActions.AttachLoadBalancers, AutoScalingActions.AttachLoadBalancerTargetGroups), Set.of(new Resource("resource1"), new Resource("resource2"))), createStatement(Set.of(S3Actions.GetObject, S3Actions.PutObject), Set.of(new Resource("resource5"))), createStatement(Set.of(S3Actions.GetObject, S3Actions.PutObject), Set.of(new Resource("resource6"))));
    policy2.setStatements(statements2);
    Set<Policy> policies = Set.of(policy1, policy2);
    List<EvaluationResult> evaluationResults = awsIamService.validateRolePolicies(iam, createRole(), policies);
    assertEquals(2, evaluationResults.size());
    verify(iam, times(2)).simulatePrincipalPolicy(any());
    List<SimulatePrincipalPolicyRequest> requests = simulatePolicyRequestCaptor.getAllValues();
    SimulatePrincipalPolicyRequest request1;
    SimulatePrincipalPolicyRequest request2;
    if (requests.get(0).getResourceArns().size() == 6) {
        request1 = requests.get(0);
        request2 = requests.get(1);
    } else {
        request1 = requests.get(1);
        request2 = requests.get(0);
    }
    assertEquals("roleArn", request1.getPolicySourceArn());
    assertEquals("roleArn", request2.getPolicySourceArn());
    assertThat(request1.getResourceArns()).containsExactlyInAnyOrder("resource1", "resource2", "resource3", "resource4", "resource5", "resource6");
    assertThat(request2.getResourceArns()).containsExactlyInAnyOrder("resource1", "resource2");
    assertThat(request1.getActionNames()).containsExactlyInAnyOrder("s3:GetObject", "s3:PutObject");
    assertThat(request2.getActionNames()).containsExactlyInAnyOrder("autoscaling:CreateAutoScalingGroup", "autoscaling:DeleteAutoScalingGroup", "autoscaling:AttachLoadBalancers", "autoscaling:AttachLoadBalancerTargetGroups");
}
Also used : Policy(com.amazonaws.auth.policy.Policy) Statement(com.amazonaws.auth.policy.Statement) Resource(com.amazonaws.auth.policy.Resource) SimulatePrincipalPolicyRequest(com.amazonaws.services.identitymanagement.model.SimulatePrincipalPolicyRequest) SimulatePrincipalPolicyResult(com.amazonaws.services.identitymanagement.model.SimulatePrincipalPolicyResult) EvaluationResult(com.amazonaws.services.identitymanagement.model.EvaluationResult) Test(org.junit.jupiter.api.Test)

Aggregations

EvaluationResult (com.amazonaws.services.identitymanagement.model.EvaluationResult)12 SimulatePrincipalPolicyResult (com.amazonaws.services.identitymanagement.model.SimulatePrincipalPolicyResult)9 SimulatePrincipalPolicyRequest (com.amazonaws.services.identitymanagement.model.SimulatePrincipalPolicyRequest)7 Role (com.amazonaws.services.identitymanagement.model.Role)6 Test (org.junit.jupiter.api.Test)6 Policy (com.amazonaws.auth.policy.Policy)4 GetCallerIdentityRequest (com.amazonaws.services.securitytoken.model.GetCallerIdentityRequest)4 GetCallerIdentityResult (com.amazonaws.services.securitytoken.model.GetCallerIdentityResult)4 AmazonIdentityManagementClient (com.sequenceiq.cloudbreak.cloud.aws.common.client.AmazonIdentityManagementClient)4 AmazonSecurityTokenServiceClient (com.sequenceiq.cloudbreak.cloud.aws.common.client.AmazonSecurityTokenServiceClient)4 AwsCredentialView (com.sequenceiq.cloudbreak.cloud.aws.common.view.AwsCredentialView)4 CloudCredential (com.sequenceiq.cloudbreak.cloud.model.CloudCredential)4 URL (java.net.URL)4 ArrayList (java.util.ArrayList)4 HashMap (java.util.HashMap)4 Test (org.junit.Test)4 InstanceProfile (com.amazonaws.services.identitymanagement.model.InstanceProfile)3 OrganizationsDecisionDetail (com.amazonaws.services.identitymanagement.model.OrganizationsDecisionDetail)3 AwsPermissionMissingException (com.sequenceiq.cloudbreak.cloud.aws.common.exception.AwsPermissionMissingException)3 ValidationResultBuilder (com.sequenceiq.cloudbreak.validation.ValidationResult.ValidationResultBuilder)3