Search in sources :

Example 41 with AssumeRoleRequest

use of com.amazonaws.services.securitytoken.model.AssumeRoleRequest in project athenz by AthenZ.

the class CloudStore method getAssumeRoleRequest.

AssumeRoleRequest getAssumeRoleRequest(String account, String roleName, Integer durationSeconds, String externalId) {
    // assume the target role to get the credentials for the client
    // aws format is arn:aws:iam::<account-id>:role/<role-name>
    final String arn = "arn:aws:iam::" + account + ":role/" + roleName;
    AssumeRoleRequest req = new AssumeRoleRequest();
    req.setRoleArn(arn);
    // for role session name AWS has a limit on length: 64
    // so we need to make sure our session is shorter than that
    req.setRoleSessionName(AWS_ROLE_SESSION_NAME);
    if (durationSeconds != null && durationSeconds > 0) {
        req.setDurationSeconds(durationSeconds);
    }
    if (externalId != null && !externalId.isEmpty()) {
        req.setExternalId(externalId);
    }
    return req;
}
Also used : AssumeRoleRequest(com.amazonaws.services.securitytoken.model.AssumeRoleRequest)

Example 42 with AssumeRoleRequest

use of com.amazonaws.services.securitytoken.model.AssumeRoleRequest in project Fidelius by FINRAOS.

the class AWSSessionService method getFreshCredentials.

private BasicSessionCredentials getFreshCredentials(AWSEnvironment environment) throws Exception {
    String roleArn = getRoleArn(environment.getAccount(), assumeRole);
    logger.info("Assuming to role: " + roleArn + " for environment " + environment.getAccount() + " on region " + environment.getRegion() + " with timeout of " + (sessionTimeout / 1000) + " seconds (with " + (sessionTimeoutPad / 1000) + " padding.)");
    AssumeRoleRequest assumeRequest = new AssumeRoleRequest().withRoleArn(roleArn).withDurationSeconds((sessionTimeout + sessionTimeoutPad) / 1000).withRoleSessionName("CREDSTSH_APP");
    AssumeRoleResult assumeResult = awsSessionFactory.createSecurityTokenServiceClient().assumeRole(assumeRequest);
    return new BasicSessionCredentials(assumeResult.getCredentials().getAccessKeyId(), assumeResult.getCredentials().getSecretAccessKey(), assumeResult.getCredentials().getSessionToken());
}
Also used : AssumeRoleRequest(com.amazonaws.services.securitytoken.model.AssumeRoleRequest) BasicSessionCredentials(com.amazonaws.auth.BasicSessionCredentials) AssumeRoleResult(com.amazonaws.services.securitytoken.model.AssumeRoleResult)

Example 43 with AssumeRoleRequest

use of com.amazonaws.services.securitytoken.model.AssumeRoleRequest in project aws-sdk-android by aws-amplify.

the class STSAssumeRoleSessionCredentialsProvider method startSession.

/**
 * Starts a new session by sending a request to the AWS Security Token
 * Service (STS) to assume a Role using the long lived AWS credentials. This
 * class then vends the short lived session credentials for the assumed Role
 * sent back from STS.
 */
private void startSession() {
    AssumeRoleResult assumeRoleResult = securityTokenService.assumeRole(new AssumeRoleRequest().withRoleArn(roleArn).withDurationSeconds(DEFAULT_DURATION_SECONDS).withRoleSessionName(roleSessionName));
    Credentials stsCredentials = assumeRoleResult.getCredentials();
    sessionCredentials = new BasicSessionCredentials(stsCredentials.getAccessKeyId(), stsCredentials.getSecretAccessKey(), stsCredentials.getSessionToken());
    sessionCredentialsExpiration = stsCredentials.getExpiration();
}
Also used : AssumeRoleRequest(com.amazonaws.services.securitytoken.model.AssumeRoleRequest) AssumeRoleResult(com.amazonaws.services.securitytoken.model.AssumeRoleResult) Credentials(com.amazonaws.services.securitytoken.model.Credentials)

