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