Corrected bugs in record parsing.
[gnutls.git] / lib / x509 / rfc2818_hostname.c
blobc53476f578e156a458adcb74d423f8f10a7391c7
1 /*
2 * Copyright (C) 2003-2012 Free Software Foundation, Inc.
3 * Copyright (C) 2002 Andrew McDonald
5 * This file is part of GnuTLS.
7 * The GnuTLS is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public License
9 * as published by the Free Software Foundation; either version 3 of
10 * the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public License
18 * along with this program. If not, see <http://www.gnu.org/licenses/>
22 #include <gnutls_int.h>
23 #include <gnutls_str.h>
24 #include <x509_int.h>
25 #include <common.h>
26 #include <gnutls_errors.h>
28 /**
29 * gnutls_x509_crt_check_hostname:
30 * @cert: should contain an gnutls_x509_crt_t structure
31 * @hostname: A null terminated string that contains a DNS name
33 * This function will check if the given certificate's subject matches
34 * the given hostname. This is a basic implementation of the matching
35 * described in RFC2818 (HTTPS), which takes into account wildcards,
36 * and the DNSName/IPAddress subject alternative name PKIX extension.
38 * Returns: non-zero for a successful match, and zero on failure.
39 **/
40 int
41 gnutls_x509_crt_check_hostname (gnutls_x509_crt_t cert, const char *hostname)
44 char dnsname[MAX_CN];
45 size_t dnsnamesize;
46 int found_dnsname = 0;
47 int ret = 0;
48 int i = 0;
50 /* try matching against:
51 * 1) a DNS name as an alternative name (subjectAltName) extension
52 * in the certificate
53 * 2) the common name (CN) in the certificate
55 * either of these may be of the form: *.domain.tld
57 * only try (2) if there is no subjectAltName extension of
58 * type dNSName
61 /* Check through all included subjectAltName extensions, comparing
62 * against all those of type dNSName.
64 for (i = 0; !(ret < 0); i++)
67 dnsnamesize = sizeof (dnsname);
68 ret = gnutls_x509_crt_get_subject_alt_name (cert, i,
69 dnsname, &dnsnamesize,
70 NULL);
72 if (ret == GNUTLS_SAN_DNSNAME)
74 found_dnsname = 1;
75 if (_gnutls_hostname_compare (dnsname, dnsnamesize, hostname, 0))
77 return 1;
82 if (!found_dnsname)
84 /* not got the necessary extension, use CN instead
86 dnsnamesize = sizeof (dnsname);
87 if (gnutls_x509_crt_get_dn_by_oid (cert, OID_X520_COMMON_NAME, 0,
88 0, dnsname, &dnsnamesize) < 0)
90 /* got an error, can't find a name
92 return 0;
95 if (_gnutls_hostname_compare (dnsname, dnsnamesize, hostname, 0))
97 return 1;
101 /* not found a matching name
103 return 0;