com.amazonaws.services.securitytoken.AWSSecurityTokenService Java Examples

The following examples show how to use com.amazonaws.services.securitytoken.AWSSecurityTokenService. 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: AWSClientManagerImpl.java    From pacbot with Apache License 2.0 7 votes vote down vote up
/**
 * Gets the temp credentials using cred provider.
 *
 * @param roleArnWithAdequateAccess
 *            the role arn with adequate access
 * @param region
 *            the region
 * @param acp
 *            the acp
 * @param validForSeconds
 *            the valid for seconds
 * @return the temp credentials using cred provider
 */
private BasicSessionCredentials getTempCredentialsUsingCredProvider(String roleArnWithAdequateAccess,
        Regions region, AWSCredentialsProvider acp, Integer validForSeconds) {
    if (null == region) { // cloud trail case
        region = Regions.DEFAULT_REGION;
    }
    AWSSecurityTokenServiceClientBuilder stsBuilder = AWSSecurityTokenServiceClientBuilder.standard()
            .withCredentials(acp).withRegion(region);
    AWSSecurityTokenService sts = stsBuilder.build();
    AssumeRoleRequest assumeRequest = new AssumeRoleRequest().withRoleArn(roleArnWithAdequateAccess)
            .withDurationSeconds(validForSeconds).withRoleSessionName(PacmanSdkConstants.DEFAULT_SESSION_NAME);
    logger.debug("assume role request " + assumeRequest.toString());
    AssumeRoleResult assumeResult = sts.assumeRole(assumeRequest);
    logger.debug("assume role response " + assumeResult.toString());
    BasicSessionCredentials temporaryCredentials = new BasicSessionCredentials(assumeResult.getCredentials()
            .getAccessKeyId(), assumeResult.getCredentials().getSecretAccessKey(), assumeResult.getCredentials()
            .getSessionToken());

    return temporaryCredentials;
}
 
Example #2
Source File: CredentialProvider.java    From pacbot with Apache License 2.0 7 votes vote down vote up
/**
 * Gets the credentials.
 *
 * @param account the account
 * @param roleName the role name
 * @return the credentials
 */
public  BasicSessionCredentials getCredentials(String account,String roleName){
	
	BasicSessionCredentials baseAccntCreds = getBaseAccountCredentials(baseAccount,baseRegion,roleName);
	if(baseAccount.equals(account)){
		return baseAccntCreds;
	}
	AWSSecurityTokenServiceClientBuilder stsBuilder = AWSSecurityTokenServiceClientBuilder.standard().withCredentials( new AWSStaticCredentialsProvider(baseAccntCreds)).withRegion(baseRegion);
	AWSSecurityTokenService stsClient = stsBuilder.build();
    AssumeRoleRequest assumeRequest = new AssumeRoleRequest().withRoleArn(getRoleArn(account,roleName)).withRoleSessionName("pic-ro-"+account);
    AssumeRoleResult assumeResult = stsClient.assumeRole(assumeRequest);
    return  new BasicSessionCredentials(
            assumeResult.getCredentials()
                        .getAccessKeyId(), assumeResult.getCredentials().getSecretAccessKey(),
            assumeResult.getCredentials().getSessionToken());
}
 
Example #3
Source File: ConvertService.java    From alexa-meets-polly with Apache License 2.0 7 votes vote down vote up
public static AmazonS3 getS3Client(final String region, final String roleArn) {
    final Regions awsRegion = StringUtils.isNullOrEmpty(region) ? Regions.US_EAST_1 : Regions.fromName(region);

    if (StringUtils.isNullOrEmpty(roleArn)) {
        return AmazonS3ClientBuilder.standard().withRegion(awsRegion).build();
    } else {
        final AssumeRoleRequest assumeRole = new AssumeRoleRequest().withRoleArn(roleArn).withRoleSessionName("io-klerch-mp3-converter");

        final AWSSecurityTokenService sts = AWSSecurityTokenServiceClientBuilder.standard().withRegion(awsRegion).build();
        final Credentials credentials = sts.assumeRole(assumeRole).getCredentials();

        final BasicSessionCredentials sessionCredentials = new BasicSessionCredentials(
                credentials.getAccessKeyId(),
                credentials.getSecretAccessKey(),
                credentials.getSessionToken());

        return AmazonS3ClientBuilder.standard().withRegion(awsRegion).withCredentials(new AWSStaticCredentialsProvider(sessionCredentials)).build();
    }
}
 