Example 44 with AssumeRoleRequest

use of com.amazonaws.services.securitytoken.model.AssumeRoleRequest in project cyberduck by iterate-ch.

the class STSCredentialsConfigurator method configure.

public Credentials configure(final Host host) throws LoginFailureException, LoginCanceledException {
    final Credentials credentials = new Credentials(host.getCredentials());
    // See https://docs.aws.amazon.com/sdkref/latest/guide/creds-config-files.html for configuration behavior
    final Local awsDirectory = LocalFactory.get(LocalFactory.get(), ".aws");
    final Local configFile = LocalFactory.get(awsDirectory, "config");
    final Local credentialsFile = LocalFactory.get(awsDirectory, "credentials");
    // Profile can be null. The default profile from the configuration will be loaded
    final String profile = host.getCredentials().getUsername();
    if (log.isDebugEnabled()) {
        log.debug(String.format("Look for profile name %s in %s and %s", profile, configFile, credentialsFile));
    }
    // Iterating all profiles on our own because AWSProfileCredentialsConfigurator does not support MFA tokens
    final Map<String, Map<String, String>> allProfileProperties = new HashMap<>();
    try {
        final Map<String, Map<String, String>> credentialsFileProfileProperties = new ProfilesConfigFileLoaderHelper().parseProfileProperties(credentialsFile);
        allProfileProperties.putAll(credentialsFileProfileProperties);
        final Map<String, Map<String, String>> configFileProfileProperties = new ProfilesConfigFileLoaderHelper().parseProfileProperties(configFile);
        for (Map.Entry<String, Map<String, String>> entry : configFileProfileProperties.entrySet()) {
            final String profileName = entry.getKey();
            final Map<String, String> configFileProperties = entry.getValue();
            final Map<String, String> credentialsFileProperties = allProfileProperties.get(profileName);
            // If the credentials file had properties, then merge them in
            if (credentialsFileProperties != null) {
                configFileProperties.putAll(credentialsFileProperties);
            }
            allProfileProperties.put(profileName, configFileProperties);
        }
    } catch (AccessDeniedException | IllegalArgumentException | IOException e) {
        log.warn(String.format("Failure reading %s and %s", configFile, credentialsFile), e);
        return credentials;
    }
    if (allProfileProperties.isEmpty()) {
        log.warn("Missing configuration file ~/.aws/credentials or ~/.aws/config. Skip auto configuration");
        return host.getCredentials();
    }
    // Convert the loaded property map to credential objects
    final Map<String, BasicProfile> profilesByName = new LinkedHashMap<>();
    for (Map.Entry<String, Map<String, String>> entry : allProfileProperties.entrySet()) {
        String profileName = entry.getKey();
        Map<String, String> properties = entry.getValue();
        profilesByName.put(profileName, new BasicProfile(profileName, properties));
    }
    final Map<String, BasicProfile> profiles = new AllProfiles(profilesByName).getProfiles();
    final Optional<Map.Entry<String, BasicProfile>> optional = profiles.entrySet().stream().filter(new Predicate<Map.Entry<String, BasicProfile>>() {

        @Override
        public boolean test(final Map.Entry<String, BasicProfile> entry) {
            final String profileName = entry.getKey();
            final BasicProfile basicProfile = entry.getValue();
            final String awsAccessIdKey = basicProfile.getAwsAccessIdKey();
            // Matching access key or profile name
            if (StringUtils.equals(profileName, profile) || StringUtils.equals(awsAccessIdKey, profile)) {
                if (log.isDebugEnabled()) {
                    log.debug(String.format("Found matching profile %s", profile));
                }
                return true;
            }
            return false;
        }
    }).findFirst();
    if (optional.isPresent()) {
        final Map.Entry<String, BasicProfile> entry = optional.get();
        final BasicProfile basicProfile = entry.getValue();
        if (basicProfile.isRoleBasedProfile()) {
            if (log.isDebugEnabled()) {
                log.debug(String.format("Configure credentials from role based profile %s", basicProfile.getProfileName()));
            }
            if (StringUtils.isBlank(basicProfile.getRoleSourceProfile())) {
                throw new LoginFailureException(String.format("Missing source profile reference in profile %s", basicProfile.getProfileName()));
            } else if (!profiles.containsKey(basicProfile.getRoleSourceProfile())) {
                throw new LoginFailureException(String.format("Missing source profile with name %s", basicProfile.getRoleSourceProfile()));
            } else {
                final BasicProfile sourceProfile = profiles.get(basicProfile.getRoleSourceProfile());
                // If a profile defines the role_arn property then the profile is treated as an assume role profile
                final AWSSecurityTokenService service = this.getTokenService(host, host.getRegion(), sourceProfile.getAwsAccessIdKey(), sourceProfile.getAwsSecretAccessKey(), sourceProfile.getAwsSessionToken());
                final String tokenCode;
                if (basicProfile.getProperties().containsKey("mfa_serial")) {
                    tokenCode = prompt.prompt(host, LocaleFactory.localizedString("Provide additional login credentials", "Credentials"), String.format("%s %s", LocaleFactory.localizedString("Multi-Factor Authentication", "S3"), basicProfile.getPropertyValue("mfa_serial")), new LoginOptions(host.getProtocol()).password(true).passwordPlaceholder(LocaleFactory.localizedString("MFA Authentication Code", "S3")).keychain(false)).getPassword();
                } else {
                    tokenCode = null;
                }
                final Integer durationSeconds;
                if (basicProfile.getProperties().containsKey("duration_seconds")) {
                    durationSeconds = Integer.valueOf(basicProfile.getPropertyValue("duration_seconds"));
                } else {
                    durationSeconds = null;
                }
                // Starts a new session by sending a request to the AWS Security Token Service (STS) to assume a
                // Role using the long lived AWS credentials
                final AssumeRoleRequest assumeRoleRequest = new AssumeRoleRequest().withExternalId(basicProfile.getRoleExternalId()).withRoleArn(basicProfile.getRoleArn()).withSerialNumber(basicProfile.getPropertyValue("mfa_serial")).withTokenCode(tokenCode).withRoleSessionName(new AsciiRandomStringService().random()).withDurationSeconds(durationSeconds);
                if (log.isDebugEnabled()) {
                    log.debug(String.format("Request %s from %s", assumeRoleRequest, service));
                }
                try {
                    final AssumeRoleResult assumeRoleResult = service.assumeRole(assumeRoleRequest);
                    if (log.isDebugEnabled()) {
                        log.debug(String.format("Set credentials from %s", assumeRoleResult));
                    }
                    credentials.setUsername(assumeRoleResult.getCredentials().getAccessKeyId());
                    credentials.setPassword(assumeRoleResult.getCredentials().getSecretAccessKey());
                    credentials.setToken(assumeRoleResult.getCredentials().getSessionToken());
                } catch (AWSSecurityTokenServiceException e) {
                    throw new LoginFailureException(e.getErrorMessage(), e);
                }
            }
        } else {
            if (log.isDebugEnabled()) {
                log.debug(String.format("Configure credentials from basic profile %s", basicProfile.getProfileName()));
            }
            final Map<String, String> profileProperties = basicProfile.getProperties();
            if (profileProperties.containsKey("sso_start_url")) {
                // Read cached SSO credentials
                final CachedCredential cached = this.fetchSsoCredentials(credentials, profileProperties, awsDirectory);
                credentials.setUsername(cached.accessKey);
                credentials.setPassword(cached.secretKey);
                credentials.setToken(cached.sessionToken);
            } else if (StringUtils.isNotBlank(basicProfile.getAwsSessionToken())) {
                // No need to obtain session token if preconfigured in profile
                if (log.isDebugEnabled()) {
                    log.debug(String.format("Set session token credentials from profile %s", profile));
                }
                credentials.setUsername(basicProfile.getAwsAccessIdKey());
                credentials.setPassword(basicProfile.getAwsSecretAccessKey());
                credentials.setToken(basicProfile.getAwsSessionToken());
            } else {
                if (host.getProtocol().isTokenConfigurable()) {
                    // Obtain session token
                    if (log.isDebugEnabled()) {
                        log.debug(String.format("Get session token from credentials in profile %s", basicProfile.getProfileName()));
                    }
                    final AWSSecurityTokenService service = this.getTokenService(host, host.getRegion(), basicProfile.getAwsAccessIdKey(), basicProfile.getAwsSecretAccessKey(), basicProfile.getAwsSessionToken());
                    final GetSessionTokenRequest sessionTokenRequest = new GetSessionTokenRequest();
                    if (log.isDebugEnabled()) {
                        log.debug(String.format("Request %s from %s", sessionTokenRequest, service));
                    }
                    try {
                        final GetSessionTokenResult sessionTokenResult = service.getSessionToken(sessionTokenRequest);
                        if (log.isDebugEnabled()) {
                            log.debug(String.format("Set credentials from %s", sessionTokenResult));
                        }
                        credentials.setUsername(sessionTokenResult.getCredentials().getAccessKeyId());
                        credentials.setPassword(sessionTokenResult.getCredentials().getSecretAccessKey());
                        credentials.setToken(sessionTokenResult.getCredentials().getSessionToken());
                    } catch (AWSSecurityTokenServiceException e) {
                        throw new LoginFailureException(e.getErrorMessage(), e);
                    }
                } else {
                    if (log.isDebugEnabled()) {
                        log.debug(String.format("Set static credentials from profile %s", basicProfile.getProfileName()));
                    }
                    credentials.setUsername(basicProfile.getAwsAccessIdKey());
                    credentials.setPassword(basicProfile.getAwsSecretAccessKey());
                }
            }
        }
    }
    return credentials;
}
Also used : AssumeRoleRequest(com.amazonaws.services.securitytoken.model.AssumeRoleRequest) AccessDeniedException(ch.cyberduck.core.exception.AccessDeniedException) AllProfiles(com.amazonaws.auth.profile.internal.AllProfiles) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) LinkedHashMap(java.util.LinkedHashMap) Predicate(java.util.function.Predicate) LoginOptions(ch.cyberduck.core.LoginOptions) AWSSecurityTokenServiceException(com.amazonaws.services.securitytoken.model.AWSSecurityTokenServiceException) BasicProfile(com.amazonaws.auth.profile.internal.BasicProfile) AsciiRandomStringService(ch.cyberduck.core.AsciiRandomStringService) GetSessionTokenResult(com.amazonaws.services.securitytoken.model.GetSessionTokenResult) Local(ch.cyberduck.core.Local) IOException(java.io.IOException) AssumeRoleResult(com.amazonaws.services.securitytoken.model.AssumeRoleResult) LoginFailureException(ch.cyberduck.core.exception.LoginFailureException) GetSessionTokenRequest(com.amazonaws.services.securitytoken.model.GetSessionTokenRequest) Map(java.util.Map) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) AWSSecurityTokenService(com.amazonaws.services.securitytoken.AWSSecurityTokenService) AWSCredentials(com.amazonaws.auth.AWSCredentials) AWSSessionCredentials(com.amazonaws.auth.AWSSessionCredentials) Credentials(ch.cyberduck.core.Credentials)

