Skip to content

Commit

Permalink
Updated plugins process
Browse files Browse the repository at this point in the history
  • Loading branch information
iggarish committed May 6, 2022
1 parent 80b8d4c commit 0c956c7
Show file tree
Hide file tree
Showing 10 changed files with 80 additions and 41 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,7 @@ private String windowsIntegratedAuthentication()
if (RedshiftLogger.isEnable())
m_log.logDebug("Command: {0}:{1}:{2}", cmd[0],cmd[1],cmd[2]);

validateURL(cmd[1]);
Process process = Runtime.getRuntime().exec(cmd);
is = process.getInputStream();
os = process.getOutputStream();
Expand Down Expand Up @@ -146,7 +147,7 @@ private String formBasedAuthentication() throws IOException
{
if (RedshiftLogger.isEnable())
m_log.logDebug("uri: {0}", uri);

validateURL(uri);
client = getHttpClient();
HttpGet get = new HttpGet(uri);
CloseableHttpResponse resp = client.execute(get);
Expand Down Expand Up @@ -204,6 +205,7 @@ else if (!name.isEmpty())
if (RedshiftLogger.isEnable())
m_log.logDebug("action uri: {0}", uri);

validateURL(uri);
HttpPost post = new HttpPost(uri);
post.setEntity(new UrlEncodedFormEntity(parameters));
resp = client.execute(post);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,8 @@ private String azureOauthBasedAuthentication() throws IOException, SdkClientExce
if (RedshiftLogger.isEnable())
m_log.logDebug("uri: {0}", uri);

validateURL(uri);

CloseableHttpClient client = null;
CloseableHttpResponse resp = null;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -396,14 +396,17 @@ private String extractSamlAssertion(String content)
*
* @param authorizationCode authorization authorizationCode
* @return object containing the request data
* @throws IOException
*/
private HttpPost createAuthorizationRequest(String authorizationCode)
private HttpPost createAuthorizationRequest(String authorizationCode) throws IOException
{
URIBuilder builder = new URIBuilder().setScheme(CURRENT_INTERACTION_SCHEMA)
.setHost(MICROSOFT_IDP_HOST)
.setPath("/" + m_idp_tenant + "/oauth2/token");

String tokenRequestUrl = builder.toString();
validateURL(tokenRequestUrl);

HttpPost post = new HttpPost(tokenRequestUrl);
final List<BasicNameValuePair> parameters = new ArrayList<>();
parameters.add(new BasicNameValuePair(OAUTH_IDP_CODE_PARAMETER_NAME, authorizationCode));
Expand Down Expand Up @@ -454,6 +457,9 @@ private void openBrowser(String state) throws URISyntaxException, IOException
.addParameter(OAUTH_STATE_PARAMETER_NAME, state);
URI authorizeRequestUrl;
authorizeRequestUrl = builder.build();

validateURL(authorizeRequestUrl.toString());

Desktop.getDesktop().browse(authorizeRequestUrl);

if(RedshiftLogger.isEnable())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -403,15 +403,18 @@ private String extractJwtAssertion(String content)
*
* @param authorizationCode authorization authorizationCode
* @return object containing the request data
* @throws IOException
*/
private HttpPost createAuthorizationRequest(String authorizationCode)
private HttpPost createAuthorizationRequest(String authorizationCode) throws IOException
{
URIBuilder builder = new URIBuilder().setScheme(CURRENT_INTERACTION_SCHEMA)
.setHost(MICROSOFT_IDP_HOST)
.setPath("/" + m_idp_tenant + "/oauth2/v2.0/token");

String tokenRequestUrl = builder.toString();
String scope = "openid " + m_scope;

validateURL(tokenRequestUrl);
HttpPost post = new HttpPost(tokenRequestUrl);
final List<BasicNameValuePair> parameters = new ArrayList<>();
parameters.add(new BasicNameValuePair(OAUTH_IDP_CODE_PARAMETER_NAME, authorizationCode));
Expand Down Expand Up @@ -466,6 +469,9 @@ private void openBrowser(String state) throws URISyntaxException, IOException
.addParameter(OAUTH_STATE_PARAMETER_NAME, state);
URI authorizeRequestUrl;
authorizeRequestUrl = builder.build();

validateURL(authorizeRequestUrl.toString());

Desktop.getDesktop().browse(authorizeRequestUrl);

if(RedshiftLogger.isEnable())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
import java.time.Duration;
import java.util.List;
import java.util.function.Function;
import java.util.regex.Matcher;

import static com.amazon.redshift.plugin.utils.CheckUtils.*;
import static com.amazon.redshift.plugin.utils.ResponseUtils.findParameter;
Expand Down Expand Up @@ -74,7 +75,7 @@ protected String getSamlAssertion() throws IOException
m_idp_response_timeout < 10,
KEY_IDP_RESPONSE_TIMEOUT + " should be 10 seconds or greater.");
checkInvalidAndThrows((m_listen_port < 1 || m_listen_port > 65535), KEY_LISTEN_PORT);
vaildateURL();
validateURL(m_login_url);
return authenticate();
}
catch (InternalPluginException ex)
Expand Down Expand Up @@ -197,36 +198,6 @@ public Object apply(List<NameValuePair> nameValuePairs)
throw new InternalPluginException("Fail to login during timeout.");
}

