summaryrefslogtreecommitdiffstats
path: root/core/java/android/net/http/CertificateChainValidator.java
blob: b7f7368ae24ebad039c4a46c9f2a6bdaad9be739 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
/*
 * Copyright (C) 2008 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package android.net.http;

import android.os.SystemClock;

import java.io.IOException;

import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateExpiredException;
import java.security.cert.CertificateNotYetValidException;
import java.security.cert.X509Certificate;
import java.security.GeneralSecurityException;
import java.security.KeyStore;

import java.util.Arrays;
import java.util.Date;
import java.util.Enumeration;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLHandshakeException;
import javax.net.ssl.SSLPeerUnverifiedException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;

import org.apache.http.HttpHost;

import org.bouncycastle.asn1.x509.X509Name;

/**
 * Class responsible for all server certificate validation functionality
 * 
 * {@hide}
 */
class CertificateChainValidator {

    private static long sTotal = 0;
    private static long sTotalReused = 0;

    /**
     * The singleton instance of the certificate chain validator
     */
    private static CertificateChainValidator sInstance;

    /**
     * Default trust manager (used to perform CA certificate validation)
     */
    private X509TrustManager mDefaultTrustManager;

    /**
     * @return The singleton instance of the certificator chain validator
     */
    public static CertificateChainValidator getInstance() {
        if (sInstance == null) {
            sInstance = new CertificateChainValidator();
        }

        return sInstance;
    }

    /**
     * Creates a new certificate chain validator. This is a pivate constructor.
     * If you need a Certificate chain validator, call getInstance().
     */
    private CertificateChainValidator() {
        try {
            TrustManagerFactory trustManagerFactory
                = TrustManagerFactory.getInstance("X509");
            trustManagerFactory.init((KeyStore)null);
            TrustManager[] trustManagers =
                trustManagerFactory.getTrustManagers();
            if (trustManagers != null && trustManagers.length > 0) {
                for (TrustManager trustManager : trustManagers) {
                    if (trustManager instanceof X509TrustManager) {
                        mDefaultTrustManager = (X509TrustManager)(trustManager);
                        break;
                    }
                }
            }
        } catch (Exception exc) {
            if (HttpLog.LOGV) {
                HttpLog.v("CertificateChainValidator():" +
                          " failed to initialize the trust manager");
            }
        }
    }