Example 45 with AssumeRoleRequest

use of com.amazonaws.services.securitytoken.model.AssumeRoleRequest in project knime-cloud by knime.

the class AmazonIdentityManagementConnection method getRoleAssumedIdentityManagementClient.

/**
 * Creates and returns a new instance of the {@link AmazonIdentityManagement} client using rule assumption.
 *
 * @param connectionInformation The connection information
 * @return AmazonIdentityManagement client
 * @throws Exception thrown if client could not be instantiated
 */
private static final AmazonIdentityManagement getRoleAssumedIdentityManagementClient(final CloudConnectionInformation connectionInformation) throws Exception {
    final AWSSecurityTokenServiceClientBuilder builder = AWSSecurityTokenServiceClientBuilder.standard().withRegion(connectionInformation.getHost());
    if (!connectionInformation.useKeyChain()) {
        final AWSCredentials credentials = getCredentials(connectionInformation);
        builder.withCredentials(new AWSStaticCredentialsProvider(credentials));
    }
    final AWSSecurityTokenService stsClient = builder.build();
    final AssumeRoleRequest assumeRoleRequest = new AssumeRoleRequest().withRoleArn(buildARN(connectionInformation)).withDurationSeconds(3600).withRoleSessionName("KNIME_AmazonIdentityManagement_Connection");
    final AssumeRoleResult assumeResult = stsClient.assumeRole(assumeRoleRequest);
    final BasicSessionCredentials tempCredentials = new BasicSessionCredentials(assumeResult.getCredentials().getAccessKeyId(), assumeResult.getCredentials().getSecretAccessKey(), assumeResult.getCredentials().getSessionToken());
    final ClientConfiguration clientConfig = new ClientConfiguration().withConnectionTimeout(connectionInformation.getTimeout());
    return AmazonIdentityManagementClientBuilder.standard().withClientConfiguration(clientConfig).withCredentials(new AWSStaticCredentialsProvider(tempCredentials)).withRegion(connectionInformation.getHost()).build();
}
Also used : AssumeRoleRequest(com.amazonaws.services.securitytoken.model.AssumeRoleRequest) AWSStaticCredentialsProvider(com.amazonaws.auth.AWSStaticCredentialsProvider) BasicSessionCredentials(com.amazonaws.auth.BasicSessionCredentials) AWSSecurityTokenServiceClientBuilder(com.amazonaws.services.securitytoken.AWSSecurityTokenServiceClientBuilder) AssumeRoleResult(com.amazonaws.services.securitytoken.model.AssumeRoleResult) BasicAWSCredentials(com.amazonaws.auth.BasicAWSCredentials) AWSCredentials(com.amazonaws.auth.AWSCredentials) AWSSecurityTokenService(com.amazonaws.services.securitytoken.AWSSecurityTokenService) ClientConfiguration(com.amazonaws.ClientConfiguration)