Example #4
Source File: AmazonS3Factory.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
private AWSCredentialsProvider buildCredentialsProvider(final AWSCredentials credentials, final String region, final String assumeRole) {
  AWSCredentialsProvider credentialsProvider = new AWSStaticCredentialsProvider(credentials);
  if (isNullOrEmpty(assumeRole)) {
    return credentialsProvider;
  }
  else {
    // STS requires a region; fall back on the SDK default if not set
    String stsRegion;
    if (isNullOrEmpty(region)) {
      stsRegion = defaultRegion();
    }
    else {
      stsRegion = region;
    }
    AWSSecurityTokenService securityTokenService = AWSSecurityTokenServiceClientBuilder.standard()
        .withRegion(stsRegion)
        .withCredentials(credentialsProvider).build();

    return new STSAssumeRoleSessionCredentialsProvider.Builder(assumeRole, "nexus-s3-session")
        .withStsClient(securityTokenService)
        .build();
  }
}
 
Example #5
Source File: ZipkinKinesisCollectorModuleTest.java    From zipkin-aws with Apache License 2.0 6 votes vote down vote up
@Test
public void kinesisCollectorConfiguredForAWSWithGivenCredentials() {
  TestPropertyValues.of(
      "zipkin.collector.kinesis.stream-name: zipkin-test",
      "zipkin.collector.kinesis.app-name: zipkin",
      "zipkin.collector.kinesis.aws-sts-region: us-east-1",
      "zipkin.collector.kinesis.aws-access-key-id: x",
      "zipkin.collector.kinesis.aws-secret-access-key: x",
      "zipkin.collector.kinesis.aws-sts-role-arn: test")
      .applyTo(context);
  context.register(
      PropertyPlaceholderAutoConfiguration.class,
      ZipkinKinesisCollectorModule.class,
      ZipkinKinesisCredentialsConfiguration.class,
      InMemoryConfiguration.class);
  context.refresh();

  assertThat(context.getBean(KinesisCollector.class)).isNotNull();
  assertThat(context.getBean(AWSSecurityTokenService.class)).isNotNull();
  assertThat(context.getBean(AWSCredentialsProvider.class))
      .isInstanceOf(STSAssumeRoleSessionCredentialsProvider.class);
}
 
Example #6
Source File: CredentialProvider.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the credentials.
 *
 * @param account the account
 * @param roleName the role name
 * @return the credentials
 */
public  BasicSessionCredentials getCredentials(String account,String roleName){
	BasicSessionCredentials baseAccntCreds = getBaseAccountCredentials(roleName);
	if(baseAccount.equals(account)){
		return baseAccntCreds;
	}
	AWSSecurityTokenServiceClientBuilder stsBuilder = AWSSecurityTokenServiceClientBuilder.standard().withCredentials( new AWSStaticCredentialsProvider(baseAccntCreds)).withRegion(baseRegion);
	AWSSecurityTokenService stsClient = stsBuilder.build();
    AssumeRoleRequest assumeRequest = new AssumeRoleRequest().withRoleArn(getRoleArn(account,roleName)).withRoleSessionName("pic-ro-"+account);
    AssumeRoleResult assumeResult = stsClient.assumeRole(assumeRequest);
    return  new BasicSessionCredentials(
            assumeResult.getCredentials()
                        .getAccessKeyId(), assumeResult.getCredentials().getSecretAccessKey(),
            assumeResult.getCredentials().getSessionToken());
}
 
Example #7
Source File: AssumedRole.java    From pipeline-aws-plugin with Apache License 2.0 6 votes vote down vote up
private AssumedRole assumeRole(final AWSSecurityTokenService sts) {
	final AssumeRoleRequest assumeRoleRequest = new AssumeRoleRequest().withRoleArn(this.roleArn)
					.withRoleSessionName(this.sessionName)
					.withDurationSeconds(this.durationInSeconds);
	Optional.ofNullable(this.externalId).ifPresent(assumeRoleRequest::setExternalId);
	Optional.ofNullable(this.policy).ifPresent(assumeRoleRequest::withPolicy);
	AssumeRoleResult assumeRoleResult = sts.assumeRole(assumeRoleRequest);
	return new AssumedRole(assumeRoleResult.getCredentials(), assumeRoleResult.getAssumedRoleUser());
}
 
