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