xref: /freebsd/contrib/libevent/sample/openssl_hostname_validation.c (revision c6989859ae9388eeb46a24fe88f9b8d07101c710)
1 /* Obtained from: https://github.com/iSECPartners/ssl-conservatory */
2 
3 /*
4 Copyright (C) 2012, iSEC Partners.
5 
6 Permission is hereby granted, free of charge, to any person obtaining a copy of
7 this software and associated documentation files (the "Software"), to deal in
8 the Software without restriction, including without limitation the rights to
9 use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
10 of the Software, and to permit persons to whom the Software is furnished to do
11 so, subject to the following conditions:
12 
13 The above copyright notice and this permission notice shall be included in all
14 copies or substantial portions of the Software.
15 
16 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22 SOFTWARE.
23  */
24 
25 /*
26  * Helper functions to perform basic hostname validation using OpenSSL.
27  *
28  * Please read "everything-you-wanted-to-know-about-openssl.pdf" before
29  * attempting to use this code. This whitepaper describes how the code works,
30  * how it should be used, and what its limitations are.
31  *
32  * Author:  Alban Diquet
33  * License: See LICENSE
34  *
35  */
36 
37 // Get rid of OSX 10.7 and greater deprecation warnings.
38 #if defined(__APPLE__) && defined(__clang__)
39 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
40 #endif
41 
42 #include <openssl/x509v3.h>
43 #include <openssl/ssl.h>
44 #include <string.h>
45 
46 #include "openssl_hostname_validation.h"
47 #include "hostcheck.h"
48 
49 #define HOSTNAME_MAX_SIZE 255
50 
51 #if OPENSSL_VERSION_NUMBER < 0x10100000L
52 #define ASN1_STRING_get0_data ASN1_STRING_data
53 #endif
54 
55 /**
56 * Tries to find a match for hostname in the certificate's Common Name field.
57 *
58 * Returns MatchFound if a match was found.
59 * Returns MatchNotFound if no matches were found.
60 * Returns MalformedCertificate if the Common Name had a NUL character embedded in it.
61 * Returns Error if the Common Name could not be extracted.
62 */
63 static HostnameValidationResult matches_common_name(const char *hostname, const X509 *server_cert) {
64         int common_name_loc = -1;
65         X509_NAME_ENTRY *common_name_entry = NULL;
66         ASN1_STRING *common_name_asn1 = NULL;
67         const char *common_name_str = NULL;
68 
69         // Find the position of the CN field in the Subject field of the certificate
70         common_name_loc = X509_NAME_get_index_by_NID(X509_get_subject_name((X509 *) server_cert), NID_commonName, -1);
71         if (common_name_loc < 0) {
72                 return Error;
73         }
74 
75         // Extract the CN field
76         common_name_entry = X509_NAME_get_entry(X509_get_subject_name((X509 *) server_cert), common_name_loc);
77         if (common_name_entry == NULL) {
78                 return Error;
79         }
80 
81         // Convert the CN field to a C string
82         common_name_asn1 = X509_NAME_ENTRY_get_data(common_name_entry);
83         if (common_name_asn1 == NULL) {
84                 return Error;
85         }
86         common_name_str = (char *) ASN1_STRING_get0_data(common_name_asn1);
87 
88         // Make sure there isn't an embedded NUL character in the CN
89         if ((size_t)ASN1_STRING_length(common_name_asn1) != strlen(common_name_str)) {
90                 return MalformedCertificate;
91         }
92 
93         // Compare expected hostname with the CN
94         if (Curl_cert_hostcheck(common_name_str, hostname) == CURL_HOST_MATCH) {
95                 return MatchFound;
96         }
97         else {
98                 return MatchNotFound;
99         }
100 }
101 
102 
103 /**
104 * Tries to find a match for hostname in the certificate's Subject Alternative Name extension.
105 *
106 * Returns MatchFound if a match was found.
107 * Returns MatchNotFound if no matches were found.
108 * Returns MalformedCertificate if any of the hostnames had a NUL character embedded in it.
109 * Returns NoSANPresent if the SAN extension was not present in the certificate.
110 */
111 static HostnameValidationResult matches_subject_alternative_name(const char *hostname, const X509 *server_cert) {
112         HostnameValidationResult result = MatchNotFound;
113         int i;
114         int san_names_nb = -1;
115         STACK_OF(GENERAL_NAME) *san_names = NULL;
116 
117         // Try to extract the names within the SAN extension from the certificate
118         san_names = X509_get_ext_d2i((X509 *) server_cert, NID_subject_alt_name, NULL, NULL);
119         if (san_names == NULL) {
120                 return NoSANPresent;
121         }
122         san_names_nb = sk_GENERAL_NAME_num(san_names);
123 
124         // Check each name within the extension
125         for (i=0; i<san_names_nb; i++) {
126                 const GENERAL_NAME *current_name = sk_GENERAL_NAME_value(san_names, i);
127 
128                 if (current_name->type == GEN_DNS) {
129                         // Current name is a DNS name, let's check it
130                         const char *dns_name = (char *) ASN1_STRING_get0_data(current_name->d.dNSName);
131 
132                         // Make sure there isn't an embedded NUL character in the DNS name
133                         if ((size_t)ASN1_STRING_length(current_name->d.dNSName) != strlen(dns_name)) {
134                                 result = MalformedCertificate;
135                                 break;
136                         }
137                         else { // Compare expected hostname with the DNS name
138                                 if (Curl_cert_hostcheck(dns_name, hostname)
139                                     == CURL_HOST_MATCH) {
140                                         result = MatchFound;
141                                         break;
142                                 }
143                         }
144                 }
145         }
146         sk_GENERAL_NAME_pop_free(san_names, GENERAL_NAME_free);
147 
148         return result;
149 }
150 
151 
152 /**
153 * Validates the server's identity by looking for the expected hostname in the
154 * server's certificate. As described in RFC 6125, it first tries to find a match
155 * in the Subject Alternative Name extension. If the extension is not present in
156 * the certificate, it checks the Common Name instead.
157 *
158 * Returns MatchFound if a match was found.
159 * Returns MatchNotFound if no matches were found.
160 * Returns MalformedCertificate if any of the hostnames had a NUL character embedded in it.
161 * Returns Error if there was an error.
162 */
163 HostnameValidationResult validate_hostname(const char *hostname, const X509 *server_cert) {
164         HostnameValidationResult result;
165 
166         if((hostname == NULL) || (server_cert == NULL))
167                 return Error;
168 
169         // First try the Subject Alternative Names extension
170         result = matches_subject_alternative_name(hostname, server_cert);
171         if (result == NoSANPresent) {
172                 // Extension was not found: try the Common Name
173                 result = matches_common_name(hostname, server_cert);
174         }
175 
176         return result;
177 }
178