Example #8
Source File: STSCredentialsConfigurator.java    From cyberduck with GNU General Public License v3.0 6 votes vote down vote up
protected AWSSecurityTokenService getTokenService(final Host host, final String region, final String accessKey, final String secretKey, final String sessionToken) {
    final ClientConfiguration configuration = new CustomClientConfiguration(host,
        new ThreadLocalHostnameDelegatingTrustManager(trust, host.getHostname()), key);
    return AWSSecurityTokenServiceClientBuilder.standard()
        .withCredentials(new AWSStaticCredentialsProvider(StringUtils.isBlank(sessionToken) ? new AWSCredentials() {
            @Override
            public String getAWSAccessKeyId() {
                return accessKey;
            }

            @Override
            public String getAWSSecretKey() {
                return secretKey;
            }
        } : new AWSSessionCredentials() {
            @Override
            public String getAWSAccessKeyId() {
                return accessKey;
            }

            @Override
            public String getAWSSecretKey() {
                return secretKey;
            }

            @Override
            public String getSessionToken() {
                return sessionToken;
            }
        }))
        .withClientConfiguration(configuration)
        .withRegion(StringUtils.isNotBlank(region) ? Regions.fromName(region) : Regions.DEFAULT_REGION).build();
}
 
Example #9
Source File: AwsSessionCredentialClient.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
private AWSSecurityTokenService awsSecurityTokenServiceClient(AwsCredentialView awsCredential) {
    if (!awsEnvironmentVariableChecker.isAwsAccessKeyAvailable(awsCredential)
            || !awsEnvironmentVariableChecker.isAwsSecretAccessKeyAvailable(awsCredential)) {
        LOGGER.debug("AWSSecurityTokenServiceClient will use aws metadata because environment variables are undefined");
        return AWSSecurityTokenServiceClientBuilder.standard()
                .withRegion(awsDefaultZoneProvider.getDefaultZone(awsCredential))
                .withCredentials(new InstanceProfileCredentialsProvider())
                .build();
    } else {
        LOGGER.debug("AWSSecurityTokenServiceClient will use environment variables");
        return AWSSecurityTokenServiceClientBuilder.standard()
                .withRegion(awsDefaultZoneProvider.getDefaultZone(awsCredential))
                .withCredentials(DefaultAWSCredentialsProviderChain.getInstance())
                .build();
    }
}
 
Example #10
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 #11
Source File: WithAWSStep.java    From pipeline-aws-plugin with Apache License 2.0 6 votes vote down vote up
private void withFederatedUserId(@Nonnull EnvVars localEnv) {
	if (!StringUtils.isNullOrEmpty(this.step.getFederatedUserId())) {
		AWSSecurityTokenService sts = AWSClientFactory.create(AWSSecurityTokenServiceClientBuilder.standard(), this.envVars);
		GetFederationTokenRequest getFederationTokenRequest = new GetFederationTokenRequest();
		getFederationTokenRequest.setDurationSeconds(this.step.getDuration());
		getFederationTokenRequest.setName(this.step.getFederatedUserId());
		getFederationTokenRequest.setPolicy(ALLOW_ALL_POLICY);

		GetFederationTokenResult federationTokenResult = sts.getFederationToken(getFederationTokenRequest);

		Credentials credentials = federationTokenResult.getCredentials();
		localEnv.override(AWSClientFactory.AWS_ACCESS_KEY_ID, credentials.getAccessKeyId());
		localEnv.override(AWSClientFactory.AWS_SECRET_ACCESS_KEY, credentials.getSecretAccessKey());
		localEnv.override(AWSClientFactory.AWS_SESSION_TOKEN, credentials.getSessionToken());
		this.envVars.overrideAll(localEnv);
	}

}
 
