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;
}
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());
}
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();
}
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;
}
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();
}
Aggregations