/**
* Validate the given login URL.
*
* @throws InternalPluginException in case of error
*/
private void vaildateURL() throws InternalPluginException
{
URI authorizeRequestUrl = URI.create(m_login_url);
String error = "Invalid url:" + m_login_url;

if(RedshiftLogger.isEnable())
m_log.log(LogLevel.DEBUG,
String.format("SSO URI: \n%s", authorizeRequestUrl.toString())
);

try
{
if(!authorizeRequestUrl.toURL().getProtocol().equalsIgnoreCase("https"))
{
m_log.log(LogLevel.ERROR, error);

throw new InternalPluginException(error);
}
}
catch (MalformedURLException e)
{
throw new InternalPluginException(error, e);
}
}

/**
* Opens the default browser with the authorization request to the web service.
*
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
package com.amazon.redshift.plugin;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URI;
import java.security.GeneralSecurityException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
Expand All @@ -15,12 +20,17 @@
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.client.LaxRedirectStrategy;

import com.amazon.redshift.logger.LogLevel;
import com.amazon.redshift.logger.RedshiftLogger;
import com.amazon.redshift.ssl.NonValidatingFactory;

abstract class IdpCredentialsProvider {

protected static final String KEY_SSL_INSECURE = "ssl_insecure";
protected boolean m_sslInsecure;
protected static final Pattern IAM_URL_PATTERN = Pattern.compile("^(https)://[-a-zA-Z0-9+&@#/%?=~_!:,.']*[-a-zA-Z0-9+&@#/%=~_']");
protected static final Pattern IAM_HTTP_URL_PATTERN = Pattern.compile("^(http)://[-a-zA-Z0-9+&@#/%?=~_!:,.']*[-a-zA-Z0-9+&@#/%=~_']");
protected RedshiftLogger m_log;

protected CloseableHttpClient getHttpClient() throws GeneralSecurityException
{
Expand Down Expand Up @@ -52,5 +62,38 @@ protected CloseableHttpClient getHttpClient() throws GeneralSecurityException

return builder.build();
}

protected void validateURL(String paramString) throws IOException {

URI authorizeRequestUrl = URI.create(paramString);
String error = "Invalid url:" + paramString;

if(RedshiftLogger.isEnable())
m_log.log(LogLevel.DEBUG,
String.format("URI: \n%s", authorizeRequestUrl.toString())
);
try
{
if(!authorizeRequestUrl.toURL().getProtocol().equalsIgnoreCase("https"))
{
m_log.log(LogLevel.ERROR, error);

throw new IOException(error);
}

Matcher matcher = IAM_URL_PATTERN.matcher(paramString);
if (!matcher.find())
{
m_log.log(LogLevel.ERROR, "Pattern matching failed:" + error);

throw new IOException("Pattern matching failed:" + error);
}
}
catch (MalformedURLException e)
{
throw new IOException(error + " " + e.getMessage(), e);
}
}


}
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@
public abstract class JwtCredentialsProvider extends IdpCredentialsProvider implements INativePlugin
{
private static final String KEY_PROVIDER_NAME = "providerName";
protected RedshiftLogger m_log;
protected Boolean m_disableCache = false;

// Optional parameters
Expand Down Expand Up @@ -185,8 +184,9 @@ public void refresh() throws RedshiftException
if (RedshiftLogger.isEnable())
m_log.logDebug(
String.format("JWT : %s", jwt));

Date expiration = null;

// Default expiration until server sends actual expirations
Date expiration = new Date(System.currentTimeMillis() + 15 * 60 * 1000);
NativeTokenHolder credentials = NativeTokenHolder.newInstance(jwt, expiration);
credentials.setRefresh(true);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,8 @@ private String oktaAuthentication(CloseableHttpClient httpClient) throws IOExcep
if (RedshiftLogger.isEnable())
m_log.logDebug("uri: {0}", uri);

validateURL(uri);

HttpPost httpost = new HttpPost(uri);
httpost.addHeader("Accept", "application/json");
httpost.addHeader("Content-Type", "application/json");
Expand Down Expand Up @@ -150,12 +152,15 @@ private String handleSamlAssertion(CloseableHttpClient httpClient, String oktaSe
// Ensure that the string is properly encoded.
m_app_name = URLEncoder.encode(m_app_name, "UTF-8");
}

String oktaAWSAppUrl = "https://" + m_idpHost + "/home/" + m_app_name + "/" + m_app_id;
String oktaAWSAppUrlWithToken = oktaAWSAppUrl + "?onetimetoken=" + oktaSessionToken;

if (RedshiftLogger.isEnable())
m_log.logDebug("oktaAWSAppUrl: {0}", oktaAWSAppUrl);

HttpGet httpget = new HttpGet(oktaAWSAppUrl + "?onetimetoken=" + oktaSessionToken);
validateURL(oktaAWSAppUrlWithToken);
HttpGet httpget = new HttpGet(oktaAWSAppUrlWithToken);
CloseableHttpResponse responseSAML = httpClient.execute(httpget);

int requestStatus = responseSAML.getStatusLine().getStatusCode();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@ protected String getSamlAssertion() throws IOException
if (RedshiftLogger.isEnable())
m_log.logDebug("uri: {0}", uri);

validateURL(uri);
client = getHttpClient();
HttpGet get = new HttpGet(uri);
resp = client.execute(get);
Expand Down Expand Up @@ -195,6 +196,8 @@ else if (!StringUtils.isNullOrEmpty(name))
if (RedshiftLogger.isEnable())
m_log.logDebug("action uri: {0}", uri);

validateURL(uri);

HttpPost post = new HttpPost(uri);
post.setEntity(new UrlEncodedFormEntity(parameters));
resp = client.execute(post);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,14 @@
import com.amazon.redshift.RedshiftProperty;
import com.amazon.redshift.core.IamHelper;
import com.amazon.redshift.httpclient.log.IamCustomLogFactory;
import com.amazon.redshift.logger.LogLevel;
import com.amazon.redshift.logger.RedshiftLogger;
import com.amazon.redshift.plugin.utils.RequestUtils;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
Expand Down Expand Up @@ -52,7 +55,6 @@

public abstract class SamlCredentialsProvider extends IdpCredentialsProvider implements IPlugin
{

protected static final String KEY_IDP_HOST = "idp_host";
private static final String KEY_IDP_PORT = "idp_port";
private static final String KEY_DURATION = "duration";
Expand All @@ -71,7 +73,6 @@ public abstract class SamlCredentialsProvider extends IdpCredentialsProvider imp
protected Boolean m_autoCreate;
protected String m_stsEndpoint;
protected String m_region;
protected RedshiftLogger m_log;
protected Boolean m_disableCache = false;
protected Boolean m_groupFederation = false;

Expand Down Expand Up @@ -754,5 +755,5 @@ protected boolean isPassword(String inputTag)
}

return "password".equals(typeVal);
}
}
}

0 comments on commit 0c956c7

Please sign in to comment.