Example #12
Source File: WithAWSStep.java    From pipeline-aws-plugin with Apache License 2.0 6 votes vote down vote up
private void withRole(@Nonnull EnvVars localEnv) throws IOException, InterruptedException {
	if (!StringUtils.isNullOrEmpty(this.step.getRole())) {
		
		AWSSecurityTokenService sts = AWSClientFactory.create(AWSSecurityTokenServiceClientBuilder.standard(), this.envVars);

		AssumeRole assumeRole = IamRoleUtils.validRoleArn(this.step.getRole()) ? new AssumeRole(this.step.getRole()) :
				new AssumeRole(this.step.getRole(), this.createAccountId(sts), IamRoleUtils.selectPartitionName(this.step.getRegion()));
		assumeRole.withDurationSeconds(this.step.getDuration());
		assumeRole.withExternalId(this.step.getExternalId());
		assumeRole.withPolicy(this.step.getPolicy());
		assumeRole.withSamlAssertion(this.step.getSamlAssertion(), this.step.getPrincipalArn());
		assumeRole.withSessionName(this.createRoleSessionName());

		this.getContext().get(TaskListener.class).getLogger().format("Requesting assume role");
		AssumedRole assumedRole = assumeRole.assumedRole(sts);
		this.getContext().get(TaskListener.class).getLogger().format("Assumed role %s with id %s %n ", assumedRole.getAssumedRoleUser().getArn(), assumedRole.getAssumedRoleUser().getAssumedRoleId());

		localEnv.override(AWSClientFactory.AWS_ACCESS_KEY_ID, assumedRole.getCredentials().getAccessKeyId());
		localEnv.override(AWSClientFactory.AWS_SECRET_ACCESS_KEY, assumedRole.getCredentials().getSecretAccessKey());
		localEnv.override(AWSClientFactory.AWS_SESSION_TOKEN, assumedRole.getCredentials().getSessionToken());
		this.envVars.overrideAll(localEnv);
	}
}
 
Example #13
Source File: ZipkinSQSCollectorModuleTest.java    From zipkin-aws with Apache License 2.0 6 votes vote down vote up
@Test
public void provideCollectorComponent_whenSqsQueueUrlIsSet() {
  context = new AnnotationConfigApplicationContext();
  TestPropertyValues.of(
      "zipkin.collector.sqs.queue-url:" + sqsRule.queueUrl(),
      "zipkin.collector.sqs.wait-time-seconds:1",
      "zipkin.collector.sqs.aws-access-key-id: x",
      "zipkin.collector.sqs.aws-secret-access-key: x")
      .applyTo(context);
  context.register(
      PropertyPlaceholderAutoConfiguration.class,
      Region.class,
      ZipkinSQSCollectorModule.class,
      ZipkinSQSCredentialsConfiguration.class,
      InMemoryConfiguration.class);
  context.refresh();

  assertThat(context.getBean(SQSCollector.class)).isNotNull();
  assertThat(context.getBean(AWSCredentialsProvider.class)).isNotNull();
  assertThatExceptionOfType(NoSuchBeanDefinitionException.class)
      .isThrownBy(() -> context.getBean(AWSSecurityTokenService.class));
}
 
Example #14
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 #15
Source File: CloudStore.java    From athenz with Apache License 2.0 5 votes vote down vote up
AWSSecurityTokenService getTokenServiceClient() {

        return AWSSecurityTokenServiceClientBuilder.standard()
                .withCredentials(new AWSStaticCredentialsProvider(credentials))
                .withRegion(Regions.fromName(awsRegion))
                .build();
    }
 
Example #16
Source File: AAWSTest.java    From aws-ec2-ssh with MIT License 5 votes vote down vote up
public AAWSTest() {
    super();
    if (Config.has(Config.Key.IAM_ROLE_ARN)) {
        final AWSSecurityTokenService sts = AWSSecurityTokenServiceClientBuilder.standard().withCredentials(new DefaultAWSCredentialsProviderChain()).build();
        this.credentialsProvider = new STSAssumeRoleSessionCredentialsProvider.Builder(Config.get(Config.Key.IAM_ROLE_ARN), IAM_SESSION_NAME).withStsClient(sts).build();
    } else {
        this.credentialsProvider = new DefaultAWSCredentialsProviderChain();
    }
    this.ec2 = AmazonEC2ClientBuilder.standard().withCredentials(this.credentialsProvider).build();
    this.iam = AmazonIdentityManagementClientBuilder.standard().withCredentials(this.credentialsProvider).build();
}
 
