1/*
2 * Copyright (C) 2010 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 */
16package com.android.internal.net;
17
18import android.net.NetworkUtils;
19import android.util.Log;
20
21import java.net.InetAddress;
22import java.security.cert.CertificateParsingException;
23import java.security.cert.X509Certificate;
24import java.util.Collection;
25import java.util.Iterator;
26import java.util.List;
27import java.util.regex.Pattern;
28import java.util.regex.PatternSyntaxException;
29
30import javax.security.auth.x500.X500Principal;
31
32/** @hide */
33public class DomainNameValidator {
34    private final static String TAG = "DomainNameValidator";
35
36    private static final boolean DEBUG = false;
37    private static final boolean LOG_ENABLED = false;
38
39    private static final int ALT_DNS_NAME = 2;
40    private static final int ALT_IPA_NAME = 7;
41
42    /**
43     * Checks the site certificate against the domain name of the site being visited
44     * @param certificate The certificate to check
45     * @param thisDomain The domain name of the site being visited
46     * @return True iff if there is a domain match as specified by RFC2818
47     */
48    public static boolean match(X509Certificate certificate, String thisDomain) {
49        if (certificate == null || thisDomain == null || thisDomain.length() == 0) {
50            return false;
51        }
52
53        thisDomain = thisDomain.toLowerCase();
54        if (!isIpAddress(thisDomain)) {
55            return matchDns(certificate, thisDomain);
56        } else {
57            return matchIpAddress(certificate, thisDomain);
58        }
59    }
60
61    /**
62     * @return True iff the domain name is specified as an IP address
63     */
64    private static boolean isIpAddress(String domain) {
65        boolean rval = (domain != null && domain.length() != 0);
66        if (rval) {
67            try {
68                // do a quick-dirty IP match first to avoid DNS lookup
69                rval = domain.equals(
70                        NetworkUtils.numericToInetAddress(domain).getHostAddress());
71            } catch (IllegalArgumentException e) {
72                if (LOG_ENABLED) {
73                    Log.v(TAG, "DomainNameValidator.isIpAddress(): " + e);
74                }
75
76                rval = false;
77            }
78        }
79
80        return rval;
81    }
82
83    /**
84     * Checks the site certificate against the IP domain name of the site being visited
85     * @param certificate The certificate to check
86     * @param thisDomain The DNS domain name of the site being visited
87     * @return True iff if there is a domain match as specified by RFC2818
88     */
89    private static boolean matchIpAddress(X509Certificate certificate, String thisDomain) {
90        if (LOG_ENABLED) {
91            Log.v(TAG, "DomainNameValidator.matchIpAddress(): this domain: " + thisDomain);
92        }
93
94        try {
95            Collection subjectAltNames = certificate.getSubjectAlternativeNames();
96            if (subjectAltNames != null) {
97                Iterator i = subjectAltNames.iterator();
98                while (i.hasNext()) {
99                    List altNameEntry = (List)(i.next());
100                    if (altNameEntry != null && 2 <= altNameEntry.size()) {
101                        Integer altNameType = (Integer)(altNameEntry.get(0));
102                        if (altNameType != null) {
103                            if (altNameType.intValue() == ALT_IPA_NAME) {
104                                String altName = (String)(altNameEntry.get(1));
105                                if (altName != null) {
106                                    if (LOG_ENABLED) {
107                                        Log.v(TAG, "alternative IP: " + altName);
108                                    }
109                                    if (thisDomain.equalsIgnoreCase(altName)) {
110                                        return true;
111                                    }
112                                }
113                            }
114                        }
115                    }
116                }
117            }
118        } catch (CertificateParsingException e) {}
119
120        return false;
121    }
122
123    /**
124     * Checks the site certificate against the DNS domain name of the site being visited
125     * @param certificate The certificate to check
126     * @param thisDomain The DNS domain name of the site being visited
127     * @return True iff if there is a domain match as specified by RFC2818
128     */
129    private static boolean matchDns(X509Certificate certificate, String thisDomain) {
130        boolean hasDns = false;
131        try {
132            Collection subjectAltNames = certificate.getSubjectAlternativeNames();
133            if (subjectAltNames != null) {
134                Iterator i = subjectAltNames.iterator();
135                while (i.hasNext()) {
136                    List altNameEntry = (List)(i.next());
137                    if (altNameEntry != null && 2 <= altNameEntry.size()) {
138                        Integer altNameType = (Integer)(altNameEntry.get(0));
139                        if (altNameType != null) {
140                            if (altNameType.intValue() == ALT_DNS_NAME) {
141                                hasDns = true;
142                                String altName = (String)(altNameEntry.get(1));
143                                if (altName != null) {
144                                    if (matchDns(thisDomain, altName)) {
145                                        return true;
146                                    }
147                                }
148                            }
149                        }
150                    }
151                }
152            }
153        } catch (CertificateParsingException e) {
154            String errorMessage = e.getMessage();
155            if (errorMessage == null) {
156                errorMessage = "failed to parse certificate";
157            }
158
159            Log.w(TAG, "DomainNameValidator.matchDns(): " + errorMessage);
160            return false;
161        }
162
163        if (!hasDns) {
164            final String cn = new DNParser(certificate.getSubjectX500Principal())
165                    .find("cn");
166            if (LOG_ENABLED) {
167                Log.v(TAG, "Validating subject: DN:"
168                        + certificate.getSubjectX500Principal().getName(X500Principal.CANONICAL)
169                        + "  CN:" + cn);
170            }
171            if (cn != null) {
172                return matchDns(thisDomain, cn);
173            }
174        }
175
176        return false;
177    }
178
179    /**
180     * @param thisDomain The domain name of the site being visited
181     * @param thatDomain The domain name from the certificate
182     * @return True iff thisDomain matches thatDomain as specified by RFC2818
183     */
184    // not private for testing
185    public static boolean matchDns(String thisDomain, String thatDomain) {
186        if (LOG_ENABLED) {
187            Log.v(TAG, "DomainNameValidator.matchDns():" +
188                      " this domain: " + thisDomain +
189                      " that domain: " + thatDomain);
190        }
191
192        if (thisDomain == null || thisDomain.length() == 0 ||
193            thatDomain == null || thatDomain.length() == 0) {
194            return false;
195        }
196
197        thatDomain = thatDomain.toLowerCase();
198
199        // (a) domain name strings are equal, ignoring case: X matches X
200        boolean rval = thisDomain.equals(thatDomain);
201        if (!rval) {
202            String[] thisDomainTokens = thisDomain.split("\\.");
203            String[] thatDomainTokens = thatDomain.split("\\.");
204
205            int thisDomainTokensNum = thisDomainTokens.length;
206            int thatDomainTokensNum = thatDomainTokens.length;
207
208            // (b) OR thatHost is a '.'-suffix of thisHost: Z.Y.X matches X
209            if (thisDomainTokensNum >= thatDomainTokensNum) {
210                for (int i = thatDomainTokensNum - 1; i >= 0; --i) {
211                    rval = thisDomainTokens[i].equals(thatDomainTokens[i]);
212                    if (!rval) {
213                        // (c) OR we have a special *-match:
214                        // *.Y.X matches Z.Y.X but *.X doesn't match Z.Y.X
215                        rval = (i == 0 && thisDomainTokensNum == thatDomainTokensNum);
216                        if (rval) {
217                            rval = thatDomainTokens[0].equals("*");
218                            if (!rval) {
219                                // (d) OR we have a *-component match:
220                                // f*.com matches foo.com but not bar.com
221                                rval = domainTokenMatch(
222                                    thisDomainTokens[0], thatDomainTokens[0]);
223                            }
224                        }
225                        break;
226                    }
227                }
228            } else {
229              // (e) OR thatHost has a '*.'-prefix of thisHost:
230              // *.Y.X matches Y.X
231              rval = thatDomain.equals("*." + thisDomain);
232            }
233        }
234
235        return rval;
236    }
237
238    /**
239     * @param thisDomainToken The domain token from the current domain name
240     * @param thatDomainToken The domain token from the certificate
241     * @return True iff thisDomainToken matches thatDomainToken, using the
242     * wildcard match as specified by RFC2818-3.1. For example, f*.com must
243     * match foo.com but not bar.com
244     */
245    private static boolean domainTokenMatch(String thisDomainToken, String thatDomainToken) {
246        if (thisDomainToken != null && thatDomainToken != null) {
247            int starIndex = thatDomainToken.indexOf('*');
248            if (starIndex >= 0) {
249                if (thatDomainToken.length() - 1 <= thisDomainToken.length()) {
250                    String prefix = thatDomainToken.substring(0,  starIndex);
251                    String suffix = thatDomainToken.substring(starIndex + 1);
252
253                    return thisDomainToken.startsWith(prefix) && thisDomainToken.endsWith(suffix);
254                }
255            }
256        }
257
258        return false;
259    }
260}
261