SNode.C
Loading...
Searching...
No Matches
ssl_utils.cpp
Go to the documentation of this file.
1/*
2 * SNode.C - A Slim Toolkit for Network Communication
3 * Copyright (C) Volker Christian <me@vchrist.at>
4 * 2020, 2021, 2022, 2023, 2024, 2025
5 *
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU Lesser General Public License as published
8 * by the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU Lesser General Public License for more details.
15 *
16 * You should have received a copy of the GNU Lesser General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 */
19
20/*
21 * MIT License
22 *
23 * Permission is hereby granted, free of charge, to any person obtaining a copy
24 * of this software and associated documentation files (the "Software"), to deal
25 * in the Software without restriction, including without limitation the rights
26 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
27 * copies of the Software, and to permit persons to whom the Software is
28 * furnished to do so, subject to the following conditions:
29 *
30 * The above copyright notice and this permission notice shall be included in
31 * all copies or substantial portions of the Software.
32 *
33 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
34 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
35 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
36 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
37 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
38 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
39 * THE SOFTWARE.
40 */
41
42#ifndef DOXYGEN_SHOULD_SKIP_THIS
43
44#include "core/socket/stream/tls/ssl_utils.h"
45
46#include "log/Logger.h"
47#include "utils/PreserveErrno.h"
48
49#include <cerrno>
50#include <cstdint>
51#include <cstdlib>
52#include <cstring>
53#include <openssl/asn1.h>
54#include <openssl/err.h>
55#include <openssl/obj_mac.h>
56#include <openssl/ssl.h>
57#include <openssl/x509.h>
58#include <openssl/x509v3.h>
59#include <string>
60
61#endif /* DOXYGEN_SHOULD_SKIP_THIS */
62
63namespace core::socket::stream::tls {
64
65 static int password_callback(char* buf, int size, [[maybe_unused]] int a, void* u) {
66 strncpy(buf, static_cast<char*>(u), static_cast<std::size_t>(size));
67 buf[size - 1] = '\0';
68
69 memset(u, 0, ::strlen(static_cast<char*>(u))); // garble Password
70 free(u);
71
72 return static_cast<int>(std::strlen(buf));
73 }
74
75 static int verify_callback(int preverify_ok, X509_STORE_CTX* ctx) {
76 SSL* ssl = static_cast<SSL*>(X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx()));
77
78 const std::string connectionName = *static_cast<std::string*>(SSL_get_ex_data(ssl, 0));
79
80 X509* curr_cert = X509_STORE_CTX_get_current_cert(ctx);
81 const int depth = X509_STORE_CTX_get_error_depth(ctx);
82
83 char subjectName[256];
84 X509_NAME_oneline(X509_get_subject_name(curr_cert), subjectName, 256);
85
86 char issuerName[256];
87 X509_NAME_oneline(X509_get_issuer_name(curr_cert), issuerName, 256);
88
89 if (preverify_ok != 0) {
90 LOG(DEBUG) << connectionName << ": SSL/TLS verify success at depth=" << depth;
91 LOG(DEBUG) << " Issuer: " << issuerName;
92 LOG(DEBUG) << " Subject: " << subjectName;
93 } else {
94 const int err = X509_STORE_CTX_get_error(ctx);
95
96 LOG(DEBUG) << connectionName << ": SSL/TLS verify error at depth=" << depth << ": " << X509_verify_cert_error_string(err);
97 LOG(DEBUG) << " Issuer: " << issuerName;
98 LOG(DEBUG) << " Subject: " << subjectName;
99
100 /*
101 * At this point, err contains the last verification error. We can use
102 * it for something special and set preverify_ok to 1 in case an unsafe connection
103 * shall be used.
104 */
105 }
106
107 return preverify_ok;
108 }
109
110 SslConfig::SslConfig(bool server)
111 : server(server) {
112 }
113
114 SSL_CTX* ssl_ctx_new(const SslConfig& sslConfig) {
115 static int sslSessionCtxId = 1;
116
117 SSL_CTX* ctx = SSL_CTX_new(sslConfig.server ? TLS_server_method() : TLS_client_method());
118
119 if (ctx != nullptr) {
120 SSL_CTX_set_read_ahead(ctx, 1);
121
122 SSL_CTX_set_mode(ctx, SSL_MODE_ENABLE_PARTIAL_WRITE);
123 SSL_CTX_set_mode(ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
124
125 bool sslErr = false;
126
127 if (sslConfig.server) {
128 SSL_CTX_set_session_id_context(ctx, reinterpret_cast<const unsigned char*>(&sslSessionCtxId), sizeof(sslSessionCtxId));
129 sslSessionCtxId++;
130 }
131 if (!sslConfig.caCert.empty() || !sslConfig.caCertDir.empty()) {
132 if (SSL_CTX_load_verify_locations(ctx,
133 !sslConfig.caCert.empty() ? sslConfig.caCert.c_str() : nullptr,
134 !sslConfig.caCertDir.empty() ? sslConfig.caCertDir.c_str() : nullptr) == 0) {
135 ssl_log_error(sslConfig.instanceName + " SSL/TLS: CA certificate error loading file '" + sslConfig.caCert + "', dir '" +
136 sslConfig.caCertDir + "'");
137 sslErr = true;
138 } else {
139 if (!sslConfig.caCert.empty()) {
140 LOG(TRACE) << sslConfig.instanceName << " SSL/TLS: CA certificate loaded";
141 LOG(TRACE) << " " << sslConfig.caCert;
142 } else {
143 LOG(TRACE) << sslConfig.instanceName << " SSL/TLS: CA certificate not loaded from a file";
144 }
145 if (!sslConfig.caCertDir.empty()) {
146 LOG(TRACE) << sslConfig.instanceName << " SSL/TLS: CA certificates load from";
147 LOG(TRACE) << " " << sslConfig.caCertDir;
148 } else {
149 LOG(TRACE) << sslConfig.instanceName << " SSL/TLS: CA certificates not loaded from a directory";
150 }
151 }
152 } else {
153 LOG(TRACE) << sslConfig.instanceName << " SSL/TLS: CA certificate not loaded from a file";
154 LOG(TRACE) << sslConfig.instanceName << " SSL/TLS: CA certificates not loaded from a directory";
155 }
156 if (!sslErr && sslConfig.caCertUseDefaultDir) {
157 if (SSL_CTX_set_default_verify_paths(ctx) == 0) {
158 ssl_log_error(sslConfig.instanceName + " SSL/TLS: CA certificates error load from default openssl CA directory");
159 sslErr = true;
160 } else {
161 LOG(TRACE) << sslConfig.instanceName << " SSL/TLS: CA certificates enabled load from default openssl CA directory";
162 }
163 } else {
164 LOG(TRACE) << sslConfig.instanceName << " SSL/TLS: CA certificates not loaded from default openssl CA directory";
165 }
166 if (!sslErr) {
167 SSL_CTX_set_verify_depth(ctx, 5);
168 SSL_CTX_set_verify(ctx,
169 (sslConfig.caCertAcceptUnknown ? SSL_VERIFY_NONE
170 : (!sslConfig.caCert.empty() || !sslConfig.caCertDir.empty() || sslConfig.caCertUseDefaultDir)
171 ? SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE | SSL_VERIFY_FAIL_IF_NO_PEER_CERT
172 : 0),
174 if ((SSL_CTX_get_verify_mode(ctx) & SSL_VERIFY_PEER) != 0) {
175 LOG(TRACE) << sslConfig.instanceName << " SSL/TLS: CA requested verify";
176 }
177 if (!sslConfig.cert.empty()) {
178 if (SSL_CTX_use_certificate_chain_file(ctx, sslConfig.cert.c_str()) == 0) {
179 ssl_log_error(sslConfig.instanceName + " SSL/TLS: Cert chain error loading from file '" + sslConfig.cert + "'");
180 sslErr = true;
181 } else if (!sslConfig.certKey.empty()) {
182 if (!sslConfig.password.empty()) {
183 SSL_CTX_set_default_passwd_cb(ctx, password_callback);
184 SSL_CTX_set_default_passwd_cb_userdata(ctx, ::strdup(sslConfig.password.c_str()));
185 }
186 if (SSL_CTX_use_PrivateKey_file(ctx, sslConfig.certKey.c_str(), SSL_FILETYPE_PEM) == 0) {
187 ssl_log_error(sslConfig.instanceName + " SSL/TLS: Cert chain key error loading file '" + sslConfig.certKey +
188 "'");
189 sslErr = true;
190 } else if (SSL_CTX_check_private_key(ctx) != 1) {
191 ssl_log_error(sslConfig.instanceName + " SSL/TLS: Cert chain key error");
192
193 LOG(TRACE) << " " << sslConfig.certKey;
194 sslErr = true;
195 } else {
196 LOG(TRACE) << sslConfig.instanceName << " SSL/TLS: Cert chain key loaded";
197 LOG(TRACE) << " " << sslConfig.certKey;
198
199 LOG(TRACE) << sslConfig.instanceName << " SSL/TLS: Cert chain loaded";
200 LOG(TRACE) << " " << sslConfig.cert;
201 }
202 }
203 }
204 }
205 if (!sslErr) {
206 if (sslConfig.sslOptions != 0) {
207 SSL_CTX_set_options(ctx, sslConfig.sslOptions);
208 }
209 if (!sslConfig.cipherList.empty()) {
210 SSL_CTX_set_cipher_list(ctx, sslConfig.cipherList.c_str());
211 }
212 } else {
213 SSL_CTX_free(ctx);
214 ctx = nullptr;
215 }
216 }
217
218 return ctx;
219 }
220
221 std::map<std::string, SSL_CTX*> ssl_get_sans(SSL_CTX* sslCtx) {
222 std::map<std::string, SSL_CTX*> sans;
223
224 if (sslCtx != nullptr) {
225 X509* x509 = SSL_CTX_get0_certificate(sslCtx);
226 if (x509 != nullptr) {
227 GENERAL_NAMES* subjectAltNames =
228 static_cast<GENERAL_NAMES*>(X509_get_ext_d2i(x509, NID_subject_alt_name, nullptr, nullptr));
229
230 const int32_t altNameCount = sk_GENERAL_NAME_num(subjectAltNames);
231
232 for (int32_t i = 0; i < altNameCount; ++i) {
233 GENERAL_NAME* generalName = sk_GENERAL_NAME_value(subjectAltNames, i);
234 if (generalName->type == GEN_DNS || generalName->type == GEN_URI || generalName->type == GEN_EMAIL) {
235 const std::string subjectAltName =
236 std::string(reinterpret_cast<const char*>(ASN1_STRING_get0_data(generalName->d.dNSName)),
237 static_cast<std::size_t>(ASN1_STRING_length(generalName->d.dNSName)));
238 sans.insert({subjectAltName, sslCtx});
239 }
240 }
241
242 sk_GENERAL_NAME_pop_free(subjectAltNames, GENERAL_NAME_free);
243 }
244 }
245
246 return sans;
247 }
248
249 void ssl_set_sni(SSL* ssl, const std::string& sni) {
250 if (!sni.empty()) {
251 SSL_set_tlsext_host_name(ssl, sni.data());
252 }
253 }
254
255 SSL_CTX* ssl_set_ssl_ctx(SSL* ssl, SSL_CTX* sslCtx) {
256 SSL_CTX* newSslCtx = SSL_set_SSL_CTX(ssl, sslCtx);
257 SSL_clear_options(ssl, 0xFFFFFFFFL);
258 SSL_set_options(ssl, SSL_CTX_get_options(sslCtx));
259 SSL_set_verify(ssl, SSL_CTX_get_verify_mode(sslCtx), SSL_CTX_get_verify_callback(sslCtx));
260 SSL_set_verify_depth(ssl, SSL_CTX_get_verify_depth(sslCtx));
261 SSL_set_mode(ssl, SSL_CTX_get_mode(sslCtx));
262
263 return newSslCtx;
264 }
265
266 void ssl_ctx_free(SSL_CTX* ctx) {
267 if (ctx != nullptr) {
268 SSL_CTX_free(ctx);
269 }
270 }
271
272 // From: https://www.bit-hive.com/documents/openssl-tutorial/
274 const unsigned char* ext = nullptr;
275 size_t ext_len = 0;
276 size_t p = 0;
277 size_t server_name_list_len = 0;
278 size_t server_name_len = 0;
279
280 if (SSL_client_hello_get0_ext(ssl, TLSEXT_TYPE_server_name, &ext, &ext_len) == 0) {
281 return "";
282 }
283
284 /* length (2 bytes) + type (1) + length (2) + server name (1+) */
285 if (ext_len < 6) {
286 return "";
287 }
288
289 /* Fetch Server Name list length */
290 server_name_list_len = static_cast<size_t>((ext[p] << 8) + ext[p + 1]);
291 p += 2;
292 if (p + server_name_list_len != ext_len) {
293 return "";
294 }
295
296 /* Fetch Server Name Type */
297 if (ext[p] != TLSEXT_NAMETYPE_host_name) {
298 return "";
299 }
300 p++;
301
302 /* Fetch Server Name Length */
303 server_name_len = static_cast<size_t>((ext[p] << 8) + ext[p + 1]);
304 p += 2;
305 if (p + server_name_len != ext_len) {
306 return "";
307 }
308
309 /* ext_len >= 6 && p == 5 */
310
311 /* Finally fetch Server Name */
312
313 return std::string(reinterpret_cast<const char*>(ext + p), ext_len - p);
314 }
315
316 void ssl_log(const std::string& message, int sslErr) {
317 const utils::PreserveErrno preserveErrno;
318
319 switch (sslErr) {
320 case SSL_ERROR_NONE:
321 [[fallthrough]];
322 case SSL_ERROR_ZERO_RETURN:
323 ssl_log_info(message);
324 break;
325 case SSL_ERROR_SYSCALL:
326 if (errno != 0) {
327 ssl_log_error(message);
328 } else {
329 ssl_log_info(message);
330 }
331 break;
332 case SSL_ERROR_SSL:
333 ssl_log_error(message);
334 break;
335 default:
336 ssl_log_warning(message);
337 break;
338 }
339 }
340
341 void ssl_log_error(const std::string& message) {
342 LOG(ERROR) << message;
343 LOG(ERROR) << " " << ERR_error_string(ERR_get_error(), nullptr);
344
345 unsigned long errorCode = 0;
346 while ((errorCode = ERR_get_error()) != 0) {
347 LOG(ERROR) << " " << ERR_error_string(errorCode, nullptr);
348 }
349 }
350
351 void ssl_log_warning(const std::string& message) {
352 LOG(WARNING) << message;
353 LOG(WARNING) << " " << ERR_error_string(ERR_get_error(), nullptr);
354
355 unsigned long errorCode = 0;
356 while ((errorCode = ERR_get_error()) != 0) {
357 LOG(WARNING) << " " << ERR_error_string(errorCode, nullptr);
358 }
359 }
360
361 void ssl_log_info(const std::string& message) {
362 LOG(INFO) << message;
363 LOG(INFO) << " " << ERR_error_string(ERR_get_error(), nullptr);
364
365 unsigned long errorCode = 0;
366 while ((errorCode = ERR_get_error()) != 0) {
367 LOG(INFO) << " " << ERR_error_string(errorCode, nullptr);
368 }
369 }
370
371 bool match(const char* first, const char* second) {
372 // If we reach at the end of both strings, we are done
373 if (*first == '\0' && *second == '\0') {
374 return true;
375 }
376
377 // Make sure to eliminate consecutive '*'
378 if (*first == '*') {
379 while (*(first + 1) == '*') {
380 first++;
381 }
382 }
383
384 // Make sure that the characters after '*' are present
385 // in second string. This function assumes that the
386 // first string will not contain two consecutive '*'
387 if (*first == '*' && *(first + 1) != '\0' && *second == '\0') {
388 return false;
389 }
390
391 // If the first string contains '?', or current
392 // characters of both strings match
393 if (*first == '?' || *first == *second) {
394 return match(first + 1, second + 1);
395 }
396
397 // If there is *, then there are two possibilities
398 // a) We consider current character of second string
399 // b) We ignore current character of second string.
400 if (*first == '*') {
401 return match(first + 1, second) || match(first, second + 1);
402 }
403
404 return false;
405 }
406
407} // namespace core::socket::stream::tls
void ssl_set_sni(SSL *ssl, const std::string &sni)
bool match(const char *first, const char *second)
static int verify_callback(int preverify_ok, X509_STORE_CTX *ctx)
Definition ssl_utils.cpp:75
void ssl_log_warning(const std::string &message)
static int password_callback(char *buf, int size, int a, void *u)
Definition ssl_utils.cpp:65
SSL_CTX * ssl_set_ssl_ctx(SSL *ssl, SSL_CTX *sslCtx)
void ssl_log_info(const std::string &message)
std::string ssl_get_servername_from_client_hello(SSL *ssl)
void ssl_log(const std::string &message, int sslErr)
void ssl_ctx_free(SSL_CTX *ctx)
std::map< std::string, SSL_CTX * > ssl_get_sans(SSL_CTX *sslCtx)
SSL_CTX * ssl_ctx_new(const SslConfig &sslConfig)
void ssl_log_error(const std::string &message)