    /**
     * Performs the handshake and server certificates validation
     * @param sslSocket The secure connection socket
     * @param domain The website domain
     * @return An SSL error object if there is an error and null otherwise
     */
    public SslError doHandshakeAndValidateServerCertificates(
        HttpsConnection connection, SSLSocket sslSocket, String domain)
        throws SSLHandshakeException, IOException {

        ++sTotal;

        SSLContext sslContext = HttpsConnection.getContext();
        if (sslContext == null) {
            closeSocketThrowException(sslSocket, "SSL context is null");
        }

        X509Certificate[] serverCertificates = null;

        long sessionBeforeHandshakeLastAccessedTime = 0;
        byte[] sessionBeforeHandshakeId = null;

        SSLSession sessionAfterHandshake = null;

        synchronized(sslContext) {
            // get SSL session before the handshake
            SSLSession sessionBeforeHandshake =
                getSSLSession(sslContext, connection.getHost());
            if (sessionBeforeHandshake != null) {
                sessionBeforeHandshakeLastAccessedTime =
                    sessionBeforeHandshake.getLastAccessedTime();

                sessionBeforeHandshakeId =
                    sessionBeforeHandshake.getId();
            }

            // start handshake, close the socket if we fail
            try {
                sslSocket.setUseClientMode(true);
                sslSocket.startHandshake();
            } catch (IOException e) {
                closeSocketThrowException(
                    sslSocket, e.getMessage(),
                    "failed to perform SSL handshake");
            }

            // retrieve the chain of the server peer certificates
            Certificate[] peerCertificates =
                sslSocket.getSession().getPeerCertificates();

            if (peerCertificates == null || peerCertificates.length <= 0) {
                closeSocketThrowException(
                    sslSocket, "failed to retrieve peer certificates");
            } else {
                serverCertificates =
                    new X509Certificate[peerCertificates.length];
                for (int i = 0; i < peerCertificates.length; ++i) {
                    serverCertificates[i] =
                        (X509Certificate)(peerCertificates[i]);
                }

                // update the SSL certificate associated with the connection
                if (connection != null) {
                    if (serverCertificates[0] != null) {
                        connection.setCertificate(
                            new SslCertificate(serverCertificates[0]));
                    }
                }
            }

            // get SSL session after the handshake
            sessionAfterHandshake =
                getSSLSession(sslContext, connection.getHost());
        }

        if (sessionBeforeHandshakeLastAccessedTime != 0 &&
            sessionAfterHandshake != null &&
            Arrays.equals(
                sessionBeforeHandshakeId, sessionAfterHandshake.getId()) &&
            sessionBeforeHandshakeLastAccessedTime <
            sessionAfterHandshake.getLastAccessedTime()) {

            if (HttpLog.LOGV) {
                HttpLog.v("SSL session was reused: total reused: "
                          + sTotalReused
                          + " out of total of: " + sTotal);

                ++sTotalReused;
            }

            // no errors!!!
            return null;
        }

        // check if the first certificate in the chain is for this site
        X509Certificate currCertificate = serverCertificates[0];
        if (currCertificate == null) {
            closeSocketThrowException(
                sslSocket, "certificate for this site is null");
        } else {
            if (!DomainNameChecker.match(currCertificate, domain)) {
                String errorMessage = "certificate not for this host: " + domain;

                if (HttpLog.LOGV) {
                    HttpLog.v(errorMessage);
                }

                sslSocket.getSession().invalidate();
                return new SslError(
                    SslError.SSL_IDMISMATCH, currCertificate);
            }
        }

        //
        // first, we validate the chain using the standard validation
        // solution; if we do not find any errors, we are done; if we
        // fail the standard validation, we re-validate again below,
        // this time trying to retrieve any individual errors we can
        // report back to the user.
        //
        try {
            synchronized (mDefaultTrustManager) {
                mDefaultTrustManager.checkServerTrusted(
                    serverCertificates, "RSA");

                // no errors!!!
                return null;
            }
        } catch (CertificateException e) {
            if (HttpLog.LOGV) {
                HttpLog.v(
                    "failed to pre-validate the certificate chain, error: " +
                    e.getMessage());
            }
        }

        sslSocket.getSession().invalidate();

        SslError error = null;

        // we check the root certificate separately from the rest of the
        // chain; this is because we need to know what certificate in
        // the chain resulted in an error if any
        currCertificate =
            serverCertificates[serverCertificates.length - 1];
        if (currCertificate == null) {
            closeSocketThrowException(
                sslSocket, "root certificate is null");
        }

        // check if the last certificate in the chain (root) is trusted
        X509Certificate[] rootCertificateChain = { currCertificate };
        try {
            synchronized (mDefaultTrustManager) {
                mDefaultTrustManager.checkServerTrusted(
                    rootCertificateChain, "RSA");
            }
        } catch (CertificateExpiredException e) {
            String errorMessage = e.getMessage();
            if (errorMessage == null) {
                errorMessage = "root certificate has expired";
            }

            if (HttpLog.LOGV) {
                HttpLog.v(errorMessage);
            }

            error = new SslError(
                SslError.SSL_EXPIRED, currCertificate);
        } catch (CertificateNotYetValidException e) {
            String errorMessage = e.getMessage();
            if (errorMessage == null) {
                errorMessage = "root certificate not valid yet";
            }

            if (HttpLog.LOGV) {
                HttpLog.v(errorMessage);
            }

            error = new SslError(
                SslError.SSL_NOTYETVALID, currCertificate);
        } catch (CertificateException e) {
            String errorMessage = e.getMessage();
            if (errorMessage == null) {
                errorMessage = "root certificate not trusted";
            }

            if (HttpLog.LOGV) {
                HttpLog.v(errorMessage);
            }

            return new SslError(
                SslError.SSL_UNTRUSTED, currCertificate);
        }

        // Then go through the certificate chain checking that each
        // certificate trusts the next and that each certificate is
        // within its valid date range. Walk the chain in the order
        // from the CA to the end-user
        X509Certificate prevCertificate =
            serverCertificates[serverCertificates.length - 1];

        for (int i = serverCertificates.length - 2; i >= 0; --i) {
            currCertificate = serverCertificates[i];

            // if a certificate is null, we cannot verify the chain
            if (currCertificate == null) {
                closeSocketThrowException(
                    sslSocket, "null certificate in the chain");
            }

            // verify if trusted by chain
            if (!prevCertificate.getSubjectDN().equals(
                    currCertificate.getIssuerDN())) {
                String errorMessage = "not trusted by chain";

                if (HttpLog.LOGV) {
                    HttpLog.v(errorMessage);
                }

                return new SslError(
                    SslError.SSL_UNTRUSTED, currCertificate);
            }

            try {
                currCertificate.verify(prevCertificate.getPublicKey());
            } catch (GeneralSecurityException e) {
                String errorMessage = e.getMessage();
                if (errorMessage == null) {
                    errorMessage = "not trusted by chain";
                }

                if (HttpLog.LOGV) {
                    HttpLog.v(errorMessage);
                }

                return new SslError(
                    SslError.SSL_UNTRUSTED, currCertificate);
            }

            // verify if the dates are valid
            try {
              currCertificate.checkValidity();
            } catch (CertificateExpiredException e) {
                String errorMessage = e.getMessage();
                if (errorMessage == null) {
                    errorMessage = "certificate expired";
                }

                if (HttpLog.LOGV) {
                    HttpLog.v(errorMessage);
                }

                if (error == null ||
                    error.getPrimaryError() < SslError.SSL_EXPIRED) {
                    error = new SslError(
                        SslError.SSL_EXPIRED, currCertificate);
                }
            } catch (CertificateNotYetValidException e) {
                String errorMessage = e.getMessage();
                if (errorMessage == null) {
                    errorMessage = "certificate not valid yet";
                }

                if (HttpLog.LOGV) {
                    HttpLog.v(errorMessage);
                }

                if (error == null ||
                    error.getPrimaryError() < SslError.SSL_NOTYETVALID) {
                    error = new SslError(
                        SslError.SSL_NOTYETVALID, currCertificate);
                }
            }

            prevCertificate = currCertificate;
        }

        // if we do not have an error to report back to the user, throw
        // an exception (a generic error will be reported instead)
        if (error == null) {
            closeSocketThrowException(
                sslSocket,
                "failed to pre-validate the certificate chain due to a non-standard error");
        }

        return error;
    }

