com.amazonaws.services.securitytoken.model.GetCallerIdentityRequest Java Examples

The following examples show how to use com.amazonaws.services.securitytoken.model.GetCallerIdentityRequest. 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: AWSAuthProvider.java    From graylog-plugin-aws with Apache License 2.0 6 votes vote down vote up
private AWSCredentialsProvider getSTSCredentialsProvider(AWSCredentialsProvider awsCredentials, String region, String assumeRoleArn) {
    AWSSecurityTokenService stsClient = AWSSecurityTokenServiceClientBuilder.standard()
            .withRegion(region)
            .withCredentials(awsCredentials)
            .build();
    String roleSessionName = String.format("API_KEY_%s@ACCOUNT_%s",
            awsCredentials.getCredentials().getAWSAccessKeyId(),
            stsClient.getCallerIdentity(new GetCallerIdentityRequest()).getAccount());
    LOG.debug("Cross account role session name: " + roleSessionName);
    return new STSAssumeRoleSessionCredentialsProvider.Builder(assumeRoleArn, roleSessionName)
            .withStsClient(stsClient)
            .build();
}
 
Example #2
Source File: IAMPolicyManager.java    From strongbox with Apache License 2.0 5 votes vote down vote up
public static String getAccount(AWSCredentialsProvider awsCredentialsProvider, ClientConfiguration clientConfiguration) {
    AWSSecurityTokenService client = AWSSecurityTokenServiceClientBuilder.standard()
        .withCredentials(awsCredentialsProvider)
        .withClientConfiguration(transformAndVerifyOrThrow(clientConfiguration))
        .withRegion(RegionResolver.getRegion())
        .build();
    GetCallerIdentityRequest request = new GetCallerIdentityRequest();
    GetCallerIdentityResult result = client.getCallerIdentity(request);

    return result.getAccount();
}
 
Example #3
Source File: WithAWSStep.java    From pipeline-aws-plugin with Apache License 2.0 5 votes vote down vote up
private String createAccountId(final AWSSecurityTokenService sts) {
	if (!StringUtils.isNullOrEmpty(this.step.getRoleAccount())) {
		return this.step.getRoleAccount();
	} else {
		return sts.getCallerIdentity(new GetCallerIdentityRequest()).getAccount();
	}
}
 
Example #4
Source File: AWSIdentityStep.java    From pipeline-aws-plugin with Apache License 2.0 5 votes vote down vote up
@Override
protected Map<String, String> run() throws Exception {
	AWSSecurityTokenService sts = AWSClientFactory.create(AWSSecurityTokenServiceClientBuilder.standard(), this.getContext());
	GetCallerIdentityResult identity = sts.getCallerIdentity(new GetCallerIdentityRequest());

	this.getContext().get(TaskListener.class).getLogger().format("Current AWS identity: %s - %s - %s %n", identity.getAccount(), identity.getUserId(), identity.getArn());

	Map<String, String> info = new HashMap<>();
	info.put("account", identity.getAccount());
	info.put("user", identity.getUserId());
	info.put("arn", identity.getArn());
	return info;
}
 
Example #5
Source File: InstanceAWSProvider.java    From athenz with Apache License 2.0 5 votes vote down vote up
boolean verifyInstanceIdentity(AWSAttestationData info, final String awsAccount) {
    
    GetCallerIdentityRequest req = new GetCallerIdentityRequest();
    
    try {
        AWSSecurityTokenService client = getInstanceClient(info);
        if (client == null) {
            LOGGER.error("verifyInstanceIdentity - unable to get AWS STS client object");
            return false;
        }
        
        GetCallerIdentityResult res = client.getCallerIdentity(req);
        if (res == null) {
            LOGGER.error("verifyInstanceIdentity - unable to get caller identity");
            return false;
        }
         
        String arn = "arn:aws:sts::" + awsAccount + ":assumed-role/" + info.getRole() + "/";
        if (!res.getArn().startsWith(arn)) {
            LOGGER.error("verifyInstanceIdentity - ARN mismatch - request: {} caller-idenity: {}",
                    arn, res.getArn());
            return false;
        }
        
        return true;
        
    } catch (Exception ex) {
        LOGGER.error("CloudStore: verifyInstanceIdentity - unable get caller identity: {}",
                ex.getMessage());
        return false;
    }
}
 
Example #6
Source File: AmazonS3Config.java    From ReCiter with Apache License 2.0 5 votes vote down vote up
private String getAccountIDUsingAccessKey(String accessKey, String secretKey) {
    AWSSecurityTokenService stsService = AWSSecurityTokenServiceClientBuilder.standard().withCredentials(
            new AWSStaticCredentialsProvider(new BasicAWSCredentials(accessKey, secretKey))).build();

    GetCallerIdentityResult callerIdentity = stsService.getCallerIdentity(new GetCallerIdentityRequest());
    return callerIdentity.getAccount();
}
 
