use of javax.net.ssl.SSLException in project Payara by payara.
the class RemoteRestAdminCommand method doHttpCommand.
/**
* Set up an HTTP connection, call cmd.prepareConnection so the consumer of
* the connection can further configure it, then open the connection (following
* redirects if needed), then call cmd.useConnection so the consumer of the
* connection can use it.
* <P>
* This method will try to execute the command repeatedly, for example,
* retrying with updated credentials (typically from the interactive user), etc., until the
* command succeeds or there are no more ways to retry that might succeed.
*
* @param uriString the URI to connect to
* @param httpMethod the HTTP method to use for the connection
* @param cmd the HttpCommand object
* @throws CommandException if anything goes wrong
*/
private void doHttpCommand(String uriString, String httpMethod, HttpCommand cmd, boolean isForMetadata) throws CommandException {
HttpURLConnection urlConnection;
/*
* There are various reasons we might retry the command - an authentication
* challenges from the DAS, shifting from an insecure connection to
* a secure one, etc. So just keep trying as long as it makes sense.
*
* Any exception handling code inside the loop that changes something
* about the connection or the request and wants to retry must set
* shoudTryCommandAgain to true.
*/
boolean shouldTryCommandAgain;
/*
* If the DAS challenges us for credentials and we've already sent
* the caller-provided ones, we might ask the user for a new set
* and use them. But we want to ask only once.
*/
boolean askedUserForCredentials = false;
/*
* On a subsequent retry we might need to use secure, even if the
* caller did not request it.
*/
boolean shouldUseSecure = secure;
/*
* Note: HttpConnectorAddress will set up SSL/TLS client cert
* handling if the current configuration calls for it.
*/
HttpConnectorAddress url = getHttpConnectorAddress(host, port, shouldUseSecure);
url.setInteractive(interactive);
do {
/*
* Any code that wants to trigger a retry will say so explicitly.
*/
shouldTryCommandAgain = false;
try {
final AuthenticationInfo authInfo = authenticationInfo();
if (logger.isLoggable(Level.FINER)) {
logger.log(Level.FINER, "URI: {0}", uriString);
logger.log(Level.FINER, "URL: {0}", url.toURL(uriString).toString());
logger.log(Level.FINER, "Method: {0}", httpMethod);
logger.log(Level.FINER, "Password options: {0}", passwordOptions);
logger.log(Level.FINER, "Using auth info: {0}", authInfo);
}
if (authInfo != null) {
url.setAuthenticationInfo(authInfo);
}
urlConnection = (HttpURLConnection) url.openConnection(uriString);
urlConnection.setRequestProperty("User-Agent", responseFormatType);
if (passwordOptions != null) {
urlConnection.setRequestProperty("X-passwords", passwordOptions.toString());
}
urlConnection.addRequestProperty("Cache-Control", "no-cache");
urlConnection.addRequestProperty("Pragma", "no-cache");
if (authToken != null) {
/*
* If this request is for metadata then we expect to reuse
* the auth token.
*/
urlConnection.setRequestProperty(SecureAdmin.Util.ADMIN_ONE_TIME_AUTH_TOKEN_HEADER_NAME, (isForMetadata ? AuthTokenManager.markTokenForReuse(authToken) : authToken));
}
if (commandModel != null && isCommandModelFromCache() && commandModel instanceof CachedCommandModel) {
urlConnection.setRequestProperty(COMMAND_MODEL_MATCH_HEADER, ((CachedCommandModel) commandModel).getETag());
if (logger.isLoggable(Level.FINER)) {
logger.log(Level.FINER, "CommandModel ETag: {0}", ((CachedCommandModel) commandModel).getETag());
}
}
urlConnection.setRequestMethod(httpMethod);
urlConnection.setReadTimeout(readTimeout);
if (connectTimeout >= 0) {
urlConnection.setConnectTimeout(connectTimeout);
}
addAdditionalHeaders(urlConnection);
urlConnection.addRequestProperty("X-Requested-By", "cli");
cmd.prepareConnection(urlConnection);
urlConnection.connect();
/*
* We must handle redirection from http to https explicitly
* because, even if the HttpURLConnection's followRedirect is
* set to true, the Java SE implementation does not do so if the
* procotols are different.
*/
String redirection = checkConnect(urlConnection);
if (redirection != null) {
/*
* Log at FINER; at FINE it would appear routinely when used from
* asadmin.
*/
logger.log(Level.FINER, "Following redirection to " + redirection);
url = followRedirection(url, redirection);
shouldTryCommandAgain = true;
/*
* Record that, during the retry of this request, we should
* use https.
*/
shouldUseSecure = url.isSecure();
/*
* Record that, if this is a metadata request, the real
* request should use https also.
*/
secure = true;
urlConnection.disconnect();
continue;
}
/*
* No redirection, so we have established the connection.
* Now delegate again to the command processing to use the
* now-created connection.
*/
cmd.useConnection(urlConnection);
processHeaders(urlConnection);
logger.finer("doHttpCommand succeeds");
} catch (AuthenticationException authEx) {
logger.log(Level.FINER, "DAS has challenged for credentials");
/*
* Try to update the credentials if we haven't already done so.
*/
if (askedUserForCredentials) {
/*
* We already updated the credentials once, and the updated
* ones did not work. No recourse.
*/
logger.log(Level.FINER, "Already tried with updated credentials; cannot authenticate");
throw authEx;
}
/*
* Try to update the creds.
*/
logger.log(Level.FINER, "Try to update credentials");
if (!updateAuthentication()) {
/*
* No updated credentials are avaiable, so we
* have no more options.
*/
logger.log(Level.FINER, "Could not update credentials; cannot authenticate");
throw authEx;
}
/*
* We have another set of credentials we can try.
*/
logger.log(Level.FINER, "Was able to update the credentials so will retry with the updated ones");
askedUserForCredentials = true;
shouldTryCommandAgain = true;
continue;
} catch (ConnectException ce) {
logger.log(Level.FINER, "doHttpCommand: connect exception {0}", ce);
// this really means nobody was listening on the remote server
// note: ConnectException extends IOException and tells us more!
String msg = strings.get("ConnectException", host, port + "");
throw new CommandException(msg, ce);
} catch (UnknownHostException he) {
logger.log(Level.FINER, "doHttpCommand: host exception {0}", he);
// bad host name
String msg = strings.get("UnknownHostException", host);
throw new CommandException(msg, he);
} catch (SocketException se) {
logger.log(Level.FINER, "doHttpCommand: socket exception {0}", se);
try {
boolean serverAppearsSecure = NetUtils.isSecurePort(host, port);
if (serverAppearsSecure && !shouldUseSecure) {
if (retryUsingSecureConnection(host, port)) {
// retry using secure connection
shouldUseSecure = true;
shouldTryCommandAgain = true;
continue;
}
}
throw new CommandException(se);
} catch (IOException io) {
// XXX - logger.printExceptionStackTrace(io);
throw new CommandException(io);
}
} catch (SSLException se) {
logger.log(Level.FINER, "doHttpCommand: SSL exception {0}", se);
try {
boolean serverAppearsSecure = NetUtils.isSecurePort(host, port);
if (!serverAppearsSecure && secure) {
logger.log(Level.SEVERE, AdminLoggerInfo.mServerIsNotSecure, new Object[] { host, port });
}
throw new CommandException(se);
} catch (IOException io) {
// XXX - logger.printExceptionStackTrace(io);
throw new CommandException(io);
}
} catch (SocketTimeoutException e) {
logger.log(Level.FINER, "doHttpCommand: read timeout {0}", e);
throw new CommandException(strings.get("ReadTimeout", (float) readTimeout / 1000), e);
} catch (IOException e) {
logger.log(Level.FINER, "doHttpCommand: IO exception {0}", e);
throw new CommandException(strings.get("IOError", e.getMessage()), e);
} catch (CommandException e) {
throw e;
} catch (Exception e) {
// logger.log(Level.FINER, "doHttpCommand: exception", e);
logger.log(Level.FINER, "doHttpCommand: exception {0}", e);
ByteArrayOutputStream buf = new ByteArrayOutputStream();
e.printStackTrace(new PrintStream(buf));
logger.finer(buf.toString());
throw new CommandException(e);
}
} while (shouldTryCommandAgain);
// no longer needed
outboundPayload = null;
}
use of javax.net.ssl.SSLException in project Payara by payara.
the class RemoteAdminCommand method doHttpCommand.
/**
* Set up an HTTP connection, call cmd.prepareConnection so the consumer of
* the connection can further configure it, then open the connection (following
* redirects if needed), then call cmd.useConnection so the consumer of the
* connection can use it.
* <P>
* This method will try to execute the command repeatedly, for example,
* retrying with updated credentials (typically from the interactive user), etc., until the
* command succeeds or there are no more ways to retry that might succeed.
*
* @param uriString the URI to connect to
* @param httpMethod the HTTP method to use for the connection
* @param cmd the HttpCommand object
* @throws CommandException if anything goes wrong
*/
private void doHttpCommand(String uriString, String httpMethod, HttpCommand cmd, boolean isForMetadata) throws CommandException {
HttpURLConnection urlConnection;
/*
* There are various reasons we might retry the command - an authentication
* challenges from the DAS, shifting from an insecure connection to
* a secure one, etc. So just keep trying as long as it makes sense.
*
* Any exception handling code inside the loop that changes something
* about the connection or the request and wants to retry must set
* shoudTryCommandAgain to true.
*/
boolean shouldTryCommandAgain;
/*
* If the DAS challenges us for credentials and we've already sent
* the caller-provided ones, we might ask the user for a new set
* and use them. But we want to ask only once.
*/
boolean askedUserForCredentials = false;
/*
* On a subsequent retry we might need to use secure, even if the
* caller did not request it.
*/
boolean shouldUseSecure = secure;
/*
* Send the caller-provided credentials (typically from command line
* options or the password file) on the first attempt only if we know
* the connection will
* be secure.
*/
boolean usedCallerProvidedCredentials = secure;
/*
* Note: HttpConnectorAddress will set up SSL/TLS client cert
* handling if the current configuration calls for it.
*/
HttpConnectorAddress url = getHttpConnectorAddress(host, port, shouldUseSecure);
url.setInteractive(interactive);
do {
/*
* Any code that wants to trigger a retry will say so explicitly.
*/
shouldTryCommandAgain = false;
try {
if (logger.isLoggable(Level.FINER)) {
logger.log(Level.FINER, "URI: {0}", uriString);
logger.log(Level.FINER, "URL: {0}", url.toString());
logger.log(Level.FINER, "URL: {0}", url.toURL(uriString).toString());
logger.log(Level.FINER, "Password options: {0}", passwordOptions);
logger.log(Level.FINER, "Using auth info: User: {0}, Password: {1}", new Object[] { user, (password != null && password.length > 0) ? "<non-null>" : "<null>" });
}
final AuthenticationInfo authInfo = authenticationInfo();
if (authInfo != null) {
url.setAuthenticationInfo(authInfo);
}
urlConnection = (HttpURLConnection) url.openConnection(uriString);
urlConnection.setRequestProperty("User-Agent", responseFormatType);
if (passwordOptions != null) {
urlConnection.setRequestProperty("X-passwords", passwordOptions.toString());
}
if (authToken != null) {
/*
* If this request is for metadata then we expect to reuse
* the auth token.
*/
urlConnection.setRequestProperty(SecureAdmin.Util.ADMIN_ONE_TIME_AUTH_TOKEN_HEADER_NAME, (isForMetadata ? AuthTokenManager.markTokenForReuse(authToken) : authToken));
}
if (commandModel != null && isCommandModelFromCache() && commandModel instanceof CachedCommandModel) {
urlConnection.setRequestProperty(COMMAND_MODEL_MATCH_HEADER, ((CachedCommandModel) commandModel).getETag());
if (logger.isLoggable(Level.FINER)) {
logger.log(Level.FINER, "CommandModel ETag: {0}", ((CachedCommandModel) commandModel).getETag());
}
}
urlConnection.setRequestMethod(httpMethod);
urlConnection.setReadTimeout(readTimeout);
if (connectTimeout >= 0)
urlConnection.setConnectTimeout(connectTimeout);
addAdditionalHeaders(urlConnection);
cmd.prepareConnection(urlConnection);
urlConnection.connect();
/*
* We must handle redirection from http to https explicitly
* because, even if the HttpURLConnection's followRedirect is
* set to true, the Java SE implementation does not do so if the
* procotols are different.
*/
String redirection = checkConnect(urlConnection);
if (redirection != null) {
/*
* Log at FINER; at FINE it would appear routinely when used from
* asadmin.
*/
logger.log(Level.FINER, "Following redirection to " + redirection);
url = followRedirection(url, redirection);
shouldTryCommandAgain = true;
/*
* Record that, during the retry of this request, we should
* use https.
*/
shouldUseSecure = url.isSecure();
/*
* Record that, if this is a metadata request, the real
* request should use https also.
*/
secure = true;
urlConnection.disconnect();
continue;
}
/*
* No redirection, so we have established the connection.
* Now delegate again to the command processing to use the
* now-created connection.
*/
cmd.useConnection(urlConnection);
processHeaders(urlConnection);
logger.finer("doHttpCommand succeeds");
} catch (AuthenticationException authEx) {
logger.log(Level.FINER, "DAS has challenged for credentials");
/*
* The DAS has challenged us to provide valid credentials.
*
* We might have sent the request without credentials previously
* (because the connection was not secure, typically). In that case,
* retry using the caller provided credentials (if there are any).
*/
if (!usedCallerProvidedCredentials) {
logger.log(Level.FINER, "Have not tried caller-supplied credentials yet; will do that next");
usedCallerProvidedCredentials = true;
shouldTryCommandAgain = true;
continue;
}
/*
* We already tried the caller-provided credentials. Try to
* update the credentials if we haven't already done so.
*/
logger.log(Level.FINER, "Already used caller-supplied credentials");
if (askedUserForCredentials) {
/*
* We already updated the credentials once, and the updated
* ones did not work. No recourse.
*/
logger.log(Level.FINER, "Already tried with updated credentials; cannot authenticate");
throw authEx;
}
/*
* Try to update the creds.
*/
logger.log(Level.FINER, "Have not yet tried to update credentials, so will try to update them");
if (!updateAuthentication()) {
/*
* No updated credentials are avaiable, so we
* have no more options.
*/
logger.log(Level.FINER, "Could not update credentials; cannot authenticate");
throw authEx;
}
/*
* We have another set of credentials we can try.
*/
logger.log(Level.FINER, "Was able to update the credentials so will retry with the updated ones");
askedUserForCredentials = true;
shouldTryCommandAgain = true;
continue;
} catch (ConnectException ce) {
logger.finer("doHttpCommand: connect exception " + ce);
// this really means nobody was listening on the remote server
// note: ConnectException extends IOException and tells us more!
String msg = strings.get("ConnectException", host, port + "");
throw new CommandException(msg, ce);
} catch (UnknownHostException he) {
logger.finer("doHttpCommand: host exception " + he);
// bad host name
String msg = strings.get("UnknownHostException", host);
throw new CommandException(msg, he);
} catch (SocketException se) {
logger.finer("doHttpCommand: socket exception " + se);
try {
boolean serverAppearsSecure = NetUtils.isSecurePort(host, port);
if (serverAppearsSecure && !shouldUseSecure) {
if (retryUsingSecureConnection(host, port)) {
// retry using secure connection
shouldUseSecure = true;
usedCallerProvidedCredentials = true;
shouldTryCommandAgain = true;
continue;
}
}
throw new CommandException(se);
} catch (IOException io) {
// XXX - logger.printExceptionStackTrace(io);
throw new CommandException(io);
}
} catch (SSLException se) {
logger.finer("doHttpCommand: SSL exception " + se);
try {
boolean serverAppearsSecure = NetUtils.isSecurePort(host, port);
if (!serverAppearsSecure && secure) {
logger.log(Level.SEVERE, AdminLoggerInfo.mServerIsNotSecure, new Object[] { host, port });
}
throw new CommandException(se);
} catch (IOException io) {
// XXX - logger.printExceptionStackTrace(io);
throw new CommandException(io);
}
} catch (SocketTimeoutException e) {
logger.finer("doHttpCommand: read timeout " + e);
throw new CommandException(strings.get("ReadTimeout", (float) readTimeout / 1000), e);
} catch (IOException e) {
logger.finer("doHttpCommand: IO exception " + e);
throw new CommandException(strings.get("IOError", e.getMessage()), e);
} catch (CommandException e) {
throw e;
} catch (Exception e) {
// logger.log(Level.FINER, "doHttpCommand: exception", e);
logger.finer("doHttpCommand: exception " + e);
ByteArrayOutputStream buf = new ByteArrayOutputStream();
e.printStackTrace(new PrintStream(buf));
logger.finer(buf.toString());
throw new CommandException(e);
}
} while (shouldTryCommandAgain);
// no longer needed
outboundPayload = null;
}
use of javax.net.ssl.SSLException in project Payara by payara.
the class JSSE14SocketFactory method checkConfig.
/**
* Checks that the certificate is compatible with the enabled cipher suites. If we don't check now, the JIoEndpoint
* can enter a nasty logging loop. See bug 45528.
*/
private void checkConfig() throws IOException {
// Create an unbound server socket
ServerSocket socket = sslProxy.createServerSocket();
initServerSocket(socket);
try {
// Set the timeout to 1ms as all we care about is if it throws an
// SSLException on accept.
socket.setSoTimeout(1);
socket.accept();
// Will never get here - no client can connect to an unbound port
} catch (SSLException ssle) {
// SSL configuration is invalid. Possibly cert doesn't match ciphers
IOException ioe = new IOException(sm.getString("jsse.invalid_ssl_conf", ssle.getMessage()));
ioe.initCause(ssle);
throw ioe;
} catch (Exception e) {
/*
* Possible ways of getting here
* socket.accept() throws a SecurityException
* socket.setSoTimeout() throws a SocketException
* socket.accept() throws some other exception (after a JDK change)
* In these cases the test won't work so carry on - essentially
* the behaviour before this patch
* socket.accept() throws a SocketTimeoutException
* In this case all is well so carry on
*/
} finally {
// Should be open here but just in case
if (!socket.isClosed()) {
socket.close();
}
}
}
use of javax.net.ssl.SSLException in project jetty.project by eclipse.
the class ConnectorTimeoutTest method testMaxIdleNoRequest.
@Test(timeout = 60000)
public void testMaxIdleNoRequest() throws Exception {
configureServer(new EchoHandler());
Socket client = newSocket(_serverURI.getHost(), _serverURI.getPort());
client.setSoTimeout(10000);
InputStream is = client.getInputStream();
Assert.assertFalse(client.isClosed());
OutputStream os = client.getOutputStream();
os.write("GET ".getBytes("utf-8"));
os.flush();
Thread.sleep(sleepTime);
long start = System.currentTimeMillis();
try {
IO.toString(is);
Assert.assertEquals(-1, is.read());
} catch (SSLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
Assert.assertTrue(System.currentTimeMillis() - start < maximumTestRuntime);
}
use of javax.net.ssl.SSLException in project AndroidAsync by koush.
the class AsyncSSLSocketWrapper method handshake.
public static void handshake(AsyncSocket socket, String host, int port, SSLEngine sslEngine, TrustManager[] trustManagers, HostnameVerifier verifier, boolean clientMode, final HandshakeCallback callback) {
AsyncSSLSocketWrapper wrapper = new AsyncSSLSocketWrapper(socket, host, port, sslEngine, trustManagers, verifier, clientMode);
wrapper.handshakeCallback = callback;
socket.setClosedCallback(new CompletedCallback() {
@Override
public void onCompleted(Exception ex) {
if (ex != null)
callback.onHandshakeCompleted(ex, null);
else
callback.onHandshakeCompleted(new SSLException("socket closed during handshake"), null);
}
});
try {
wrapper.engine.beginHandshake();
wrapper.handleHandshakeStatus(wrapper.engine.getHandshakeStatus());
} catch (SSLException e) {
wrapper.report(e);
}
}
Aggregations