    private void closeSocketThrowException(
        SSLSocket socket, String errorMessage, String defaultErrorMessage)
        throws SSLHandshakeException, IOException {
        closeSocketThrowException(
            socket, errorMessage != null ? errorMessage : defaultErrorMessage);
    }

    private void closeSocketThrowException(SSLSocket socket, String errorMessage)
        throws SSLHandshakeException, IOException {
        if (HttpLog.LOGV) {
            HttpLog.v("validation error: " + errorMessage);
        }

        if (socket != null) {
            SSLSession session = socket.getSession();
            if (session != null) {
                session.invalidate();
            }

            socket.close();
        }

        throw new SSLHandshakeException(errorMessage);
    }

    /**
     * @param sslContext The SSL context shared accross all the SSL sessions
     * @param host The host associated with the session
     * @return A suitable SSL session from the SSL context
     */
    private SSLSession getSSLSession(SSLContext sslContext, HttpHost host) {
        if (sslContext != null && host != null) {
            Enumeration en = sslContext.getClientSessionContext().getIds();
            while (en.hasMoreElements()) {
                byte[] id = (byte[]) en.nextElement();
                if (id != null) {
                    SSLSession session =
                        sslContext.getClientSessionContext().getSession(id);
                    if (session.isValid() &&
                        host.getHostName().equals(session.getPeerHost()) &&
                        host.getPort() == session.getPeerPort()) {
                        return session;
                    }
                }
            }
        }

        return null;
    }
}