History

My first initial commit with all of mine experimental changes.

Dmitry Kabak (userdima committed 13 years ago

Commit d37b88d1 parent 3f5b46618352 files · +2598093 −-8690Browse files

Showing the changes to java/pkg/sun/net/www/protocol/https/HttpsClient.java (1 of 18352 files). Show all

Unified · Split

java/pkg/sun/net/www/protocol/https/HttpsClient.java+749−0
@@ -0,0 +1,749 @@
1+/*
2+ * Copyright (c) 2001, 2010, Oracle and/or its affiliates. All rights reserved.
3+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4+ *
5+ * This code is free software; you can redistribute it and/or modify it
6+ * under the terms of the GNU General Public License version 2 only, as
7+ * published by the Free Software Foundation. Oracle designates this
8+ * particular file as subject to the "Classpath" exception as provided
9+ * by Oracle in the LICENSE file that accompanied this code.
10+ *
11+ * This code is distributed in the hope that it will be useful, but WITHOUT
12+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14+ * version 2 for more details (a copy is included in the LICENSE file that
15+ * accompanied this code).
16+ *
17+ * You should have received a copy of the GNU General Public License version
18+ * 2 along with this work; if not, write to the Free Software Foundation,
19+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20+ *
21+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22+ * or visit www.oracle.com if you need additional information or have any
23+ * questions.
24+ */
25+
26+
27+package sun.net.www.protocol.https;
28+
29+import java.io.IOException;
30+import java.io.UnsupportedEncodingException;
31+import java.io.PrintStream;
32+import java.io.BufferedOutputStream;
33+import java.net.Socket;
34+import java.net.SocketException;
35+import java.net.URL;
36+import java.net.UnknownHostException;
37+import java.net.InetSocketAddress;
38+import java.net.Proxy;
39+import java.net.CookieHandler;
40+import java.security.Principal;
41+import java.security.cert.*;
42+import java.util.StringTokenizer;
43+import java.util.Vector;
44+import java.security.AccessController;
45+
46+import javax.security.auth.x500.X500Principal;
47+
48+import javax.net.ssl.*;
49+import sun.net.www.http.HttpClient;
50+import sun.security.action.*;
51+
52+import sun.security.util.HostnameChecker;
53+import sun.security.ssl.SSLSocketImpl;
54+
55+
56+/**
57+ * This class provides HTTPS client URL support, building on the standard
58+ * "sun.net.www" HTTP protocol handler. HTTPS is the same protocol as HTTP,
59+ * but differs in the transport layer which it uses: <UL>
60+ *
61+ * <LI>There's a <em>Secure Sockets Layer</em> between TCP
62+ * and the HTTP protocol code.
63+ *
64+ * <LI>It uses a different default TCP port.
65+ *
66+ * <LI>It doesn't use application level proxies, which can see and
67+ * manipulate HTTP user level data, compromising privacy. It uses
68+ * low level tunneling instead, which hides HTTP protocol and data
69+ * from all third parties. (Traffic analysis is still possible).
70+ *
71+ * <LI>It does basic server authentication, to protect
72+ * against "URL spoofing" attacks. This involves deciding
73+ * whether the X.509 certificate chain identifying the server
74+ * is trusted, and verifying that the name of the server is
75+ * found in the certificate. (The application may enable an
76+ * anonymous SSL cipher suite, and such checks are not done
77+ * for anonymous ciphers.)
78+ *
79+ * <LI>It exposes key SSL session attributes, specifically the
80+ * cipher suite in use and the server's X509 certificates, to
81+ * application software which knows about this protocol handler.
82+ *
83+ * </UL>
84+ *
85+ * <P> System properties used include: <UL>
86+ *
87+ * <LI><em>https.proxyHost</em> ... the host supporting SSL
88+ * tunneling using the conventional CONNECT syntax
89+ *
90+ * <LI><em>https.proxyPort</em> ... port to use on proxyHost
91+ *
92+ * <LI><em>https.cipherSuites</em> ... comma separated list of
93+ * SSL cipher suite names to enable.
94+ *
95+ * <LI><em>http.nonProxyHosts</em> ...
96+ *
97+ * </UL>
98+ *
99+ * @author David Brownell
100+ * @author Bill Foote
101+ */
102+
103+// final for export control reasons (access to APIs); remove with care
104+final class HttpsClient extends HttpClient
105+ implements HandshakeCompletedListener
106+{
107+ // STATIC STATE and ACCESSORS THERETO
108+
109+ // HTTPS uses a different default port number than HTTP.
110+ private static final int httpsPortNumber = 443;
111+
112+ // default HostnameVerifier class canonical name
113+ private static final String defaultHVCanonicalName =
114+ "javax.net.ssl.HttpsURLConnection.DefaultHostnameVerifier";
115+
116+ /** Returns the default HTTPS port (443) */
117+ @Override
118+ protected int getDefaultPort() { return httpsPortNumber; }
119+
120+ private HostnameVerifier hv;
121+ private SSLSocketFactory sslSocketFactory;
122+
123+ // HttpClient.proxyDisabled will always be false, because we don't
124+ // use an application-level HTTP proxy. We might tunnel through
125+ // our http proxy, though.
126+
127+
128+ // INSTANCE DATA
129+
130+ // last negotiated SSL session
131+ private SSLSession session;
132+
133+ private String [] getCipherSuites() {
134+ //
135+ // If ciphers are assigned, sort them into an array.
136+ //
137+ String ciphers [];
138+ String cipherString = AccessController.doPrivileged(
139+ new GetPropertyAction("https.cipherSuites"));
140+
141+ if (cipherString == null || "".equals(cipherString)) {
142+ ciphers = null;
143+ } else {
144+ StringTokenizer tokenizer;
145+ Vector<String> v = new Vector<String>();
146+
147+ tokenizer = new StringTokenizer(cipherString, ",");
148+ while (tokenizer.hasMoreTokens())
149+ v.addElement(tokenizer.nextToken());
150+ ciphers = new String [v.size()];
151+ for (int i = 0; i < ciphers.length; i++)
152+ ciphers [i] = v.elementAt(i);
153+ }
154+ return ciphers;
155+ }
156+
157+ private String [] getProtocols() {
158+ //
159+ // If protocols are assigned, sort them into an array.
160+ //
161+ String protocols [];
162+ String protocolString = AccessController.doPrivileged(
163+ new GetPropertyAction("https.protocols"));
164+
165+ if (protocolString == null || "".equals(protocolString)) {
166+ protocols = null;
167+ } else {
168+ StringTokenizer tokenizer;
169+ Vector<String> v = new Vector<String>();
170+
171+ tokenizer = new StringTokenizer(protocolString, ",");
172+ while (tokenizer.hasMoreTokens())
173+ v.addElement(tokenizer.nextToken());
174+ protocols = new String [v.size()];
175+ for (int i = 0; i < protocols.length; i++) {
176+ protocols [i] = v.elementAt(i);
177+ }
178+ }
179+ return protocols;
180+ }
181+
182+ private String getUserAgent() {
183+ String userAgent = java.security.AccessController.doPrivileged(
184+ new sun.security.action.GetPropertyAction("https.agent"));
185+ if (userAgent == null || userAgent.length() == 0) {
186+ userAgent = "JSSE";
187+ }
188+ return userAgent;
189+ }
190+
191+ // should remove once HttpClient.newHttpProxy is putback
192+ private static Proxy newHttpProxy(String proxyHost, int proxyPort) {
193+ InetSocketAddress saddr = null;
194+ final String phost = proxyHost;
195+ final int pport = proxyPort < 0 ? httpsPortNumber : proxyPort;
196+ try {
197+ saddr = java.security.AccessController.doPrivileged(new
198+ java.security.PrivilegedExceptionAction<InetSocketAddress>() {
199+ public InetSocketAddress run() {
200+ return new InetSocketAddress(phost, pport);
201+ }});
202+ } catch (java.security.PrivilegedActionException pae) {
203+ }
204+ return new Proxy(Proxy.Type.HTTP, saddr);
205+ }
206+
207+ // CONSTRUCTOR, FACTORY
208+
209+
210+ /**
211+ * Create an HTTPS client URL. Traffic will be tunneled through any
212+ * intermediate nodes rather than proxied, so that confidentiality
213+ * of data exchanged can be preserved. However, note that all the
214+ * anonymous SSL flavors are subject to "person-in-the-middle"
215+ * attacks against confidentiality. If you enable use of those
216+ * flavors, you may be giving up the protection you get through
217+ * SSL tunneling.
218+ *
219+ * Use New to get new HttpsClient. This constructor is meant to be
220+ * used only by New method. New properly checks for URL spoofing.
221+ *
222+ * @param URL https URL with which a connection must be established
223+ */
224+ private HttpsClient(SSLSocketFactory sf, URL url)
225+ throws IOException
226+ {
227+ // HttpClient-level proxying is always disabled,
228+ // because we override doConnect to do tunneling instead.
229+ this(sf, url, (String)null, -1);
230+ }
231+
232+ /**
233+ * Create an HTTPS client URL. Traffic will be tunneled through
234+ * the specified proxy server.
235+ */
236+ HttpsClient(SSLSocketFactory sf, URL url, String proxyHost, int proxyPort)
237+ throws IOException {
238+ this(sf, url, proxyHost, proxyPort, -1);
239+ }
240+
241+ /**
242+ * Create an HTTPS client URL. Traffic will be tunneled through
243+ * the specified proxy server, with a connect timeout
244+ */
245+ HttpsClient(SSLSocketFactory sf, URL url, String proxyHost, int proxyPort,
246+ int connectTimeout)
247+ throws IOException {
248+ this(sf, url,
249+ (proxyHost == null? null:
250+ HttpsClient.newHttpProxy(proxyHost, proxyPort)),
251+ connectTimeout);
252+ }
253+
254+ /**
255+ * Same as previous constructor except using a Proxy
256+ */
257+ HttpsClient(SSLSocketFactory sf, URL url, Proxy proxy,
258+ int connectTimeout)
259+ throws IOException {
260+ this.proxy = proxy;
261+ setSSLSocketFactory(sf);
262+ this.proxyDisabled = true;
263+
264+ this.host = url.getHost();
265+ this.url = url;
266+ port = url.getPort();
267+ if (port == -1) {
268+ port = getDefaultPort();
269+ }
270+ setConnectTimeout(connectTimeout);
271+ // get the cookieHandler if there is any
272+ cookieHandler = java.security.AccessController.doPrivileged(
273+ new java.security.PrivilegedAction<CookieHandler>() {
274+ public CookieHandler run() {
275+ return CookieHandler.getDefault();
276+ }
277+ });
278+ openServer();
279+ }
280+
281+
282+ // This code largely ripped off from HttpClient.New, and
283+ // it uses the same keepalive cache.
284+
285+ static HttpClient New(SSLSocketFactory sf, URL url, HostnameVerifier hv)
286+ throws IOException {
287+ return HttpsClient.New(sf, url, hv, true);
288+ }
289+
290+ /** See HttpClient for the model for this method. */
291+ static HttpClient New(SSLSocketFactory sf, URL url,
292+ HostnameVerifier hv, boolean useCache) throws IOException {
293+ return HttpsClient.New(sf, url, hv, (String)null, -1, useCache);
294+ }
295+
296+ /**
297+ * Get a HTTPS client to the URL. Traffic will be tunneled through
298+ * the specified proxy server.
299+ */
300+ static HttpClient New(SSLSocketFactory sf, URL url, HostnameVerifier hv,
301+ String proxyHost, int proxyPort) throws IOException {
302+ return HttpsClient.New(sf, url, hv, proxyHost, proxyPort, true);
303+ }
304+
305+ static HttpClient New(SSLSocketFactory sf, URL url, HostnameVerifier hv,
306+ String proxyHost, int proxyPort, boolean useCache)
307+ throws IOException {
308+ return HttpsClient.New(sf, url, hv, proxyHost, proxyPort, useCache, -1);
309+ }
310+
311+ static HttpClient New(SSLSocketFactory sf, URL url, HostnameVerifier hv,
312+ String proxyHost, int proxyPort, boolean useCache,
313+ int connectTimeout)
314+ throws IOException {
315+
316+ return HttpsClient.New(sf, url, hv,
317+ (proxyHost == null? null :
318+ HttpsClient.newHttpProxy(proxyHost, proxyPort)),
319+ useCache, connectTimeout);
320+ }
321+
322+ static HttpClient New(SSLSocketFactory sf, URL url, HostnameVerifier hv,
323+ Proxy p, boolean useCache,
324+ int connectTimeout)
325+ throws IOException {
326+ HttpsClient ret = null;
327+ if (useCache) {
328+ /* see if one's already around */
329+ ret = (HttpsClient) kac.get(url, sf);
330+ if (ret != null) {
331+ ret.cachedHttpClient = true;
332+ }
333+ }
334+ if (ret == null) {
335+ ret = new HttpsClient(sf, url, p, connectTimeout);
336+ } else {
337+ SecurityManager security = System.getSecurityManager();
338+ if (security != null) {
339+ security.checkConnect(url.getHost(), url.getPort());
340+ }
341+ ret.url = url;
342+ }
343+ ret.setHostnameVerifier(hv);
344+
345+ return ret;
346+ }
347+
348+ // METHODS
349+ void setHostnameVerifier(HostnameVerifier hv) {
350+ this.hv = hv;
351+ }
352+
353+ void setSSLSocketFactory(SSLSocketFactory sf) {
354+ sslSocketFactory = sf;
355+ }
356+
357+ SSLSocketFactory getSSLSocketFactory() {
358+ return sslSocketFactory;
359+ }
360+
361+ /**
362+ * The following method, createSocket, is defined in NetworkClient
363+ * and overridden here so that the socket facroty is used to create
364+ * new sockets.
365+ */
366+ @Override
367+ protected Socket createSocket() throws IOException {
368+ try {
369+ return sslSocketFactory.createSocket();
370+ } catch (SocketException se) {
371+ //
372+ // bug 6771432
373+ // javax.net.SocketFactory throws a SocketException with an
374+ // UnsupportedOperationException as its cause to indicate that
375+ // unconnected sockets have not been implemented.
376+ //
377+ Throwable t = se.getCause();
378+ if (t != null && t instanceof UnsupportedOperationException) {
379+ return super.createSocket();
380+ } else {
381+ throw se;
382+ }
383+ }
384+ }
385+
386+
387+ @Override
388+ public boolean needsTunneling() {
389+ return (proxy != null && proxy.type() != Proxy.Type.DIRECT
390+ && proxy.type() != Proxy.Type.SOCKS);
391+ }
392+
393+ @Override
394+ public void afterConnect() throws IOException, UnknownHostException {
395+ if (!isCachedConnection()) {
396+ SSLSocket s = null;
397+ SSLSocketFactory factory = sslSocketFactory;
398+ try {
399+ if (!(serverSocket instanceof SSLSocket)) {
400+ s = (SSLSocket)factory.createSocket(serverSocket,
401+ host, port, true);
402+ } else {
403+ s = (SSLSocket)serverSocket;
404+ if (s instanceof SSLSocketImpl) {
405+ ((SSLSocketImpl)s).setHost(host);
406+ }
407+ }
408+ } catch (IOException ex) {
409+ // If we fail to connect through the tunnel, try it
410+ // locally, as a last resort. If this doesn't work,
411+ // throw the original exception.
412+ try {
413+ s = (SSLSocket)factory.createSocket(host, port);
414+ } catch (IOException ignored) {
415+ throw ex;
416+ }
417+ }
418+
419+ //
420+ // Force handshaking, so that we get any authentication.
421+ // Register a handshake callback so our session state tracks any
422+ // later session renegotiations.
423+ //
424+ String [] protocols = getProtocols();
425+ String [] ciphers = getCipherSuites();
426+ if (protocols != null) {
427+ s.setEnabledProtocols(protocols);
428+ }
429+ if (ciphers != null) {
430+ s.setEnabledCipherSuites(ciphers);
431+ }
432+ s.addHandshakeCompletedListener(this);
433+
434+ // We have two hostname verification approaches. One is in
435+ // SSL/TLS socket layer, where the algorithm is configured with
436+ // SSLParameters.setEndpointIdentificationAlgorithm(), and the
437+ // hostname verification is done by X509ExtendedTrustManager when
438+ // the algorithm is "HTTPS". The other one is in HTTPS layer,
439+ // where the algorithm is customized by
440+ // HttpsURLConnection.setHostnameVerifier(), and the hostname
441+ // verification is done by HostnameVerifier when the default
442+ // rules for hostname verification fail.
443+ //
444+ // The relationship between two hostname verification approaches
445+ // likes the following:
446+ //
447+ // | EIA algorithm
448+ // +----------------------------------------------
449+ // | null | HTTPS | LDAP/other |
450+ // -------------------------------------------------------------
451+ // | |1 |2 |3 |
452+ // HNV | default | Set HTTPS EIA | use EIA | HTTPS |
453+ // |--------------------------------------------------------
454+ // | non - |4 |5 |6 |
455+ // | default | HTTPS/HNV | use EIA | HTTPS/HNV |
456+ // -------------------------------------------------------------
457+ //
458+ // Abbreviation:
459+ // EIA: the endpoint identification algorithm in SSL/TLS
460+ // socket layer
461+ // HNV: the hostname verification object in HTTPS layer
462+ // Notes:
463+ // case 1. default HNV and EIA is null
464+ // Set EIA as HTTPS, hostname check done in SSL/TLS
465+ // layer.
466+ // case 2. default HNV and EIA is HTTPS
467+ // Use existing EIA, hostname check done in SSL/TLS
468+ // layer.
469+ // case 3. default HNV and EIA is other than HTTPS
470+ // Use existing EIA, EIA check done in SSL/TLS
471+ // layer, then do HTTPS check in HTTPS layer.
472+ // case 4. non-default HNV and EIA is null
473+ // No EIA, no EIA check done in SSL/TLS layer, then do
474+ // HTTPS check in HTTPS layer using HNV as override.
475+ // case 5. non-default HNV and EIA is HTTPS
476+ // Use existing EIA, hostname check done in SSL/TLS
477+ // layer. No HNV override possible. We will review this
478+ // decision and may update the architecture for JDK 7.
479+ // case 6. non-default HNV and EIA is other than HTTPS
480+ // Use existing EIA, EIA check done in SSL/TLS layer,
481+ // then do HTTPS check in HTTPS layer as override.
482+ boolean needToCheckSpoofing = true;
483+ String identification =
484+ s.getSSLParameters().getEndpointIdentificationAlgorithm();
485+ if (identification != null && identification.length() != 0) {
486+ if (identification.equalsIgnoreCase("HTTPS")) {
487+ // Do not check server identity again out of SSLSocket,
488+ // the endpoint will be identified during TLS handshaking
489+ // in SSLSocket.
490+ needToCheckSpoofing = false;
491+ } // else, we don't understand the identification algorithm,
492+ // need to check URL spoofing here.
493+ } else {
494+ boolean isDefaultHostnameVerifier = false;
495+
496+ // We prefer to let the SSLSocket do the spoof checks, but if
497+ // the application has specified a HostnameVerifier (HNV),
498+ // we will always use that.
499+ if (hv != null) {
500+ String canonicalName = hv.getClass().getCanonicalName();
501+ if (canonicalName != null &&
502+ canonicalName.equalsIgnoreCase(defaultHVCanonicalName)) {
503+ isDefaultHostnameVerifier = true;
504+ }
505+ } else {
506+ // Unlikely to happen! As the behavior is the same as the
507+ // default hostname verifier, so we prefer to let the
508+ // SSLSocket do the spoof checks.
509+ isDefaultHostnameVerifier = true;
510+ }
511+
512+ if (isDefaultHostnameVerifier) {
513+ // If the HNV is the default from HttpsURLConnection, we
514+ // will do the spoof checks in SSLSocket.
515+ SSLParameters paramaters = s.getSSLParameters();
516+ paramaters.setEndpointIdentificationAlgorithm("HTTPS");
517+ s.setSSLParameters(paramaters);
518+
519+ needToCheckSpoofing = false;
520+ }
521+ }
522+
523+ s.startHandshake();
524+ session = s.getSession();
525+ // change the serverSocket and serverOutput
526+ serverSocket = s;
527+ try {
528+ serverOutput = new PrintStream(
529+ new BufferedOutputStream(serverSocket.getOutputStream()),
530+ false, encoding);
531+ } catch (UnsupportedEncodingException e) {
532+ throw new InternalError(encoding+" encoding not found");
533+ }
534+
535+ // check URL spoofing if it has not been checked under handshaking
536+ if (needToCheckSpoofing) {
537+ checkURLSpoofing(hv);
538+ }
539+ } else {
540+ // if we are reusing a cached https session,
541+ // we don't need to do handshaking etc. But we do need to
542+ // set the ssl session
543+ session = ((SSLSocket)serverSocket).getSession();
544+ }
545+ }
546+
547+ // Server identity checking is done according to RFC 2818: HTTP over TLS
548+ // Section 3.1 Server Identity
549+ private void checkURLSpoofing(HostnameVerifier hostnameVerifier)
550+ throws IOException {
551+ //
552+ // Get authenticated server name, if any
553+ //
554+ String host = url.getHost();
555+
556+ // if IPv6 strip off the "[]"
557+ if (host != null && host.startsWith("[") && host.endsWith("]")) {
558+ host = host.substring(1, host.length()-1);
559+ }
560+
561+ Certificate[] peerCerts = null;
562+ String cipher = session.getCipherSuite();
563+ try {
564+ HostnameChecker checker = HostnameChecker.getInstance(
565+ HostnameChecker.TYPE_TLS);
566+
567+ // Use ciphersuite to determine whether Kerberos is present.
568+ if (cipher.startsWith("TLS_KRB5")) {
569+ if (!HostnameChecker.match(host, getPeerPrincipal())) {
570+ throw new SSLPeerUnverifiedException("Hostname checker" +
571+ " failed for Kerberos");
572+ }
573+ } else { // X.509
574+
575+ // get the subject's certificate
576+ peerCerts = session.getPeerCertificates();
577+
578+ X509Certificate peerCert;
579+ if (peerCerts[0] instanceof
580+ java.security.cert.X509Certificate) {
581+ peerCert = (java.security.cert.X509Certificate)peerCerts[0];
582+ } else {
583+ throw new SSLPeerUnverifiedException("");
584+ }
585+ checker.match(host, peerCert);
586+ }
587+
588+ // if it doesn't throw an exception, we passed. Return.
589+ return;
590+
591+ } catch (SSLPeerUnverifiedException e) {
592+
593+ //
594+ // client explicitly changed default policy and enabled
595+ // anonymous ciphers; we can't check the standard policy
596+ //
597+ // ignore
598+ } catch (java.security.cert.CertificateException cpe) {
599+ // ignore
600+ }
601+
602+ if ((cipher != null) && (cipher.indexOf("_anon_") != -1)) {
603+ return;
604+ } else if ((hostnameVerifier != null) &&
605+ (hostnameVerifier.verify(host, session))) {
606+ return;
607+ }
608+
609+ serverSocket.close();
610+ session.invalidate();
611+
612+ throw new IOException("HTTPS hostname wrong: should be <"
613+ + url.getHost() + ">");
614+ }
615+
616+ @Override
617+ protected void putInKeepAliveCache() {
618+ kac.put(url, sslSocketFactory, this);
619+ }
620+
621+ /*
622+ * Close an idle connection to this URL (if it exists in the cache).
623+ */
624+ @Override
625+ public void closeIdleConnection() {
626+ HttpClient http = (HttpClient) kac.get(url, sslSocketFactory);
627+ if (http != null) {
628+ http.closeServer();
629+ }
630+ }
631+
632+ /**
633+ * Returns the cipher suite in use on this connection.
634+ */
635+ String getCipherSuite() {
636+ return session.getCipherSuite();
637+ }
638+
639+ /**
640+ * Returns the certificate chain the client sent to the
641+ * server, or null if the client did not authenticate.
642+ */
643+ public java.security.cert.Certificate [] getLocalCertificates() {
644+ return session.getLocalCertificates();
645+ }
646+
647+ /**
648+ * Returns the certificate chain with which the server
649+ * authenticated itself, or throw a SSLPeerUnverifiedException
650+ * if the server did not authenticate.
651+ */
652+ java.security.cert.Certificate [] getServerCertificates()
653+ throws SSLPeerUnverifiedException
654+ {
655+ return session.getPeerCertificates();
656+ }
657+
658+ /**
659+ * Returns the X.509 certificate chain with which the server
660+ * authenticated itself, or null if the server did not authenticate.
661+ */
662+ javax.security.cert.X509Certificate [] getServerCertificateChain()
663+ throws SSLPeerUnverifiedException
664+ {
665+ return session.getPeerCertificateChain();
666+ }
667+
668+ /**
669+ * Returns the principal with which the server authenticated
670+ * itself, or throw a SSLPeerUnverifiedException if the
671+ * server did not authenticate.
672+ */
673+ Principal getPeerPrincipal()
674+ throws SSLPeerUnverifiedException
675+ {
676+ Principal principal;
677+ try {
678+ principal = session.getPeerPrincipal();
679+ } catch (AbstractMethodError e) {
680+ // if the provider does not support it, fallback to peer certs.
681+ // return the X500Principal of the end-entity cert.
682+ java.security.cert.Certificate[] certs =
683+ session.getPeerCertificates();
684+ principal = (X500Principal)
685+ ((X509Certificate)certs[0]).getSubjectX500Principal();
686+ }
687+ return principal;
688+ }
689+
690+ /**
691+ * Returns the principal the client sent to the
692+ * server, or null if the client did not authenticate.
693+ */
694+ Principal getLocalPrincipal()
695+ {
696+ Principal principal;
697+ try {
698+ principal = session.getLocalPrincipal();
699+ } catch (AbstractMethodError e) {
700+ principal = null;
701+ // if the provider does not support it, fallback to local certs.
702+ // return the X500Principal of the end-entity cert.
703+ java.security.cert.Certificate[] certs =
704+ session.getLocalCertificates();
705+ if (certs != null) {
706+ principal = (X500Principal)
707+ ((X509Certificate)certs[0]).getSubjectX500Principal();
708+ }
709+ }
710+ return principal;
711+ }
712+
713+ /**
714+ * This method implements the SSL HandshakeCompleted callback,
715+ * remembering the resulting session so that it may be queried
716+ * for the current cipher suite and peer certificates. Servers
717+ * sometimes re-initiate handshaking, so the session in use on
718+ * a given connection may change. When sessions change, so may
719+ * peer identities and cipher suites.
720+ */
721+ public void handshakeCompleted(HandshakeCompletedEvent event)
722+ {
723+ session = event.getSession();
724+ }
725+
726+ /**
727+ * @return the proxy host being used for this client, or null
728+ * if we're not going through a proxy
729+ */
730+ @Override
731+ public String getProxyHostUsed() {
732+ if (!needsTunneling()) {
733+ return null;
734+ } else {
735+ return super.getProxyHostUsed();
736+ }
737+ }
738+
739+ /**
740+ * @return the proxy port being used for this client. Meaningless
741+ * if getProxyHostUsed() gives null.
742+ */
743+ @Override
744+ public int getProxyPortUsed() {
745+ return (proxy == null || proxy.type() == Proxy.Type.DIRECT ||
746+ proxy.type() == Proxy.Type.SOCKS)? -1:
747+ ((InetSocketAddress)proxy.address()).getPort();
748+ }
749+}