@Test public void connectionsAreNotReusedIfSslSocketFactoryChanges() throws Exception { enableHttps(); server.enqueue(new MockResponse()); server.enqueue(new MockResponse()); Request request = new Request.Builder() .url(server.url("/")) .build(); Response response = client.newCall(request).execute(); response.body().close(); // This client shares a connection pool but has a different SSL socket factory. SslClient sslClient2 = new SslClient.Builder().build(); OkHttpClient anotherClient = client.newBuilder() .sslSocketFactory(sslClient2.socketFactory, sslClient2.trustManager) .build(); // This client fails to connect because the new SSL socket factory refuses. try { anotherClient.newCall(request).execute(); fail(); } catch (SSLException expected) { } }
/** * Construct a {@code CertStatusReqItemV2} object from encoded bytes * * @param requestBytes the encoded bytes for the {@code CertStatusReqItemV2} * * @throws IOException if any decoding errors take place * @throws IllegalArgumentException if the parsed reqType value is not a * supported status request type. */ CertStatusReqItemV2(byte[] reqItemBytes) throws IOException { ByteBuffer reqBuf = ByteBuffer.wrap(reqItemBytes); statReqType = StatusRequestType.get(reqBuf.get()); int requestLength = Short.toUnsignedInt(reqBuf.getShort()); if (requestLength == reqBuf.remaining()) { byte[] statReqBytes = new byte[requestLength]; reqBuf.get(statReqBytes); if (statReqType == StatusRequestType.OCSP || statReqType == StatusRequestType.OCSP_MULTI) { request = new OCSPStatusRequest(statReqBytes); } else { request = new UnknownStatusRequest(statReqBytes); } } else { throw new SSLException("Incorrect request_length: " + "Expected " + reqBuf.remaining() + ", got " + requestLength); } }
private SslContext buildSslCtx() { SslProvider provider = OpenSsl.isAlpnSupported() ? SslProvider.OPENSSL : SslProvider.JDK; try { return SslContextBuilder.forClient() .sslProvider(provider) .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE) .trustManager(InsecureTrustManagerFactory.INSTANCE) // TODO(JR): Make a seperate Handler Class for http2 as opposed to autoneg // .applicationProtocolConfig(new ApplicationProtocolConfig( // ApplicationProtocolConfig.Protocol.ALPN, // // NO_ADVERTISE is currently the only mode supported by both OpenSsl and JDK providers. // ApplicationProtocolConfig.SelectorFailureBehavior.NO_ADVERTISE, // // ACCEPT is currently the only mode supported by both OpenSsl and JDK providers. // ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT, // ApplicationProtocolNames.HTTP_2, // ApplicationProtocolNames.HTTP_1_1)) .build(); } catch (SSLException e) { e.printStackTrace(); } return null; }
/** * PROT command. * <ul> * <li>C - Clear</li> * <li>S - Safe(SSL protocol only)</li> * <li>E - Confidential(SSL protocol only)</li> * <li>P - Private</li> * </ul> * <b>N.B.</b> the method calls * {@link #setSocketFactory(javax.net.SocketFactory)} and * {@link #setServerSocketFactory(javax.net.ServerSocketFactory)} * * @param prot Data Channel Protection Level, if {@code null}, use {@link #DEFAULT_PROT}. * @throws javax.net.ssl.SSLException If the server reply code does not equal {@code 200}. * @throws java.io.IOException If an I/O error occurs while sending * the command. */ public void execPROT(String prot) throws SSLException, IOException { if (prot == null) { prot = DEFAULT_PROT; } if (!checkPROTValue(prot)) { throw new IllegalArgumentException(); } if (FTPReply.COMMAND_OK != sendCommand(CMD_PROT, prot)) { throw new SSLException(getReplyString()); } if (DEFAULT_PROT.equals(prot)) { setSocketFactory(null); setServerSocketFactory(null); } else { setSocketFactory(new FTPSSocketFactory(context)); setServerSocketFactory(new FTPSServerSocketFactory(context)); initSslContext(); } }
/** * Send an FTP command. * A successful CCC (Clear Command Channel) command causes the underlying {@link javax.net.ssl.SSLSocket} * instance to be assigned to a plain {@link java.net.Socket} * @param command The FTP command. * @return server reply. * @throws java.io.IOException If an I/O error occurs while sending the command. * @throws javax.net.ssl.SSLException if a CCC command fails * @see FTP#sendCommand(String) */ // Would like to remove this method, but that will break any existing clients that are using CCC @Override public int sendCommand(String command, String args) throws IOException { int repCode = super.sendCommand(command, args); /* If CCC is issued, restore socket i/o streams to unsecured versions */ if (CMD_CCC.equals(command)) { if (FTPReply.COMMAND_OK == repCode) { _socket_.close(); _socket_ = plainSocket; _controlInput_ = new BufferedReader( new InputStreamReader( _socket_ .getInputStream(), getControlEncoding())); _controlOutput_ = new BufferedWriter( new OutputStreamWriter( _socket_.getOutputStream(), getControlEncoding())); } else { throw new SSLException(getReplyString()); } } return repCode; }
/** * (Re)starts SSL session for the specified <tt>session</tt> if not started yet. * Please note that SSL session is automatically started by default, and therefore * you don't need to call this method unless you've used TLS closure. * * @return <tt>true</tt> if the SSL session has been started, <tt>false</tt> if already started. * @throws SSLException if failed to start the SSL session */ public boolean startSsl(IoSession session) throws SSLException { SslHandler handler = getSslSessionHandler(session); boolean started; synchronized (handler) { if (handler.isOutboundDone()) { NextFilter nextFilter = (NextFilter) session.getAttribute(NEXT_FILTER); handler.destroy(); handler.init(); handler.handshake(nextFilter); started = true; } else { started = false; } } handler.flushScheduledEvents(); return started; }
/** * Executed just before the filter is added into the chain, we do : * <ul> * <li>check that we don't have a SSL filter already present * <li>we update the next filter * <li>we create the SSL handler helper class * <li>and we store it into the session's Attributes * </ul> */ @Override public void onPreAdd(IoFilterChain parent, String name, NextFilter nextFilter) throws SSLException { // Check that we don't have a SSL filter already present in the chain if (parent.contains(SslFilter.class)) { String msg = "Only one SSL filter is permitted in a chain."; LOGGER.error(msg); throw new IllegalStateException(msg); } LOGGER.debug("Adding the SSL Filter {} to the chain", name); IoSession session = parent.getSession(); session.setAttribute(NEXT_FILTER, nextFilter); // Create a SSL handler and start handshake. SslHandler handler = new SslHandler(this, session); handler.init(); session.setAttribute(SSL_HANDLER, handler); }
@Override public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { if (executionCount >= 3) {// 如果已经重试了3次,就放弃 return false; } if (exception instanceof NoHttpResponseException) {// 如果服务器丢掉了连接,那么就重试 return true; } if (exception instanceof SSLHandshakeException) {// 不要重试SSL握手异常 return false; } if (exception instanceof InterruptedIOException) {// 超时 return true; } if (exception instanceof UnknownHostException) {// 目标服务器不可达 return false; } if (exception instanceof ConnectTimeoutException) {// 连接被拒绝 return false; } if (exception instanceof SSLException) {// ssl握手异常 return false; } HttpClientContext clientContext = HttpClientContext.adapt(context); HttpRequest request = clientContext.getRequest(); // 如果请求是幂等的,就再次尝试 if (!(request instanceof HttpEntityEnclosingRequest)) { return true; } return false; }
private void handleSslException(SSLException e) throws CertificateValidationException, SSLException { if (e.getCause() instanceof CertificateException) { throw new CertificateValidationException(e.getMessage(), e); } else { throw e; } }
/** * performs the unwrap operation by unwrapping from {@link #inCrypt} to * {@link #inData} * */ private synchronized ByteBuffer unwrap() throws SSLException { int rem; do { rem = inData.remaining(); readEngineResult = sslEngine.unwrap(inCrypt, inData); } while (readEngineResult.getStatus() == SSLEngineResult.Status.OK && (rem != inData.remaining() || sslEngine.getHandshakeStatus() == HandshakeStatus.NEED_UNWRAP)); inData.flip(); return inData; }
@Test(expected = MessagingException.class) public void whenTrustedSocketFactoryThrowsCertificateException_throwMessagingException() throws Exception { when(mockTrustedSocketFactory.createSocket(null, "server", 12345, null)).thenThrow( new SSLException("")); setSettingsForMockSocket(); settings.setAuthType(AuthType.PLAIN); new Pop3Connection(settings, mockTrustedSocketFactory); }
@Override public boolean verify(String host, SSLSession session) { try { Certificate[] certificates = session.getPeerCertificates(); return verify(host, (X509Certificate) certificates[0]); } catch (SSLException e) { return false; } }
public boolean shouldRetry(Exception e, int currentRetryCount) { if (currentRetryCount >= maxRetryCount) { return false; } if (e instanceof ClientException) { if (((ClientException) e).isCanceledException()) { return false; } Exception localException = (Exception) e.getCause(); if (localException instanceof InterruptedIOException && !(localException instanceof SocketTimeoutException)) { WCSLogUtil.e("[shouldRetry] - is interrupted!"); return false; } else if (localException instanceof IllegalArgumentException) { return false; } else if (localException instanceof SSLException) { return false; } WCSLogUtil.d("shouldRetry - " + e.toString()); e.getCause().printStackTrace(); return true; } else if (e instanceof ServiceException) { ServiceException serviceException = (ServiceException) e; if (serviceException.getStatusCode() == 408 || (serviceException.getStatusCode() >= 500 && serviceException.getStatusCode() != 579)) { return true; } else { return false; } } else { return false; } }
private SslContext buildServerSslContext() { try { InputStream certs = SslUtil.loadInputStreamCert("server.pem"); InputStream keys = SslUtil.loadInputStreamCert("server_pkcs8.key"); return GrpcSslContexts.configure(SslContextBuilder.forServer(certs, keys)).build(); } catch (SSLException e) { throw new RpcFrameworkException(e); } }
/** * Read a CipherSuiteList from a HandshakeInStream in V3 ClientHello * format. Does not check if the listed ciphersuites are known or * supported. */ CipherSuiteList(HandshakeInStream in) throws IOException { byte[] bytes = in.getBytes16(); if ((bytes.length & 1) != 0) { throw new SSLException("Invalid ClientHello message"); } cipherSuites = new ArrayList<CipherSuite>(bytes.length >> 1); for (int i = 0; i < bytes.length; i += 2) { cipherSuites.add(CipherSuite.valueOf(bytes[i], bytes[i+1])); } }
/** * Extract the names from the certificate and tests host matches one of them * @param host * @param cert * @throws SSLException */ private static void verifyHostName(final String host, X509Certificate cert) throws SSLException { // I'm okay with being case-insensitive when comparing the host we used // to establish the socket to the hostname in the certificate. // Don't trim the CN, though. String cn = getCN(cert); String[] subjectAlts = getDNSSubjectAlts(cert); verifyHostName(host, cn.toLowerCase(Locale.US), subjectAlts); }
/** * The javax.net.ssl.HostnameVerifier contract. * * @param host 'hostname' we used to create our socket * @param session SSLSession with the remote server * @return true if the host matched the one in the certificate. */ @Override public boolean verify(String host, SSLSession session) { try { Certificate[] certs = session.getPeerCertificates(); X509Certificate x509 = (X509Certificate) certs[0]; check(new String[]{host}, x509); return true; } catch (SSLException e) { return false; } }
/** * Tests opening an SSL/TLS connection to redis with an empty certificate * trust store. This test should fail because there is no trust anchor for the * redis server certificate. * * @throws Exception */ @Test public void connectWithShardInfoAndEmptyTrustStore() throws Exception { final URI uri = URI.create("rediss://localhost:6390"); final SSLSocketFactory sslSocketFactory = createTrustNoOneSslSocketFactory(); JedisShardInfo shardInfo = new JedisShardInfo(uri, sslSocketFactory, null, null); shardInfo.setPassword("foobared"); Jedis jedis = new Jedis(shardInfo); try { jedis.get("foo"); Assert.fail("The code did not throw the expected JedisConnectionException."); } catch (JedisConnectionException e) { Assert.assertEquals("Unexpected first inner exception.", SSLException.class, e.getCause().getClass()); Assert.assertEquals("Unexpected second inner exception.", RuntimeException.class, e.getCause().getCause().getClass()); Assert.assertEquals("Unexpected third inner exception.", InvalidAlgorithmParameterException.class, e.getCause().getCause().getCause().getClass()); } try { jedis.close(); } catch (Throwable e1) { // Expected. } }
/** * Construct the {@code CertStatusReqListV2Extension} object from data * read from a {@code HandshakeInputStream} * * @param s the {@code HandshakeInputStream} providing the encoded data * @param len the length of the extension data * * @throws IOException if any decoding errors happen during object * construction. */ CertStatusReqListV2Extension(HandshakeInStream s, int len) throws IOException { super(ExtensionType.EXT_STATUS_REQUEST_V2); if (len <= 0) { // Handle the empty extension data case (from a ServerHello) itemList = Collections.emptyList(); itemListLength = 0; } else { List<CertStatusReqItemV2> workingList = new ArrayList<>(); itemListLength = s.getInt16(); if (itemListLength <= 0) { throw new SSLException("certificate_status_req_list length " + "must be greater than zero (received length: " + itemListLength + ")"); } int totalRead = 0; CertStatusReqItemV2 reqItem; do { reqItem = new CertStatusReqItemV2(s); totalRead += reqItem.length(); } while (workingList.add(reqItem) && totalRead < itemListLength); // If for some reason the add returns false, we may not have read // all the necessary bytes from the stream. Check this and throw // an exception if we terminated the loop early. if (totalRead != itemListLength) { throw new SSLException("Not all certificate_status_req_list " + "bytes were read: expected " + itemListLength + ", read " + totalRead); } itemList = Collections.unmodifiableList(workingList); } }
public static SslContext ctxForServer(NitmProxyConfig config, String serverHost) throws SSLException { Certificate certificate = CertUtil.newCert(config.getCertFile(), config.getKeyFile(), serverHost); return SslContextBuilder .forServer(certificate.getKeyPair().getPrivate(), certificate.getChain()) .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE) .applicationProtocolConfig(applicationProtocolConfig(config, config.isClientHttp2())) .build(); }
/** * 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(); } } }
/** * AUTH command. * @throws javax.net.ssl.SSLException If it server reply code not equal "234" and "334". * @throws java.io.IOException If an I/O error occurs while either sending * the command. */ protected void execAUTH() throws SSLException, IOException { int replyCode = sendCommand(CMD_AUTH, auth); if (FTPReply.SECURITY_MECHANISM_IS_OK == replyCode) { // replyCode = 334 // I carry out an ADAT command. } else if (FTPReply.SECURITY_DATA_EXCHANGE_COMPLETE != replyCode) { throw new SSLException(getReplyString()); } }
/** * PBSZ command. pbsz value: 0 to (2^32)-1 decimal integer. * Issues the command and parses the response to return the negotiated value. * * @param pbsz Protection Buffer Size. * @throws javax.net.ssl.SSLException If the server reply code does not equal "200". * @throws java.io.IOException If an I/O error occurs while sending * the command. * @return the negotiated value. * @see #execPBSZ(long) * @since 3.0 */ public long parsePBSZ(long pbsz) throws SSLException, IOException { execPBSZ(pbsz); long minvalue = pbsz; String remainder = extractPrefixedData("PBSZ=", getReplyString()); if (remainder != null) { long replysz = Long.parseLong(remainder); if (replysz < minvalue) { minvalue = replysz; } } return minvalue; }
private static CloseableHttpClient createHttpClient(int maxTotal, int maxPerRoute, int maxRoute, String hostname, int port) { ConnectionSocketFactory plainsf = PlainConnectionSocketFactory .getSocketFactory(); LayeredConnectionSocketFactory sslsf = SSLConnectionSocketFactory .getSocketFactory(); Registry<ConnectionSocketFactory> registry = RegistryBuilder .<ConnectionSocketFactory>create() .register("http", plainsf) .register("https", sslsf) .build(); PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager( registry); // 将最大连接数增加 cm.setMaxTotal(maxTotal); // 将每个路由基础的连接增加 cm.setDefaultMaxPerRoute(maxPerRoute); // 将目标主机的最大连接数增加 HttpHost httpHost = new HttpHost(hostname, port); cm.setMaxPerRoute(new HttpRoute(httpHost), maxRoute); // 请求重试处理 HttpRequestRetryHandler httpRequestRetryHandler = (exception, executionCount, context) -> { if (executionCount >= 5) {// 如果已经重试了5次,就放弃 return false; } if (exception instanceof NoHttpResponseException) {// 如果服务器丢掉了连接,那么就重试 return true; } if (exception instanceof SSLHandshakeException) {// 不要重试SSL握手异常 return false; } if (exception instanceof InterruptedIOException) {// 超时 return false; } if (exception instanceof UnknownHostException) {// 目标服务器不可达 return false; } if (exception instanceof ConnectTimeoutException) {// 连接被拒绝 return false; } if (exception instanceof SSLException) {// SSL握手异常 return false; } HttpClientContext clientContext = HttpClientContext.adapt(context); HttpRequest request = clientContext.getRequest(); // 如果请求是幂等的,就再次尝试 if (!(request instanceof HttpEntityEnclosingRequest)) { return true; } return false; }; CloseableHttpClient httpClient = HttpClients.custom() .setConnectionManager(cm) .setRetryHandler(httpRequestRetryHandler) .build(); return httpClient; }
/** * Initializes the server socket. */ private void initServer(SSLContextImpl context) throws SSLException { if (context == null) { throw new SSLException("No Authentication context given"); } sslContext = context; enabledCipherSuites = sslContext.getDefaultCipherSuiteList(true); enabledProtocols = sslContext.getDefaultProtocolList(true); }
private static LoadingCache<UserAuth, String> initCache() { try { currentAuth = ApprcHolder.get().currentAuth(); URI uri = new URI(currentAuth.getApiserver()); logger.info(String.format("Connecting to apiserver: %s host: %s port: %s", currentAuth.getApiserver(), uri.getHost(), uri.getPort())); NettyChannelBuilder builder = NettyChannelBuilder .forAddress(uri.getHost(), uri.getPort()) .nameResolverFactory(new DnsNameResolverProvider()); if (useTLS(currentAuth)) { File trustCertCollectionFile = null; builder .sslContext(GrpcSslContexts.forClient().trustManager(trustCertCollectionFile).build()) .negotiationType(NegotiationType.TLS); } else { builder.negotiationType(NegotiationType.PLAINTEXT); } channel = builder.build(); return CacheBuilder.newBuilder() .expireAfterAccess(DESCRIPTOR.getAuthCacheTtl(), TimeUnit.SECONDS) .build( new CacheLoader<UserAuth, String>() { @Override public String load(UserAuth key) throws Exception { if (isToken(key.getSecret())) { return checkToken(key.getUsername(), key.getSecret().substring(BEARER_PREFIX.length())); } return checkPassword(key.getUsername(), key.getSecret()); } } ); } catch (URISyntaxException | SSLException e) { logger.log(Level.SEVERE, e.getMessage()); } return null; }
void flushPreHandshakeEvents() throws SSLException { IoFilterEvent scheduledWrite; while ((scheduledWrite = preHandshakeEventQueue.poll()) != null) { sslFilter .filterWrite(scheduledWrite.getNextFilter(), session, (WriteRequest) scheduledWrite.getParameter()); } }
/** * 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(); } } }
private void renegotiateIfNeeded(NextFilter nextFilter, SSLEngineResult res) throws SSLException { if ((res.getStatus() != SSLEngineResult.Status.CLOSED) && (res.getStatus() != SSLEngineResult.Status.BUFFER_UNDERFLOW) && (res.getHandshakeStatus() != SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING)) { // Renegotiation required. handshakeComplete = false; handshakeStatus = res.getHandshakeStatus(); handshake(nextFilter); } }
@Override public int read() throws IOException { int n = r.read(); if (n == -1) { throw new SSLException("Unexpected end of handshake data"); } return n; }
/** * Stops the SSL session by sending TLS <tt>close_notify</tt> message to * initiate TLS closure. * * @param session the {@link IoSession} to initiate TLS closure * @throws SSLException if failed to initiate TLS closure * @throws IllegalArgumentException if this filter is not managing the specified session */ public WriteFuture stopSsl(IoSession session) throws SSLException { SslHandler handler = getSslSessionHandler(session); NextFilter nextFilter = (NextFilter) session.getAttribute(NEXT_FILTER); WriteFuture future; synchronized (handler) { future = initiateClosure(nextFilter, session); } handler.flushScheduledEvents(); return future; }
public boolean verify(String host, SSLSession session) { try { Certificate[] certificates = session.getPeerCertificates(); return verify(host, (X509Certificate) certificates[0]); } catch (SSLException e) { return false; } }
/** * close_notify(0), * unexpected_message(10), * bad_record_mac(20), * decryption_failed_RESERVED(21), * record_overflow(22), * decompression_failure(30), * handshake_failure(40), * no_certificate_RESERVED(41), * bad_certificate(42), * unsupported_certificate(43), * certificate_revoked(44), * certificate_expired(45), * certificate_unknown(46), * illegal_parameter(47), * unknown_ca(48), * access_denied(49), * decode_error(50), * decrypt_error(51), * export_restriction_RESERVED(60), * protocol_version(70), * insufficient_security(71), * internal_error(80), * user_canceled(90), * no_renegotiation(100), * unsupported_extension(110), */ @Override public BackgroundException map(final SSLException failure) { final StringBuilder buffer = new StringBuilder(); for(Throwable cause : ExceptionUtils.getThrowableList(failure)) { if(cause instanceof SocketException) { // Map Connection has been shutdown: javax.net.ssl.SSLException: java.net.SocketException: Broken pipe return new DefaultSocketExceptionMappingService().map((SocketException) cause); } } final String message = failure.getMessage(); for(Alert alert : Alert.values()) { if(StringUtils.contains(message, alert.name())) { this.append(buffer, alert.getDescription()); break; } } if(failure instanceof SSLHandshakeException) { if(ExceptionUtils.getRootCause(failure) instanceof CertificateException) { log.warn(String.format("Ignore certificate failure %s and drop connection", failure.getMessage())); // Server certificate not accepted return new ConnectionCanceledException(failure); } return new SSLNegotiateException(buffer.toString(), failure); } if(ExceptionUtils.getRootCause(failure) instanceof GeneralSecurityException) { this.append(buffer, ExceptionUtils.getRootCause(failure).getMessage()); return new InteroperabilityException(buffer.toString(), failure); } this.append(buffer, message); return new InteroperabilityException(buffer.toString(), failure); }
@Override public void check(String[] host, X509Certificate cert) throws SSLException { String[] cns = Certificates.getCNs(cert); String[] subjectAlts = Certificates.getDNSSubjectAlts(cert); check(host, cns, subjectAlts); }
@Test public void testAlgorithmFailure() { assertEquals("EC AlgorithmParameters not available. Please contact your web hosting service provider for assistance.", new S3ExceptionMappingService().map(new S3ServiceException( new SSLException( new RuntimeException( new NoSuchAlgorithmException("EC AlgorithmParameters not available") ) ))).getDetail()); }
/** * Read a CipherSuiteList from a HandshakeInStream in V3 ClientHello * format. Does not check if the listed ciphersuites are known or * supported. */ CipherSuiteList(HandshakeInStream in) throws IOException { byte[] bytes = in.getBytes16(); if ((bytes.length & 1) != 0) { throw new SSLException("Invalid ClientHello message"); } cipherSuites = new ArrayList<CipherSuite>(bytes.length >> 1); for (int i = 0; i < bytes.length; i += 2) { CipherSuite suite = CipherSuite.valueOf(bytes[i], bytes[i+1]); cipherSuites.add(suite); updateGroupTypes(suite); } }
@Test public void testMRWebAppSSLDisabled() throws Exception { MRApp app = new MRApp(2, 2, true, this.getClass().getName(), true) { @Override protected ClientService createClientService(AppContext context) { return new MRClientService(context); } }; Configuration conf = new Configuration(); // MR is explicitly disabling SSL, even though setting as HTTPS_ONLY conf.set(YarnConfiguration.YARN_HTTP_POLICY_KEY, Policy.HTTPS_ONLY.name()); Job job = app.submit(conf); String hostPort = NetUtils.getHostPortString(((MRClientService) app.getClientService()) .getWebApp().getListenerAddress()); // http:// should be accessible URL httpUrl = new URL("http://" + hostPort); HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection(); InputStream in = conn.getInputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copyBytes(in, out, 1024); Assert.assertTrue(out.toString().contains("MapReduce Application")); // https:// is not accessible. URL httpsUrl = new URL("https://" + hostPort); try { HttpURLConnection httpsConn = (HttpURLConnection) httpsUrl.openConnection(); httpsConn.getInputStream(); Assert.fail("https:// is not accessible, expected to fail"); } catch (Exception e) { Assert.assertTrue(e instanceof SSLException); } app.waitForState(job, JobState.SUCCEEDED); app.verifyCompleted(); }
public ImapClientFactory(ImapClientFactoryConfiguration configuration, KeyStore keyStore) { this.configuration = configuration; try { TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(keyStore); sslContext = SslContextBuilder.forClient() .trustManager(trustManagerFactory) .build(); } catch (NoSuchAlgorithmException | SSLException | KeyStoreException e) { throw new RuntimeException(e); } }