Example #17
Source File: InstanceAWSProvider.java    From athenz with Apache License 2.0 5 votes vote down vote up
AWSSecurityTokenService getInstanceClient(AWSAttestationData info) {
    
    String access = info.getAccess();
    if (access == null || access.isEmpty()) {
        LOGGER.error("getInstanceClient: No access key id available in instance document");
        return null;
    }
    
    String secret = info.getSecret();
    if (secret == null || secret.isEmpty()) {
        LOGGER.error("getInstanceClient: No secret access key available in instance document");
        return null;
    }
    
    String token = info.getToken();
    if (token == null || token.isEmpty()) {
        LOGGER.error("getInstanceClient: No token available in instance document");
        return null;
    }
    
    BasicSessionCredentials creds = new BasicSessionCredentials(access, secret, token);

    return AWSSecurityTokenServiceClientBuilder.standard()
            .withCredentials(new AWSStaticCredentialsProvider(creds))
            .withRegion(Regions.fromName(awsRegion))
            .build();
}
 
Example #18
Source File: AAWSTest.java    From aws-s3-virusscan with Apache License 2.0 5 votes vote down vote up
public AAWSTest() {
    super();
    if (Config.has(Config.Key.IAM_ROLE_ARN)) {
        final AWSSecurityTokenService local = AWSSecurityTokenServiceClientBuilder.standard().withCredentials(new DefaultAWSCredentialsProviderChain()).build();
        this.credentialsProvider = new STSAssumeRoleSessionCredentialsProvider.Builder(Config.get(Config.Key.IAM_ROLE_ARN), IAM_SESSION_NAME).withStsClient(local).build();
    } else {
        this.credentialsProvider = new DefaultAWSCredentialsProviderChain();
    }
    this.s3 = AmazonS3ClientBuilder.standard().withCredentials(this.credentialsProvider).build();
}
 
Example #19
Source File: AAWSTest.java    From aws-cf-templates with Apache License 2.0 5 votes vote down vote up
public AAWSTest() {
    super();
    if (Config.has(Config.Key.IAM_ROLE_ARN)) {
        final AWSSecurityTokenService local = AWSSecurityTokenServiceClientBuilder.standard().withCredentials(new DefaultAWSCredentialsProviderChain()).build();
        this.credentialsProvider = new STSAssumeRoleSessionCredentialsProvider.Builder(Config.get(Config.Key.IAM_ROLE_ARN), IAM_SESSION_NAME).withStsClient(local).build();
    } else {
        this.credentialsProvider = new DefaultAWSCredentialsProviderChain();
    }
    this.ec2 = AmazonEC2ClientBuilder.standard().withCredentials(this.credentialsProvider).build();
    this.iam = AmazonIdentityManagementClientBuilder.standard().withCredentials(this.credentialsProvider).build();
    this.s3 = AmazonS3ClientBuilder.standard().withCredentials(this.credentialsProvider).build();
    this.sts = AWSSecurityTokenServiceClientBuilder.standard().withCredentials(this.credentialsProvider).build();
}
 
Example #20
Source File: ExamplePlugin.java    From fullstop with Apache License 2.0 5 votes vote down vote up
private AmazonEC2 getClientForAccount(final String accountId, final Region region) {
    final AWSSecurityTokenService stsClient = AWSSecurityTokenServiceClient.builder()
            .withCredentials(new ProfileCredentialsProvider()).build();
    final String roleArn = String.format("arn:aws:iam::%s:role/fullstop-role", accountId);
    final String sessionName = "fullstop-role";
    final AWSCredentialsProvider tempCredentialsProvider = new STSAssumeRoleSessionCredentialsProvider.Builder(roleArn, sessionName)
            .withStsClient(stsClient)
            .withRoleSessionDurationSeconds(3600)
            .build();
    return AmazonEC2Client.builder().withCredentials(tempCredentialsProvider).withRegion(region.getName()).build();
}
 
