Make the OAuth authorization available or not depending upon a variable in oauth.xml
[pub/Android/ownCloud.git] / src / com / owncloud / android / network / AdvancedSslSocketFactory.java
1 /* ownCloud Android client application
2 * Copyright (C) 2012 Bartek Przybylski
3 * Copyright (C) 2012-2013 ownCloud Inc.
4 *
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17 *
18 */
19
20 package com.owncloud.android.network;
21
22 import java.io.IOException;
23 import java.net.InetAddress;
24 import java.net.InetSocketAddress;
25 import java.net.Socket;
26 import java.net.SocketAddress;
27 import java.net.UnknownHostException;
28 import java.security.cert.X509Certificate;
29
30 import javax.net.SocketFactory;
31 import javax.net.ssl.SSLContext;
32 import javax.net.ssl.SSLException;
33 import javax.net.ssl.SSLHandshakeException;
34 import javax.net.ssl.SSLPeerUnverifiedException;
35 import javax.net.ssl.SSLSession;
36 import javax.net.ssl.SSLSocket;
37
38 import org.apache.commons.httpclient.ConnectTimeoutException;
39 import org.apache.commons.httpclient.params.HttpConnectionParams;
40 import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;
41 import org.apache.http.conn.ssl.X509HostnameVerifier;
42
43 import android.util.Log;
44
45 /**
46 * AdvancedSSLProtocolSocketFactory allows to create SSL {@link Socket}s with
47 * a custom SSLContext and an optional Hostname Verifier.
48 *
49 * @author David A. Velasco
50 */
51
52 public class AdvancedSslSocketFactory implements ProtocolSocketFactory {
53
54 private static final String TAG = AdvancedSslSocketFactory.class.getSimpleName();
55
56 private SSLContext mSslContext = null;
57 private AdvancedX509TrustManager mTrustManager = null;
58 private X509HostnameVerifier mHostnameVerifier = null;
59
60 public SSLContext getSslContext() {
61 return mSslContext;
62 }
63
64 /**
65 * Constructor for AdvancedSSLProtocolSocketFactory.
66 */
67 public AdvancedSslSocketFactory(SSLContext sslContext, AdvancedX509TrustManager trustManager, X509HostnameVerifier hostnameVerifier) {
68 if (sslContext == null)
69 throw new IllegalArgumentException("AdvancedSslSocketFactory can not be created with a null SSLContext");
70 if (trustManager == null)
71 throw new IllegalArgumentException("AdvancedSslSocketFactory can not be created with a null Trust Manager");
72 mSslContext = sslContext;
73 mTrustManager = trustManager;
74 mHostnameVerifier = hostnameVerifier;
75 }
76
77 /**
78 * @see ProtocolSocketFactory#createSocket(java.lang.String,int,java.net.InetAddress,int)
79 */
80 public Socket createSocket(String host, int port, InetAddress clientHost, int clientPort) throws IOException, UnknownHostException {
81 Socket socket = mSslContext.getSocketFactory().createSocket(host, port, clientHost, clientPort);
82 verifyPeerIdentity(host, port, socket);
83 return socket;
84 }
85
86
87 /**
88 * Attempts to get a new socket connection to the given host within the
89 * given time limit.
90 *
91 * @param host the host name/IP
92 * @param port the port on the host
93 * @param clientHost the local host name/IP to bind the socket to
94 * @param clientPort the port on the local machine
95 * @param params {@link HttpConnectionParams Http connection parameters}
96 *
97 * @return Socket a new socket
98 *
99 * @throws IOException if an I/O error occurs while creating the socket
100 * @throws UnknownHostException if the IP address of the host cannot be
101 * determined
102 */
103 public Socket createSocket(final String host, final int port,
104 final InetAddress localAddress, final int localPort,
105 final HttpConnectionParams params) throws IOException,
106 UnknownHostException, ConnectTimeoutException {
107 Log.d(TAG, "Creating SSL Socket with remote " + host + ":" + port + ", local " + localAddress + ":" + localPort + ", params: " + params);
108 if (params == null) {
109 throw new IllegalArgumentException("Parameters may not be null");
110 }
111 int timeout = params.getConnectionTimeout();
112 SocketFactory socketfactory = mSslContext.getSocketFactory();
113 Log.d(TAG, " ... with connection timeout " + timeout + " and socket timeout " + params.getSoTimeout());
114 Socket socket = socketfactory.createSocket();
115 SocketAddress localaddr = new InetSocketAddress(localAddress, localPort);
116 SocketAddress remoteaddr = new InetSocketAddress(host, port);
117 socket.setSoTimeout(params.getSoTimeout());
118 socket.bind(localaddr);
119 socket.connect(remoteaddr, timeout);
120 verifyPeerIdentity(host, port, socket);
121 return socket;
122 }
123
124 /**
125 * @see ProtocolSocketFactory#createSocket(java.lang.String,int)
126 */
127 public Socket createSocket(String host, int port) throws IOException,
128 UnknownHostException {
129 Log.d(TAG, "Creating SSL Socket with remote " + host + ":" + port);
130 Socket socket = mSslContext.getSocketFactory().createSocket(host, port);
131 verifyPeerIdentity(host, port, socket);
132 return socket;
133 }
134
135 public boolean equals(Object obj) {
136 return ((obj != null) && obj.getClass().equals(
137 AdvancedSslSocketFactory.class));
138 }
139
140 public int hashCode() {
141 return AdvancedSslSocketFactory.class.hashCode();
142 }
143
144
145 public X509HostnameVerifier getHostNameVerifier() {
146 return mHostnameVerifier;
147 }
148
149
150 public void setHostNameVerifier(X509HostnameVerifier hostnameVerifier) {
151 mHostnameVerifier = hostnameVerifier;
152 }
153
154 /**
155 * Verifies the identity of the server.
156 *
157 * The server certificate is verified first.
158 *
159 * Then, the host name is compared with the content of the server certificate using the current host name verifier, if any.
160 * @param socket
161 */
162 private void verifyPeerIdentity(String host, int port, Socket socket) throws IOException {
163 try {
164 CertificateCombinedException failInHandshake = null;
165 /// 1. VERIFY THE SERVER CERTIFICATE through the registered TrustManager (that should be an instance of AdvancedX509TrustManager)
166 try {
167 SSLSocket sock = (SSLSocket) socket; // a new SSLSession instance is created as a "side effect"
168 sock.startHandshake();
169
170 } catch (RuntimeException e) {
171
172 if (e instanceof CertificateCombinedException) {
173 failInHandshake = (CertificateCombinedException) e;
174 } else {
175 Throwable cause = e.getCause();
176 Throwable previousCause = null;
177 while (cause != null && cause != previousCause && !(cause instanceof CertificateCombinedException)) {
178 previousCause = cause;
179 cause = cause.getCause();
180 }
181 if (cause != null && cause instanceof CertificateCombinedException) {
182 failInHandshake = (CertificateCombinedException)cause;
183 }
184 }
185 if (failInHandshake == null) {
186 throw e;
187 }
188 failInHandshake.setHostInUrl(host);
189
190 }
191
192 /// 2. VERIFY HOSTNAME
193 SSLSession newSession = null;
194 boolean verifiedHostname = true;
195 if (mHostnameVerifier != null) {
196 if (failInHandshake != null) {
197 /// 2.1 : a new SSLSession instance was NOT created in the handshake
198 X509Certificate serverCert = failInHandshake.getServerCertificate();
199 try {
200 mHostnameVerifier.verify(host, serverCert);
201 } catch (SSLException e) {
202 verifiedHostname = false;
203 }
204
205 } else {
206 /// 2.2 : a new SSLSession instance was created in the handshake
207 newSession = ((SSLSocket)socket).getSession();
208 if (!mTrustManager.isKnownServer((X509Certificate)(newSession.getPeerCertificates()[0]))) {
209 verifiedHostname = mHostnameVerifier.verify(host, newSession);
210 }
211 }
212 }
213
214 /// 3. Combine the exceptions to throw, if any
215 if (!verifiedHostname) {
216 SSLPeerUnverifiedException pue = new SSLPeerUnverifiedException("Names in the server certificate do not match to " + host + " in the URL");
217 if (failInHandshake == null) {
218 failInHandshake = new CertificateCombinedException((X509Certificate) newSession.getPeerCertificates()[0]);
219 failInHandshake.setHostInUrl(host);
220 }
221 failInHandshake.setSslPeerUnverifiedException(pue);
222 pue.initCause(failInHandshake);
223 throw pue;
224
225 } else if (failInHandshake != null) {
226 SSLHandshakeException hse = new SSLHandshakeException("Server certificate could not be verified");
227 hse.initCause(failInHandshake);
228 throw hse;
229 }
230
231 } catch (IOException io) {
232 try {
233 socket.close();
234 } catch (Exception x) {
235 // NOTHING - irrelevant exception for the caller
236 }
237 throw io;
238 }
239 }
240
241 }