Example #7
Source File: AwsIdentityService.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private String getAccountIdUsingAccessKey(String region, String accessKey, String secretKey) {
    AWSSecurityTokenService stsService = AWSSecurityTokenServiceClientBuilder.standard()
            .withRegion(region)
            .withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials(accessKey, secretKey)))
            .build();

    GetCallerIdentityResult callerIdentity = stsService.getCallerIdentity(new GetCallerIdentityRequest());
    return callerIdentity.getAccount();
}
 
Example #8
Source File: AwsCredentialVerifier.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Cacheable(value = AwsCredentialCachingConfig.TEMPORARY_AWS_CREDENTIAL_VERIFIER_CACHE,
        unless = "#awsCredential == null")
public void validateAws(AwsCredentialView awsCredential) throws AwsPermissionMissingException {
    String policies = new String(Base64.getDecoder().decode(awsPlatformParameters.getCredentialPoliciesJson()));
    try {
        Map<String, List<String>> resourcesWithActions = getRequiredActions(policies);
        AmazonIdentityManagement amazonIdentityManagement = awsClient.createAmazonIdentityManagement(awsCredential);
        AWSSecurityTokenService awsSecurityTokenService = awsClient.createAwsSecurityTokenService(awsCredential);
        String arn;
        if (awsCredential.getRoleArn() != null) {
            arn = awsCredential.getRoleArn();
        } else {
            GetCallerIdentityResult callerIdentity = awsSecurityTokenService.getCallerIdentity(new GetCallerIdentityRequest());
            arn = callerIdentity.getArn();
        }

        List<String> failedActionList = new ArrayList<>();
        for (Map.Entry<String, List<String>> resourceAndAction : resourcesWithActions.entrySet()) {
            SimulatePrincipalPolicyRequest simulatePrincipalPolicyRequest = new SimulatePrincipalPolicyRequest();
            simulatePrincipalPolicyRequest.setPolicySourceArn(arn);
            simulatePrincipalPolicyRequest.setActionNames(resourceAndAction.getValue());
            simulatePrincipalPolicyRequest.setResourceArns(Collections.singleton(resourceAndAction.getKey()));
            SimulatePrincipalPolicyResult simulatePrincipalPolicyResult = amazonIdentityManagement.simulatePrincipalPolicy(simulatePrincipalPolicyRequest);
            simulatePrincipalPolicyResult.getEvaluationResults().stream()
                    .filter(evaluationResult -> evaluationResult.getEvalDecision().toLowerCase().contains("deny"))
                    .map(evaluationResult -> evaluationResult.getEvalActionName() + ":" + evaluationResult.getEvalResourceName())
                    .forEach(failedActionList::add);
        }
        if (!failedActionList.isEmpty()) {
            throw new AwsPermissionMissingException(String.format("CDP Credential '%s' doesn't have permission for these actions which are required: %s",
                    awsCredential.getName(), failedActionList));
        }
    } catch (IOException e) {
        throw new IllegalStateException("Can not parse aws policy json", e);
    }
}
 