Aggregations

AssumeRoleRequest (com.amazonaws.services.securitytoken.model.AssumeRoleRequest)53 AssumeRoleResult (com.amazonaws.services.securitytoken.model.AssumeRoleResult)42 BasicSessionCredentials (com.amazonaws.auth.BasicSessionCredentials)30 AWSSecurityTokenService (com.amazonaws.services.securitytoken.AWSSecurityTokenService)28 Regions (com.amazonaws.regions.Regions)13 AWSStaticCredentialsProvider (com.amazonaws.auth.AWSStaticCredentialsProvider)11 BasicAWSCredentials (com.amazonaws.auth.BasicAWSCredentials)11 Credentials (com.amazonaws.services.securitytoken.model.Credentials)11 AWSCredentials (com.amazonaws.auth.AWSCredentials)10 AmazonDynamoDBClient (com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient)10 AWSSecurityTokenServiceClientBuilder (com.amazonaws.services.securitytoken.AWSSecurityTokenServiceClientBuilder)8 AWSSecurityTokenServiceClient (com.amazonaws.services.securitytoken.AWSSecurityTokenServiceClient)7 AutomationException (exceptions.AutomationException)7 ClientConfiguration (com.amazonaws.ClientConfiguration)6 AmazonServiceException (com.amazonaws.AmazonServiceException)4 AWSCredentialsProvider (com.amazonaws.auth.AWSCredentialsProvider)4 DeleteItemSpec (com.amazonaws.services.dynamodbv2.document.spec.DeleteItemSpec)3 AWSSessionCredentials (com.amazonaws.auth.AWSSessionCredentials)2 AnonymousAWSCredentials (com.amazonaws.auth.AnonymousAWSCredentials)2 ValueMap (com.amazonaws.services.dynamodbv2.document.utils.ValueMap)2