Example #21
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 #22
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 #23
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 #24
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 #25
Source File: AssumeRoleCredentialsStrategy.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Override
public AWSCredentialsProvider getDerivedCredentialsProvider(Map<PropertyDescriptor, String> properties,
                                                            AWSCredentialsProvider primaryCredentialsProvider) {
    final String assumeRoleArn = properties.get(ASSUME_ROLE_ARN);
    final String assumeRoleName = properties.get(ASSUME_ROLE_NAME);
    String rawMaxSessionTime = properties.get(MAX_SESSION_TIME);
    rawMaxSessionTime = (rawMaxSessionTime != null) ? rawMaxSessionTime : MAX_SESSION_TIME.getDefaultValue();
    final Integer maxSessionTime = Integer.parseInt(rawMaxSessionTime.trim());
    final String assumeRoleExternalId = properties.get(ASSUME_ROLE_EXTERNAL_ID);
    STSAssumeRoleSessionCredentialsProvider.Builder builder;
    ClientConfiguration config = new ClientConfiguration();

    // If proxy variables are set, then create Client Configuration with those values
    if (proxyVariablesValidForAssumeRole(properties)) {
        final String assumeRoleProxyHost = properties.get(ASSUME_ROLE_PROXY_HOST);
        final Integer assumeRoleProxyPort = Integer.parseInt(properties.get(ASSUME_ROLE_PROXY_PORT));
        config.withProxyHost(assumeRoleProxyHost);
        config.withProxyPort(assumeRoleProxyPort);
    }

    AWSSecurityTokenService securityTokenService = new AWSSecurityTokenServiceClient(primaryCredentialsProvider, config);
    builder = new STSAssumeRoleSessionCredentialsProvider
            .Builder(assumeRoleArn, assumeRoleName)
            .withStsClient(securityTokenService)
            .withRoleSessionDurationSeconds(maxSessionTime);

    if (assumeRoleExternalId != null && !assumeRoleExternalId.isEmpty()) {
        builder = builder.withExternalId(assumeRoleExternalId);
    }

    final AWSCredentialsProvider credsProvider = builder.build();

    return credsProvider;
}
 
Example #26
Source File: ZipkinKinesisCredentialsConfiguration.java    From zipkin-aws with Apache License 2.0 5 votes vote down vote up
/** Setup {@link AWSSecurityTokenService} client an IAM role to assume is given. */
@Bean
@ConditionalOnMissingBean
@Conditional(STSSetCondition.class)
AWSSecurityTokenService securityTokenService(ZipkinKinesisCollectorProperties properties) {
  return AWSSecurityTokenServiceClientBuilder.standard()
      .withCredentials(getDefaultCredentialsProvider(properties))
      .withRegion(properties.getAwsStsRegion())
      .build();
}
 
Example #27
Source File: AssumeRoleCredentialsStrategy.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
@Override
public AWSCredentialsProvider getDerivedCredentialsProvider(Map<PropertyDescriptor, String> properties,
                                                            AWSCredentialsProvider primaryCredentialsProvider) {
    final String assumeRoleArn = properties.get(ASSUME_ROLE_ARN);
    final String assumeRoleName = properties.get(ASSUME_ROLE_NAME);
    String rawMaxSessionTime = properties.get(MAX_SESSION_TIME);
    rawMaxSessionTime = (rawMaxSessionTime != null) ? rawMaxSessionTime : MAX_SESSION_TIME.getDefaultValue();
    final Integer maxSessionTime = Integer.parseInt(rawMaxSessionTime.trim());
    final String assumeRoleExternalId = properties.get(ASSUME_ROLE_EXTERNAL_ID);
    STSAssumeRoleSessionCredentialsProvider.Builder builder;
    ClientConfiguration config = new ClientConfiguration();

    // If proxy variables are set, then create Client Configuration with those values
    if (proxyVariablesValidForAssumeRole(properties)) {
        final String assumeRoleProxyHost = properties.get(ASSUME_ROLE_PROXY_HOST);
        final Integer assumeRoleProxyPort = Integer.parseInt(properties.get(ASSUME_ROLE_PROXY_PORT));
        config.withProxyHost(assumeRoleProxyHost);
        config.withProxyPort(assumeRoleProxyPort);
    }

    AWSSecurityTokenService securityTokenService = new AWSSecurityTokenServiceClient(primaryCredentialsProvider, config);
    builder = new STSAssumeRoleSessionCredentialsProvider
            .Builder(assumeRoleArn, assumeRoleName)
            .withStsClient(securityTokenService)
            .withRoleSessionDurationSeconds(maxSessionTime);

    if (assumeRoleExternalId != null && !assumeRoleExternalId.isEmpty()) {
        builder = builder.withExternalId(assumeRoleExternalId);
    }

    final AWSCredentialsProvider credsProvider = builder.build();

    return credsProvider;
}
 
