-
Notifications
You must be signed in to change notification settings - Fork 47
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
4a0d15b
commit 6bcfc68
Showing
17 changed files
with
1,870 additions
and
4 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
54 changes: 54 additions & 0 deletions
54
examples/AWSDriverExample/src/main/java/software/amazon/FederatedAuthPluginExample.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,54 @@ | ||
/* | ||
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"). | ||
* You may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
|
||
package software.amazon; | ||
|
||
import software.amazon.jdbc.PropertyDefinition; | ||
import software.amazon.jdbc.plugin.federatedauth.FederatedAuthPlugin; | ||
import java.sql.Connection; | ||
import java.sql.DriverManager; | ||
import java.sql.ResultSet; | ||
import java.sql.SQLException; | ||
import java.sql.Statement; | ||
import java.util.Properties; | ||
|
||
public class FederatedAuthPluginExample { | ||
|
||
private static final String CONNECTION_STRING = "jdbc:aws-wrapper:postgresql://db-identifier.XYZ.us-east-2.rds.amazonaws.com:5432/employees"; | ||
|
||
public static void main(String[] args) throws SQLException { | ||
// Set the AWS Federated Authentication Connection Plugin parameters and the JDBC Wrapper parameters. | ||
final Properties properties = new Properties(); | ||
|
||
// Enable the AWS Federated Authentication Connection Plugin. | ||
properties.setProperty(PropertyDefinition.PLUGINS.name, "federatedAuth"); | ||
properties.setProperty(FederatedAuthPlugin.IDP_NAME.name, "adfs"); | ||
properties.setProperty(FederatedAuthPlugin.IDP_ENDPOINT.name, "ec2amaz-ab3cdef.example.com"); | ||
properties.setProperty(FederatedAuthPlugin.IAM_ROLE_ARN.name, "arn:aws:iam::123456789012:role/adfs_example_iam_role"); | ||
properties.setProperty(FederatedAuthPlugin.IAM_IDP_ARN.name, "arn:aws:iam::123456789012:saml-provider/adfs_example"); | ||
properties.setProperty(FederatedAuthPlugin.IAM_REGION.name, "us-east-2"); | ||
properties.setProperty(FederatedAuthPlugin.IDP_USERNAME.name, "[email protected]"); | ||
properties.setProperty(FederatedAuthPlugin.IDP_PASSWORD.name, "somePassword"); | ||
properties.setProperty(PropertyDefinition.USER.name, "someIamUser"); | ||
|
||
// Try and make a connection: | ||
try (final Connection conn = DriverManager.getConnection(CONNECTION_STRING, properties); | ||
final Statement statement = conn.createStatement(); | ||
final ResultSet rs = statement.executeQuery("SELECT 1")) { | ||
System.out.println(Util.getResult(rs)); | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
239 changes: 239 additions & 0 deletions
239
...c/main/java/software/amazon/jdbc/plugin/federatedauth/AdfsCredentialsProviderFactory.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,239 @@ | ||
/* | ||
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"). | ||
* You may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
|
||
package software.amazon.jdbc.plugin.federatedauth; | ||
|
||
import java.io.IOException; | ||
import java.net.MalformedURLException; | ||
import java.net.URI; | ||
import java.util.ArrayList; | ||
import java.util.HashSet; | ||
import java.util.List; | ||
import java.util.Properties; | ||
import java.util.Set; | ||
import java.util.logging.Logger; | ||
import java.util.regex.Matcher; | ||
import java.util.regex.Pattern; | ||
import org.apache.http.NameValuePair; | ||
import org.apache.http.client.entity.UrlEncodedFormEntity; | ||
import org.apache.http.client.methods.CloseableHttpResponse; | ||
import org.apache.http.client.methods.HttpGet; | ||
import org.apache.http.client.methods.HttpPost; | ||
import org.apache.http.impl.client.CloseableHttpClient; | ||
import org.apache.http.message.BasicNameValuePair; | ||
import org.apache.http.util.EntityUtils; | ||
import org.checkerframework.checker.nullness.qual.NonNull; | ||
import software.amazon.jdbc.PluginService; | ||
import software.amazon.jdbc.util.Messages; | ||
import software.amazon.jdbc.util.StringUtils; | ||
import software.amazon.jdbc.util.telemetry.TelemetryContext; | ||
import software.amazon.jdbc.util.telemetry.TelemetryFactory; | ||
import software.amazon.jdbc.util.telemetry.TelemetryTraceLevel; | ||
|
||
public class AdfsCredentialsProviderFactory extends SamlCredentialsProviderFactory { | ||
|
||
public static final String IDP_NAME = "adfs"; | ||
private static final String TELEMETRY_FETCH_SAML = "Fetch ADFS SAML Assertion"; | ||
private static final Logger LOGGER = Logger.getLogger(AdfsCredentialsProviderFactory.class.getName()); | ||
private final PluginService pluginService; | ||
private final TelemetryFactory telemetryFactory; | ||
private final CloseableHttpClient httpClient; | ||
private TelemetryContext telemetryContext; | ||
|
||
public AdfsCredentialsProviderFactory(PluginService pluginService, CloseableHttpClient httpClient) { | ||
this.pluginService = pluginService; | ||
this.telemetryFactory = this.pluginService.getTelemetryFactory(); | ||
this.httpClient = httpClient; | ||
} | ||
|
||
@Override | ||
String getSamlAssertion(final @NonNull Properties props) { | ||
this.telemetryContext = telemetryFactory.openTelemetryContext(TELEMETRY_FETCH_SAML, TelemetryTraceLevel.NESTED); | ||
|
||
String uri = "https://" + FederatedAuthPlugin.IDP_ENDPOINT.getString(props) + ':' | ||
+ FederatedAuthPlugin.IDP_PORT.getString(props) + "/adfs/ls/IdpInitiatedSignOn.aspx?loginToRp=" | ||
+ FederatedAuthPlugin.RELAYING_PARTY_ID.getString(props); | ||
|
||
try { | ||
LOGGER.finest(Messages.get("AdfsCredentialsProviderFactory.signOnPageUrl", new Object[] {uri})); | ||
validateURL(uri); | ||
HttpGet get = new HttpGet(uri); | ||
CloseableHttpResponse resp = httpClient.execute(get); | ||
|
||
if (resp.getStatusLine().getStatusCode() != 200) { | ||
throw new IOException(Messages.get("AdfsCredentialsProviderFactory.signOnPageRequestFailed", | ||
new Object[] { | ||
resp.getStatusLine().getStatusCode(), | ||
resp.getStatusLine().getReasonPhrase(), | ||
EntityUtils.toString(resp.getEntity())})); | ||
} | ||
|
||
String body = EntityUtils.toString(resp.getEntity()); | ||
|
||
String action = getFormAction(body); | ||
if (!StringUtils.isNullOrEmpty(action) && action.startsWith("/")) { | ||
uri = "https://" + FederatedAuthPlugin.IDP_ENDPOINT.getString(props) + ':' + FederatedAuthPlugin.IDP_PORT.getString(props) + action; | ||
} | ||
|
||
LOGGER.finest(Messages.get("AdfsCredentialsProviderFactory.signOnPagePostActionUrl", new Object[] {uri})); | ||
|
||
validateURL(uri); | ||
HttpPost post = new HttpPost(uri); | ||
post.setEntity(new UrlEncodedFormEntity(getParameters(body, props))); | ||
resp = httpClient.execute(post); | ||
if (resp.getStatusLine().getStatusCode() != 200) { | ||
throw new IOException(Messages.get("AdfsCredentialsProviderFactory.signOnPagePostActionRequestFailed", | ||
new Object[] { | ||
resp.getStatusLine().getStatusCode(), | ||
resp.getStatusLine().getReasonPhrase(), | ||
EntityUtils.toString(resp.getEntity())})); | ||
} | ||
|
||
String content = EntityUtils.toString(resp.getEntity()); | ||
Matcher matcher = FederatedAuthPlugin.SAML_RESPONSE_PATTERN.matcher(content); | ||
if (!matcher.find()) { | ||
throw new IOException(Messages.get("AdfsCredentialsProviderFactory.failedLogin", new Object[] {content})); | ||
} | ||
|
||
return matcher.group(1); | ||
} catch (IOException e) { | ||
LOGGER.severe(Messages.get("AdfsCredentialsProviderFactory.getSamlAssertionFailed", new Object[] {e})); | ||
this.telemetryContext.setSuccess(false); | ||
this.telemetryContext.setException(e); | ||
throw new RuntimeException(e); | ||
} finally { | ||
this.telemetryContext.closeContext(); | ||
} | ||
} | ||
|
||
private List<String> getInputTagsFromHTML(String body) { | ||
Set<String> distinctInputTags = new HashSet<>(); | ||
List<String> inputTags = new ArrayList<String>(); | ||
Pattern inputTagPattern = Pattern.compile("<input(.+?)/>", Pattern.DOTALL); | ||
Matcher inputTagMatcher = inputTagPattern.matcher(body); | ||
while (inputTagMatcher.find()) { | ||
String tag = inputTagMatcher.group(0); | ||
String tagNameLower = getValueByKey(tag, "name").toLowerCase(); | ||
if (!tagNameLower.isEmpty() && distinctInputTags.add(tagNameLower)) { | ||
inputTags.add(tag); | ||
} | ||
} | ||
return inputTags; | ||
} | ||
|
||
private String getValueByKey(String input, String key) { | ||
Pattern keyValuePattern = Pattern.compile("(" + Pattern.quote(key) + ")\\s*=\\s*\"(.*?)\""); | ||
Matcher keyValueMatcher = keyValuePattern.matcher(input); | ||
if (keyValueMatcher.find()) { | ||
return escapeHtmlEntity(keyValueMatcher.group(2)); | ||
} | ||
return ""; | ||
} | ||
|
||
private String escapeHtmlEntity(String html) { | ||
StringBuilder sb = new StringBuilder(html.length()); | ||
int i = 0; | ||
int length = html.length(); | ||
while (i < length) { | ||
char c = html.charAt(i); | ||
if (c != '&') { | ||
sb.append(c); | ||
i++; | ||
continue; | ||
} | ||
|
||
if (html.startsWith("&", i)) { | ||
sb.append('&'); | ||
i += 5; | ||
} else if (html.startsWith("'", i)) { | ||
sb.append('\''); | ||
i += 6; | ||
} else if (html.startsWith(""", i)) { | ||
sb.append('"'); | ||
i += 6; | ||
} else if (html.startsWith("<", i)) { | ||
sb.append('<'); | ||
i += 4; | ||
} else if (html.startsWith(">", i)) { | ||
sb.append('>'); | ||
i += 4; | ||
} else { | ||
sb.append(c); | ||
++i; | ||
} | ||
} | ||
return sb.toString(); | ||
} | ||
|
||
private List<NameValuePair> getParameters(String body, final @NonNull Properties props) { | ||
List<NameValuePair> parameters = new ArrayList<NameValuePair>(); | ||
for (String inputTag : getInputTagsFromHTML(body)) { | ||
String name = getValueByKey(inputTag, "name"); | ||
String value = getValueByKey(inputTag, "value"); | ||
String nameLower = name.toLowerCase(); | ||
|
||
if (nameLower.contains("username")) { | ||
parameters.add(new BasicNameValuePair(name, FederatedAuthPlugin.IDP_USERNAME.getString(props))); | ||
} else if (nameLower.contains("authmethod")) { | ||
if (!value.isEmpty()) { | ||
parameters.add(new BasicNameValuePair(name, value)); | ||
} | ||
} else if (nameLower.contains("password")) { | ||
parameters | ||
.add(new BasicNameValuePair(name, FederatedAuthPlugin.IDP_PASSWORD.getString(props))); | ||
} else if (!name.isEmpty()) { | ||
parameters.add(new BasicNameValuePair(name, value)); | ||
} | ||
} | ||
return parameters; | ||
} | ||
|
||
private String getFormAction(String body) { | ||
Pattern pattern = Pattern.compile("<form.*?action=\"([^\"]+)\""); | ||
Matcher m = pattern.matcher(body); | ||
if (m.find()) { | ||
return escapeHtmlEntity(m.group(1)); | ||
} | ||
return null; | ||
} | ||
|
||
private void validateURL(String paramString) throws IOException { | ||
|
||
URI authorizeRequestUrl = URI.create(paramString); | ||
String errorMessage = Messages.get("AdfsCredentialsProviderFactory.invalidHttpsUrl", new Object[] {paramString}); | ||
|
||
try { | ||
if (!authorizeRequestUrl.toURL().getProtocol().equalsIgnoreCase("https")) { | ||
throw new IOException(errorMessage); | ||
} | ||
|
||
Matcher matcher = FederatedAuthPlugin.HTTPS_URL_PATTERN.matcher(paramString); | ||
if (!matcher.find()) { | ||
throw new IOException(errorMessage); | ||
} | ||
} catch (MalformedURLException e) { | ||
throw new IOException(errorMessage, e); | ||
} | ||
} | ||
|
||
public void close() { | ||
try { | ||
this.httpClient.close(); | ||
} catch (IOException e) { | ||
// Ignore | ||
} | ||
} | ||
} |
27 changes: 27 additions & 0 deletions
27
...r/src/main/java/software/amazon/jdbc/plugin/federatedauth/CredentialsProviderFactory.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
/* | ||
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"). | ||
* You may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
|
||
package software.amazon.jdbc.plugin.federatedauth; | ||
|
||
import java.io.Closeable; | ||
import java.util.Properties; | ||
import org.checkerframework.checker.nullness.qual.NonNull; | ||
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider; | ||
import software.amazon.awssdk.regions.Region; | ||
|
||
public interface CredentialsProviderFactory extends Closeable { | ||
AwsCredentialsProvider getAwsCredentialsProvider(String host, Region region, final @NonNull Properties props); | ||
} |
Oops, something went wrong.