Example #9
Source File: AwsCredentialVerifierTest.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Test
public void verifyCredentialTest() throws IOException, AwsPermissionMissingException {
    URL url = Resources.getResource("definitions/aws-cb-policy.json");
    String awsCbPolicy = Resources.toString(url, Charsets.UTF_8);
    when(awsPlatformParameters.getCredentialPoliciesJson()).thenReturn(Base64.getEncoder().encodeToString(awsCbPolicy.getBytes()));
    Map<String, Object> awsParameters = new HashMap<>();
    awsParameters.put("accessKey", "a");
    awsParameters.put("secretKey", "b");
    CloudCredential cloudCredential = new CloudCredential("id", "name", awsParameters, false);

    AmazonIdentityManagement amazonIdentityManagement = mock(AmazonIdentityManagement.class);
    when(awsClient.createAmazonIdentityManagement(any(AwsCredentialView.class))).thenReturn(amazonIdentityManagement);

    AWSSecurityTokenService awsSecurityTokenService = mock(AWSSecurityTokenService.class);
    GetCallerIdentityResult getCallerIdentityResult = new GetCallerIdentityResult();
    getCallerIdentityResult.setArn("arn");
    when(awsSecurityTokenService.getCallerIdentity(any(GetCallerIdentityRequest.class))).thenReturn(getCallerIdentityResult);
    when(awsClient.createAwsSecurityTokenService(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")
                .withEvalActionName("accepted_action1").withEvalResourceName("aws:ec2"));
        evaluationResults.add(new EvaluationResult().withEvalDecision("accept")
                .withEvalActionName("accepted_action2").withEvalResourceName("aws:ec2"));
        evaluationResults.add(new EvaluationResult().withEvalDecision("accept")
                .withEvalActionName("accepted_action3").withEvalResourceName("aws:ec2"));
        evaluationResults.add(new EvaluationResult().withEvalDecision("accept")
                .withEvalActionName("accepted_action4").withEvalResourceName("*"));
        simulatePrincipalPolicyResult.setEvaluationResults(evaluationResults);
        when(amazonIdentityManagement.simulatePrincipalPolicy(requestArgumentCaptor.capture())).thenReturn(simulatePrincipalPolicyResult);

    awsCredentialVerifier.validateAws(new AwsCredentialView(cloudCredential));
}
 
Example #10
Source File: AAWSTest.java    From aws-cf-templates with Apache License 2.0 4 votes vote down vote up
protected final String getAccount() {
    return this.sts.getCallerIdentity(new GetCallerIdentityRequest()).getAccount();
}
 
Example #11
Source File: AAWSTest.java    From aws-cf-templates with Apache License 2.0 4 votes vote down vote up
protected final String getCallerIdentityArn() {
    return this.sts.getCallerIdentity(new GetCallerIdentityRequest()).getArn();
}
 
Example #12
Source File: AwsCredentialVerifierTest.java    From cloudbreak with Apache License 2.0 4 votes vote down vote up
@Test
public void verifyCredentialAndThrowFailExceptionTest() throws IOException {
    URL url = Resources.getResource("definitions/aws-cb-policy.json");
    String awsCbPolicy = Resources.toString(url, Charsets.UTF_8);
    when(awsPlatformParameters.getCredentialPoliciesJson()).thenReturn(Base64.getEncoder().encodeToString(awsCbPolicy.getBytes()));
    Map<String, Object> awsParameters = new HashMap<>();
    awsParameters.put("accessKey", "a");
    awsParameters.put("secretKey", "b");
    CloudCredential cloudCredential = new CloudCredential("id", "name", awsParameters, false);

    AmazonIdentityManagement amazonIdentityManagement = mock(AmazonIdentityManagement.class);
    when(awsClient.createAmazonIdentityManagement(any(AwsCredentialView.class))).thenReturn(amazonIdentityManagement);

    AWSSecurityTokenService awsSecurityTokenService = mock(AWSSecurityTokenService.class);
    GetCallerIdentityResult getCallerIdentityResult = new GetCallerIdentityResult();
    getCallerIdentityResult.setArn("arn");
    when(awsSecurityTokenService.getCallerIdentity(any(GetCallerIdentityRequest.class))).thenReturn(getCallerIdentityResult);
    when(awsClient.createAwsSecurityTokenService(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")
                .withEvalActionName("denied_action1_" + i).withEvalResourceName("aws:ec2"));
        evaluationResults.add(new EvaluationResult().withEvalDecision("deny")
                .withEvalActionName("denied_action2_" + i).withEvalResourceName("aws:ec2"));
        evaluationResults.add(new EvaluationResult().withEvalDecision("deny")
                .withEvalActionName("denied_action3_" + i).withEvalResourceName("aws:ec2"));
        evaluationResults.add(new EvaluationResult().withEvalDecision("accept")
                .withEvalActionName("accepted_action_" + i).withEvalResourceName("*"));
        simulatePrincipalPolicyResult.setEvaluationResults(evaluationResults);
        i.getAndIncrement();
        return simulatePrincipalPolicyResult;
    });

    try {
        awsCredentialVerifier.validateAws(new AwsCredentialView(cloudCredential));
        fail("It shoud throw verification exception");
    } catch (AwsPermissionMissingException e) {
        Assert.assertThat(e.getMessage(), CoreMatchers.containsString("denied_action1"));
        Assert.assertThat(e.getMessage(), CoreMatchers.containsString("denied_action2"));
        Assert.assertThat(e.getMessage(), CoreMatchers.containsString("denied_action3"));
        Assert.assertThat(e.getMessage(), not(CoreMatchers.containsString("accepted_action")));
    }
    List<SimulatePrincipalPolicyRequest> allSimulatePrincipalPolicyRequest = requestArgumentCaptor.getAllValues();
    int simulateRequestNumber = 4;
    assertEquals("expect if " + simulateRequestNumber + " simulate request has been sent",
            simulateRequestNumber, allSimulatePrincipalPolicyRequest.size());
    allSimulatePrincipalPolicyRequest.forEach(simulatePrincipalPolicyRequest ->
            assertEquals("arn", simulatePrincipalPolicyRequest.getPolicySourceArn()));

}