[go: nahoru, domu]

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