1 /*
2  * Copyright (C) 2012 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package android.net.http;
18 
19 import android.security.net.config.UserCertificateSource;
20 
21 import com.android.org.conscrypt.TrustManagerImpl;
22 
23 import java.lang.reflect.InvocationTargetException;
24 import java.lang.reflect.Method;
25 import java.security.cert.CertificateException;
26 import java.security.cert.X509Certificate;
27 import java.util.List;
28 
29 import javax.net.ssl.X509TrustManager;
30 
31 /**
32  * X509TrustManager wrapper exposing Android-added features.
33  * <p>
34  * The checkServerTrusted method allows callers to perform additional
35  * verification of certificate chains after they have been successfully verified
36  * by the platform.
37  * </p>
38  */
39 public class X509TrustManagerExtensions {
40 
41     private final TrustManagerImpl mDelegate;
42     // Methods to use when mDelegate is not a TrustManagerImpl and duck typing is being used.
43     private final X509TrustManager mTrustManager;
44     private final Method mCheckServerTrusted;
45     private final Method mIsSameTrustConfiguration;
46 
47     /**
48      * Constructs a new X509TrustManagerExtensions wrapper.
49      *
50      * @param tm A {@link X509TrustManager} as returned by TrustManagerFactory.getInstance();
51      * @throws IllegalArgumentException If tm is an unsupported TrustManager type.
52      */
X509TrustManagerExtensions(X509TrustManager tm)53     public X509TrustManagerExtensions(X509TrustManager tm) throws IllegalArgumentException {
54         if (tm instanceof TrustManagerImpl) {
55             mDelegate = (TrustManagerImpl) tm;
56             mTrustManager = null;
57             mCheckServerTrusted = null;
58             mIsSameTrustConfiguration = null;
59             return;
60         }
61         // Use duck typing if possible.
62         mDelegate = null;
63         mTrustManager = tm;
64         // Check that the hostname aware checkServerTrusted is present.
65         try {
66             mCheckServerTrusted = tm.getClass().getMethod("checkServerTrusted",
67                     X509Certificate[].class,
68                     String.class,
69                     String.class);
70         } catch (NoSuchMethodException e) {
71             throw new IllegalArgumentException("Required method"
72                     + " checkServerTrusted(X509Certificate[], String, String, String) missing");
73         }
74         // Get the option isSameTrustConfiguration method.
75         Method isSameTrustConfiguration = null;
76         try {
77             isSameTrustConfiguration = tm.getClass().getMethod("isSameTrustConfiguration",
78                     String.class,
79                     String.class);
80         } catch (ReflectiveOperationException ignored) {
81         }
82         mIsSameTrustConfiguration = isSameTrustConfiguration;
83     }
84 
85     /**
86      * Verifies the given certificate chain.
87      *
88      * <p>See {@link X509TrustManager#checkServerTrusted(X509Certificate[], String)} for a
89      * description of the chain and authType parameters. The final parameter, host, should be the
90      * hostname of the server.</p>
91      *
92      * @throws CertificateException if the chain does not verify correctly.
93      * @return the properly ordered chain used for verification as a list of X509Certificates.
94      */
checkServerTrusted(X509Certificate[] chain, String authType, String host)95     public List<X509Certificate> checkServerTrusted(X509Certificate[] chain, String authType,
96                                                     String host) throws CertificateException {
97         if (mDelegate != null) {
98             return mDelegate.checkServerTrusted(chain, authType, host);
99         } else {
100             try {
101                 return (List<X509Certificate>) mCheckServerTrusted.invoke(mTrustManager, chain,
102                         authType, host);
103             } catch (IllegalAccessException e) {
104                 throw new CertificateException("Failed to call checkServerTrusted", e);
105             } catch (InvocationTargetException e) {
106                 if (e.getCause() instanceof CertificateException) {
107                     throw (CertificateException) e.getCause();
108                 }
109                 if (e.getCause() instanceof RuntimeException) {
110                     throw (RuntimeException) e.getCause();
111                 }
112                 throw new CertificateException("checkServerTrusted failed", e.getCause());
113             }
114         }
115     }
116 
117     /**
118      * Checks whether a CA certificate is added by an user.
119      *
120      * <p>Since {@link X509TrustManager#checkServerTrusted} may allow its parameter {@code chain} to
121      * chain up to user-added CA certificates, this method can be used to perform additional
122      * policies for user-added CA certificates.
123      *
124      * @return {@code true} to indicate that the certificate authority exists in the user added
125      * certificate store, {@code false} otherwise.
126      */
isUserAddedCertificate(X509Certificate cert)127     public boolean isUserAddedCertificate(X509Certificate cert) {
128         return UserCertificateSource.getInstance().findBySubjectAndPublicKey(cert) != null;
129     }
130 
131     /**
132      * Returns {@code true} if the TrustManager uses the same trust configuration for the provided
133      * hostnames.
134      */
isSameTrustConfiguration(String hostname1, String hostname2)135     public boolean isSameTrustConfiguration(String hostname1, String hostname2) {
136         if (mIsSameTrustConfiguration == null) {
137             return true;
138         }
139         try {
140             return (Boolean) mIsSameTrustConfiguration.invoke(mTrustManager, hostname1, hostname2);
141         } catch (IllegalAccessException e) {
142             throw new RuntimeException("Failed to call isSameTrustConfiguration", e);
143         } catch (InvocationTargetException e) {
144             if (e.getCause() instanceof RuntimeException) {
145                 throw (RuntimeException) e.getCause();
146             } else {
147                 throw new RuntimeException("isSameTrustConfiguration failed", e.getCause());
148             }
149         }
150     }
151 }
152