Example #28
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 #29
Source File: ProfileCredentialProvider.java    From strongbox with Apache License 2.0 5 votes vote down vote up
/**
 * Resolve AWS credentials based on MFA/Assume role
 *
 * We will assume that if mfa_serial is defined, then role_arn and source_profile also has to be specified.
 *
 * Please note that Strongbox differ from the AWS CLI in the following:
 * AWS CLI: 'Note that configuration variables for using IAM roles can only be in the AWS CLI config file.'
 * Strongbox: '--assume-role' can be specified explicitly
 *
 * https://docs.aws.amazon.com/cli/latest/topic/config-vars.html#using-aws-iam-roles
 */
private AWSCredentials assumeRole(ClientConfiguration clientConfiguration,
                                  ConfigProviderChain configProvider,
                                  ProfileIdentifier profile,
                                  RoleARN roleToAssume) {

    Optional<ProfileIdentifier> sourceProfile = configProvider.getSourceProfile(profile);
    if (!sourceProfile.isPresent()) {
        throw new IllegalStateException(String.format("'%s' must be specified when using '%s' for profile '%s'",
                AWSConfigPropertyKey.SOURCE_PROFILE,
                AWSConfigPropertyKey.ROLE_ARN,
                profile.name));
    }

    SessionCache sessionCache = new SessionCache(profile, roleToAssume);
    Optional<BasicSessionCredentials> cachedCredentials = sessionCache.load();

    if (cachedCredentials.isPresent()) {
        return cachedCredentials.get();
    } else {
        AWSCredentialsProvider staticCredentialsProvider = new AWSStaticCredentialsProvider(getStaticCredentials(configProvider, sourceProfile.get()));

        AWSSecurityTokenService client = AWSSecurityTokenServiceClientBuilder.standard()
                .withCredentials(staticCredentialsProvider)
                .withClientConfiguration(transformAndVerifyOrThrow(clientConfiguration))
                .withRegion(RegionResolver.getRegion())
                .build();

        String sessionId = String.format("strongbox-cli-session-%s", ZonedDateTime.now().toEpochSecond());

        AssumeRoleRequest request = new AssumeRoleRequest();
        request.withRoleArn(roleToAssume.toArn())
                .withRoleSessionName(sessionId);

        Optional<String> mfaSerial = configProvider.getMFASerial(profile);
        if (mfaSerial.isPresent()) {
            MFAToken mfaToken = mfaTokenSupplier.get();

            request.withSerialNumber(mfaSerial.get())
                    .withTokenCode(mfaToken.value);
        }

        AssumeRoleResult result = client.assumeRole(request);
        Credentials credentials = result.getCredentials();

        BasicSessionCredentials basicSessionCredentials = new BasicSessionCredentials(credentials.getAccessKeyId(), credentials.getSecretAccessKey(), credentials.getSessionToken());

        sessionCache.save(result.getAssumedRoleUser(),
                basicSessionCredentials,
                ZonedDateTime.ofInstant(credentials.getExpiration().toInstant(), ZoneId.of("UTC")));

        return basicSessionCredentials;
    }
}
 
Example #30
Source File: GroupModel.java    From strongbox with Apache License 2.0 5 votes vote down vote up
private AWSCredentialsProvider assumeRole(AWSCredentialsProvider longLivedAWSCredentials, ClientConfiguration clientConfiguration, String assumeRoleArn) {
    AWSSecurityTokenService client = AWSSecurityTokenServiceClientBuilder.standard()
            .withCredentials(longLivedAWSCredentials)
            .withClientConfiguration(transformAndVerifyOrThrow(clientConfiguration))
            .withRegion(RegionResolver.getRegion())
            .build();

    STSAssumeRoleSessionCredentialsProvider.Builder builder =
            new STSAssumeRoleSessionCredentialsProvider.Builder(assumeRoleArn, "strongbox-cli");
    builder.withStsClient(client);

    return builder.build();
}