Debian Codegraph @

runtime/net_ossl.c

raw
1 /* net.c
2 * Implementation of network-related stuff.
3 *
4 * File begun on 2023-08-29 by Alorbach (extracted from net.c)
5 *
6 * Copyright 2023 Andre Lorbach and Adiscon GmbH.
7 *
8 * This file is part of rsyslog.
9 *
10 * Licensed under the Apache License, Version 2.0 (the "License");
11 * you may not use this file except in compliance with the License.
12 * You may obtain a copy of the License at
13 *
14 * http://www.apache.org/licenses/LICENSE-2.0
15 * -or-
16 * see COPYING.ASL20 in the source distribution
17 *
18 * Unless required by applicable law or agreed to in writing, software
19 * distributed under the License is distributed on an "AS IS" BASIS,
20 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21 * See the License for the specific language governing permissions and
22 * limitations under the License.
23 */
24 #include "config.h"
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <assert.h>
28 #include <string.h>
29 #include <strings.h>
30
31 #include <errno.h>
32 #include <sys/stat.h>
33 #include <unistd.h>
34 #include <fcntl.h>
35 #include <pthread.h>
36 #include <netdb.h>
37 #include <sys/select.h>
38 #include <sys/time.h>
39
40 #include "rsyslog.h"
41 #include "syslogd-types.h"
42 #include "module-template.h"
43 #include "parse.h"
44 #include "srUtils.h"
45 #include "obj.h"
46 #include "errmsg.h"
47 #include "net.h"
48 #include "net_ossl.h"
49 #include "nsd_ptcp.h"
50 #include "rsconf.h"
51
52 #define OCSP_TIMEOUT 5
53 #define OCSP_CACHE_MAX_ENTRIES 100
54 #define OCSP_CACHE_DEFAULT_TTL 3600
55
56 /* static data */
57 DEFobjStaticHelpers;
58 DEFobjCurrIf(glbl) DEFobjCurrIf(net) DEFobjCurrIf(nsd_ptcp)
59
60 /* Prototypes for openssl helper functions */
61 void net_ossl_lastOpenSSLErrorMsg(
62 uchar *fromHost, int ret, SSL *ssl, int severity, const char *pszCallSource, const char *pszOsslApi);
63 void net_ossl_set_ssl_verify_callback(SSL *pSsl, int flags);
64 void net_ossl_set_ctx_verify_callback(SSL_CTX *pCtx, int flags);
65 void net_ossl_set_bio_callback(BIO *conn);
66 int net_ossl_verify_callback(int status, X509_STORE_CTX *store);
67 #if OPENSSL_VERSION_NUMBER >= 0x10002000L && !defined(LIBRESSL_VERSION_NUMBER) && !defined(ENABLE_WOLFSSL)
68 rsRetVal net_ossl_apply_tlscgfcmd(net_ossl_t *pThis, uchar *tlscfgcmd);
69 #endif // OPENSSL_VERSION_NUMBER >= 0x10002000L
70 rsRetVal net_ossl_chkpeercertvalidity(net_ossl_t *pThis, SSL *ssl, uchar *fromHostIP);
71 X509 *net_ossl_getpeercert(net_ossl_t *pThis, SSL *ssl, uchar *fromHostIP);
72 rsRetVal net_ossl_peerfingerprint(net_ossl_t *pThis, X509 *certpeer, uchar *fromHostIP);
73 #ifndef ENABLE_WOLFSSL
74 void ocsp_cache_cleanup(void);
75 #endif
76 rsRetVal net_ossl_chkpeername(net_ossl_t *pThis, X509 *certpeer, uchar *fromHostIP);
77
78
79 /*--------------------------------------MT OpenSSL helpers ------------------------------------------*/
80 #ifndef ENABLE_WOLFSSL
81 static MUTEX_TYPE *mutex_buf = NULL;
82 static sbool openssl_initialized = 0; // Avoid multiple initialization / deinitialization
83
84 void locking_function(int mode, int n, __attribute__((unused)) const char *file, __attribute__((unused)) int line) {
85 if (mode & CRYPTO_LOCK)
86 MUTEX_LOCK(mutex_buf[n]);
87 else
88 MUTEX_UNLOCK(mutex_buf[n]);
89 }
90
91 unsigned long id_function(void) {
92 return ((unsigned long)THREAD_ID);
93 }
94
95
96 struct CRYPTO_dynlock_value *dyn_create_function(__attribute__((unused)) const char *file,
97 __attribute__((unused)) int line) {
98 struct CRYPTO_dynlock_value *value;
99 value = (struct CRYPTO_dynlock_value *)malloc(sizeof(struct CRYPTO_dynlock_value));
100 if (!value) return NULL;
101
102 MUTEX_SETUP(value->mutex);
103 return value;
104 }
105
106 void dyn_lock_function(int mode,
107 struct CRYPTO_dynlock_value *l,
108 __attribute__((unused)) const char *file,
109 __attribute__((unused)) int line) {
110 if (mode & CRYPTO_LOCK)
111 MUTEX_LOCK(l->mutex);
112 else
113 MUTEX_UNLOCK(l->mutex);
114 }
115
116 void dyn_destroy_function(struct CRYPTO_dynlock_value *l,
117 __attribute__((unused)) const char *file,
118 __attribute__((unused)) int line) {
119 MUTEX_CLEANUP(l->mutex);
120 free(l);
121 }
122
123 /* set up support functions for openssl multi-threading. This must
124 * be done at library initialisation. If the function fails,
125 * processing can not continue normally. On failure, 0 is
126 * returned, on success 1.
127 */
128 int opensslh_THREAD_setup(void) {
129 int i;
130 if (openssl_initialized == 1) {
131 DBGPRINTF("openssl: multithread setup already initialized\n");
132 return 1;
133 }
134
135 mutex_buf = (MUTEX_TYPE *)malloc(CRYPTO_num_locks() * sizeof(MUTEX_TYPE));
136 if (mutex_buf == NULL) return 0;
137 for (i = 0; i < CRYPTO_num_locks(); i++) MUTEX_SETUP(mutex_buf[i]);
138
139 #if OPENSSL_VERSION_NUMBER < 0x10100000L
140 CRYPTO_set_id_callback(id_function);
141 #endif /* OPENSSL_VERSION_NUMBER < 0x10100000L */
142 CRYPTO_set_locking_callback(locking_function);
143 /* The following three CRYPTO_... functions are the OpenSSL functions
144 for registering the callbacks we implemented above */
145 CRYPTO_set_dynlock_create_callback(dyn_create_function);
146 CRYPTO_set_dynlock_lock_callback(dyn_lock_function);
147 CRYPTO_set_dynlock_destroy_callback(dyn_destroy_function);
148
149 DBGPRINTF("openssl: multithread setup finished\n");
150 openssl_initialized = 1;
151 return 1;
152 }
153
154 /* shut down openssl - do this only when you are totally done
155 * with openssl.
156 */
157 int opensslh_THREAD_cleanup(void) {
158 int i;
159 if (openssl_initialized == 0) {
160 DBGPRINTF("openssl: multithread cleanup already done\n");
161 return 1;
162 }
163 if (!mutex_buf) return 0;
164
165 #if OPENSSL_VERSION_NUMBER < 0x10100000L
166 CRYPTO_set_id_callback(NULL);
167 #endif /* OPENSSL_VERSION_NUMBER < 0x10100000L */
168 CRYPTO_set_locking_callback(NULL);
169 CRYPTO_set_dynlock_create_callback(NULL);
170 CRYPTO_set_dynlock_lock_callback(NULL);
171 CRYPTO_set_dynlock_destroy_callback(NULL);
172
173 for (i = 0; i < CRYPTO_num_locks(); i++) MUTEX_CLEANUP(mutex_buf[i]);
174
175 free(mutex_buf);
176 mutex_buf = NULL;
177
178 DBGPRINTF("openssl: multithread cleanup finished\n");
179 openssl_initialized = 0;
180 return 1;
181 }
182 #else
183 int opensslh_THREAD_setup(void) {
184 return 1;
185 }
186
187 int opensslh_THREAD_cleanup(void) {
188 return 1;
189 }
190 #endif /* !ENABLE_WOLFSSL */
191 /*-------------------------------------- MT OpenSSL helpers -----------------------------------------*/
192
193
194 /*--------------------------------------OpenSSL helpers ------------------------------------------*/
195
196 /* globally initialize OpenSSL
197 */
198 void osslGlblInit(void) {
199 DBGPRINTF("osslGlblInit: ENTER\n");
200
201 #ifdef ENABLE_WOLFSSL
202 if (!SSL_library_init()) {
203 LogError(0, RS_RET_NO_ERRCODE, "Error: OpenSSL initialization failed!");
204 }
205 #else
206 if ((opensslh_THREAD_setup() == 0) ||
207 #if OPENSSL_VERSION_NUMBER < 0x10100000L
208 /* Setup OpenSSL library < 1.1.0 */
209 !SSL_library_init()
210 #else
211 /* Setup OpenSSL library >= 1.1.0 with system default settings */
212 OPENSSL_init_ssl(0, NULL) == 0
213 #endif
214 ) {
215 LogError(0, RS_RET_NO_ERRCODE, "Error: OpenSSL initialization failed!");
216 }
217 #endif
218
219 #if defined(ENABLE_WOLFSSL) && defined(DEBUG_WOLFSSL)
220 wolfSSL_Debugging_ON();
221 #endif
222
223 /* Load readable error strings */
224 SSL_load_error_strings();
225 #if OPENSSL_VERSION_NUMBER >= 0x30000000L && !defined(LIBRESSL_VERSION_NUMBER)
226 /*
227 * ERR_load_*(), ERR_func_error_string(), ERR_get_error_line(), ERR_get_error_line_data(), ERR_get_state()
228 * OpenSSL now loads error strings automatically so these functions are not needed.
229 * SEE FOR MORE:
230 * https://www.openssl.org/docs/manmaster/man7/migration_guide.html
231 *
232 */
233 #else
234 /* Load error strings into mem*/
235 ERR_load_BIO_strings();
236 ERR_load_crypto_strings();
237 #endif
238
239 PRAGMA_DIAGNOSTIC_PUSH
240 PRAGMA_IGNORE_Wdeprecated_declarations
241
242 #ifndef OPENSSL_NO_ENGINE
243 // Initialize OpenSSL engine library
244 ENGINE_load_builtin_engines();
245 /* Register all of them for every algorithm they collectively implement */
246 ENGINE_register_all_complete();
247
248 // Iterate through all available engines
249 ENGINE *osslEngine = ENGINE_get_first();
250 const char *engine_id = NULL;
251 const char *engine_name = NULL;
252 while (osslEngine) {
253 // Print engine ID and name if the engine is loaded
254 if (ENGINE_get_init_function(osslEngine)) { // Check if engine is initialized
255 engine_id = ENGINE_get_id(osslEngine);
256 engine_name = ENGINE_get_name(osslEngine);
257 DBGPRINTF("osslGlblInit: Loaded Engine: ID = %s, Name = %s\n", engine_id, engine_name);
258 }
259 osslEngine = ENGINE_get_next(osslEngine);
260 }
261 // Free the engine reference when done
262 ENGINE_free(osslEngine);
263 #else
264 DBGPRINTF("osslGlblInit: OpenSSL compiled without ENGINE support - ENGINE support disabled\n");
265 #endif /* OPENSSL_NO_ENGINE */
266
267 PRAGMA_DIAGNOSTIC_POP
268 }
269
270 /* globally de-initialize OpenSSL */
271 void osslGlblExit(void) {
272 DBGPRINTF("openssl: entering osslGlblExit\n");
273 #ifndef ENABLE_WOLFSSL
274 ocsp_cache_cleanup();
275 #endif
276 #ifndef OPENSSL_NO_ENGINE
277 ENGINE_cleanup();
278 #endif
279 ERR_free_strings();
280 EVP_cleanup();
281 CRYPTO_cleanup_all_ex_data();
282 }
283
284
285 /* initialize openssl context; called on
286 * - listener creation
287 * - outbound connection creation
288 * Once created, the ctx object is used by-subobjects (accepted inbound connections)
289 */
290 static rsRetVal net_ossl_osslCtxInit(net_ossl_t *pThis, const SSL_METHOD *method) {
291 DEFiRet;
292 int bHaveCA;
293 int bHaveCRL;
294 int bHaveCert;
295 int bHaveKey;
296 int bHaveExtraCAFiles;
297 const char *caFile, *crlFile, *certFile, *keyFile;
298 char *extraCaFiles, *extraCaFile;
299 /* Setup certificates */
300 caFile = (char *)((pThis->pszCAFile == NULL) ? glbl.GetDfltNetstrmDrvrCAF(runConf) : pThis->pszCAFile);
301 if (caFile == NULL) {
302 LogMsg(0, RS_RET_CA_CERT_MISSING, LOG_WARNING, "Warning: CA certificate is not set");
303 bHaveCA = 0;
304 } else {
305 dbgprintf("osslCtxInit: OSSL CA file: '%s'\n", caFile);
306 bHaveCA = 1;
307 }
308 crlFile = (char *)((pThis->pszCRLFile == NULL) ? glbl.GetDfltNetstrmDrvrCRLF(runConf) : pThis->pszCRLFile);
309 if (crlFile == NULL) {
310 bHaveCRL = 0;
311 } else {
312 dbgprintf("osslCtxInit: OSSL CRL file: '%s'\n", crlFile);
313 bHaveCRL = 1;
314 }
315 certFile = (char *)((pThis->pszCertFile == NULL) ? glbl.GetDfltNetstrmDrvrCertFile(runConf) : pThis->pszCertFile);
316 if (certFile == NULL) {
317 LogMsg(0, RS_RET_CERT_MISSING, LOG_WARNING, "Warning: Certificate file is not set");
318 bHaveCert = 0;
319 } else {
320 dbgprintf("osslCtxInit: OSSL CERT file: '%s'\n", certFile);
321 bHaveCert = 1;
322 }
323 keyFile = (char *)((pThis->pszKeyFile == NULL) ? glbl.GetDfltNetstrmDrvrKeyFile(runConf) : pThis->pszKeyFile);
324 if (keyFile == NULL) {
325 LogMsg(0, RS_RET_CERTKEY_MISSING, LOG_WARNING, "Warning: Key file is not set");
326 bHaveKey = 0;
327 } else {
328 dbgprintf("osslCtxInit: OSSL KEY file: '%s'\n", keyFile);
329 bHaveKey = 1;
330 }
331 extraCaFiles =
332 (char *)((pThis->pszExtraCAFiles == NULL) ? glbl.GetNetstrmDrvrCAExtraFiles(runConf) : pThis->pszExtraCAFiles);
333 if (extraCaFiles == NULL) {
334 bHaveExtraCAFiles = 0;
335 } else {
336 dbgprintf("osslCtxInit: OSSL EXTRA CA files: '%s'\n", extraCaFiles);
337 bHaveExtraCAFiles = 1;
338 }
339
340 /* Create main CTX Object based on method parameter */
341 if (pThis->ctx != NULL) {
342 SSL_CTX_free(pThis->ctx);
343 pThis->ctx = NULL;
344 }
345 pThis->ctx = SSL_CTX_new(method);
346
347 if (bHaveExtraCAFiles == 1) {
348 while ((extraCaFile = strsep(&extraCaFiles, ","))) {
349 if (SSL_CTX_load_verify_locations(pThis->ctx, extraCaFile, NULL) != 1) {
350 LogError(0, RS_RET_TLS_CERT_ERR,
351 "Error: Extra Certificate file could not be accessed. "
352 "Check at least: 1) file path is correct, 2) file exist, "
353 "3) permissions are correct, 4) file content is correct. "
354 "OpenSSL error info may follow in next messages");
355 net_ossl_lastOpenSSLErrorMsg(NULL, 0, NULL, LOG_ERR, "osslCtxInit", "SSL_CTX_load_verify_locations");
356 ABORT_FINALIZE(RS_RET_TLS_CERT_ERR);
357 }
358 }
359 }
360 if (bHaveCA == 1 && SSL_CTX_load_verify_locations(pThis->ctx, caFile, NULL) != 1) {
361 LogError(0, RS_RET_TLS_CERT_ERR,
362 "Error: CA certificate could not be accessed. "
363 "Check at least: 1) file path is correct, 2) file exist, "
364 "3) permissions are correct, 4) file content is correct. "
365 "OpenSSL error info may follow in next messages");
366 net_ossl_lastOpenSSLErrorMsg(NULL, 0, NULL, LOG_ERR, "osslCtxInit", "SSL_CTX_load_verify_locations");
367 ABORT_FINALIZE(RS_RET_TLS_CERT_ERR);
368 }
369 if (bHaveCRL == 1) {
370 #if OPENSSL_VERSION_NUMBER >= 0x30000000L && !defined(LIBRESSL_VERSION_NUMBER)
371 // Get X509_STORE reference
372 X509_STORE *store = SSL_CTX_get_cert_store(pThis->ctx);
373 if (!X509_STORE_load_file(store, crlFile)) {
374 LogError(0, RS_RET_CRL_INVALID,
375 "Error: CRL could not be accessed. "
376 "Check at least: 1) file path is correct, 2) file exist, "
377 "3) permissions are correct, 4) file content is correct. "
378 "OpenSSL error info may follow in next messages");
379 net_ossl_lastOpenSSLErrorMsg(NULL, 0, NULL, LOG_ERR, "osslCtxInit", "X509_STORE_load_file");
380 ABORT_FINALIZE(RS_RET_CRL_INVALID);
381 }
382 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK);
383 #else
384 #if OPENSSL_VERSION_NUMBER >= 0x10002000L
385 // Get X509_STORE reference
386 X509_STORE *store = SSL_CTX_get_cert_store(pThis->ctx);
387 // Load the CRL PEM file
388 FILE *fp = fopen(crlFile, "r");
389 if (fp == NULL) {
390 LogError(0, RS_RET_CRL_MISSING,
391 "Error: CRL could not be accessed. "
392 "Check at least: 1) file path is correct, 2) file exist, "
393 "3) permissions are correct, 4) file content is correct. "
394 "OpenSSL error info may follow in next messages");
395 net_ossl_lastOpenSSLErrorMsg(NULL, 0, NULL, LOG_ERR, "osslCtxInit", "fopen");
396 ABORT_FINALIZE(RS_RET_CRL_MISSING);
397 }
398 X509_CRL *crl = PEM_read_X509_CRL(fp, NULL, NULL, NULL);
399 fclose(fp);
400 if (crl == NULL) {
401 LogError(0, RS_RET_CRL_INVALID,
402 "Error: Unable to read CRL."
403 "OpenSSL error info may follow in next messages");
404 net_ossl_lastOpenSSLErrorMsg(NULL, 0, NULL, LOG_ERR, "osslCtxInit", "PEM_read_X509_CRL");
405 ABORT_FINALIZE(RS_RET_CRL_INVALID);
406 }
407 // Add the CRL to the X509_STORE
408 if (!X509_STORE_add_crl(store, crl)) {
409 LogError(0, RS_RET_CRL_INVALID,
410 "Error: Unable to add CRL to store."
411 "OpenSSL error info may follow in next messages");
412 net_ossl_lastOpenSSLErrorMsg(NULL, 0, NULL, LOG_ERR, "osslCtxInit", "X509_STORE_add_crl");
413 X509_CRL_free(crl);
414 ABORT_FINALIZE(RS_RET_CRL_INVALID);
415 }
416 // Set the X509_STORE to the SSL_CTX
417 // SSL_CTX_set_cert_store(pThis->ctx, store);
418 // Enable CRL checking
419 X509_VERIFY_PARAM *param = X509_VERIFY_PARAM_new();
420 X509_VERIFY_PARAM_set_flags(param, X509_V_FLAG_CRL_CHECK);
421 SSL_CTX_set1_param(pThis->ctx, param);
422 X509_VERIFY_PARAM_free(param);
423 #else
424 LogError(0, RS_RET_SYS_ERR,
425 "Warning: TLS library does not support X509_STORE_load_file"
426 "(requires OpenSSL 3.x or higher). Cannot use Certificate revocation list (CRL) '%s'.",
427 crlFile);
428 #endif
429 #endif
430 }
431 if (bHaveCert == 1 && SSL_CTX_use_certificate_chain_file(pThis->ctx, certFile) != 1) {
432 LogError(0, RS_RET_TLS_CERT_ERR,
433 "Error: Certificate file could not be accessed. "
434 "Check at least: 1) file path is correct, 2) file exist, "
435 "3) permissions are correct, 4) file content is correct. "
436 "OpenSSL error info may follow in next messages");
437 net_ossl_lastOpenSSLErrorMsg(NULL, 0, NULL, LOG_ERR, "osslCtxInit", "SSL_CTX_use_certificate_chain_file");
438 ABORT_FINALIZE(RS_RET_TLS_CERT_ERR);
439 }
440 if (bHaveKey == 1 && SSL_CTX_use_PrivateKey_file(pThis->ctx, keyFile, SSL_FILETYPE_PEM) != 1) {
441 LogError(0, RS_RET_TLS_KEY_ERR,
442 "Error: Key could not be accessed. "
443 "Check at least: 1) file path is correct, 2) file exist, "
444 "3) permissions are correct, 4) file content is correct. "
445 "OpenSSL error info may follow in next messages");
446 net_ossl_lastOpenSSLErrorMsg(NULL, 0, NULL, LOG_ERR, "osslCtxInit", "SSL_CTX_use_PrivateKey_file");
447 ABORT_FINALIZE(RS_RET_TLS_KEY_ERR);
448 }
449
450 /* Set CTX Options */
451 SSL_CTX_set_options(pThis->ctx, SSL_OP_NO_SSLv2); /* Disable insecure SSLv2 Protocol */
452 SSL_CTX_set_options(pThis->ctx, SSL_OP_NO_SSLv3); /* Disable insecure SSLv3 Protocol */
453 SSL_CTX_sess_set_cache_size(pThis->ctx, 1024); /* TODO: make configurable? */
454
455 /* Set default VERIFY Options for OpenSSL CTX - and CALLBACK */
456 if (pThis->authMode == OSSL_AUTH_CERTANON) {
457 dbgprintf("osslCtxInit: SSL_VERIFY_NONE\n");
458 net_ossl_set_ctx_verify_callback(pThis->ctx, SSL_VERIFY_NONE);
459 } else {
460 dbgprintf("osslCtxInit: SSL_VERIFY_PEER\n");
461 net_ossl_set_ctx_verify_callback(pThis->ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT);
462 }
463
464 SSL_CTX_set_timeout(pThis->ctx, 30); /* Default Session Timeout, TODO: Make configureable */
465 SSL_CTX_set_mode(pThis->ctx, SSL_MODE_AUTO_RETRY);
466
467 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && !defined(ENABLE_WOLFSSL)
468 /* Enable Support for automatic ephemeral/temporary DH parameter selection. */
469 SSL_CTX_set_dh_auto(pThis->ctx, 1);
470 #endif
471
472 #ifndef ENABLE_WOLFSSL
473 #if OPENSSL_VERSION_NUMBER >= 0x10002000L
474 #if OPENSSL_VERSION_NUMBER <= 0x101010FFL
475 /* Enable Support for automatic EC temporary key parameter selection. */
476 SSL_CTX_set_ecdh_auto(pThis->ctx, 1);
477 #else
478 /*
479 * SSL_CTX_set_ecdh_auto and SSL_CTX_set_tmp_ecdh are depreceated in higher
480 * OpenSSL Versions, so we no more need them - see for more:
481 * https://www.openssl.org/docs/manmaster/man3/SSL_CTX_set_ecdh_auto.html
482 */
483 #endif
484 #else
485 dbgprintf(
486 "osslCtxInit: openssl to old, cannot use SSL_CTX_set_ecdh_auto."
487 "Using SSL_CTX_set_tmp_ecdh with NID_X9_62_prime256v1/() instead.\n");
488 SSL_CTX_set_tmp_ecdh(pThis->ctx, EC_KEY_new_by_curve_name(NID_X9_62_prime256v1));
489 #endif
490 #endif
491 finalize_it:
492 RETiRet;
493 }
494
495 /* Helper function to print usefull OpenSSL errors
496 */
497 void net_ossl_lastOpenSSLErrorMsg(
498 uchar *fromHost, int ret, SSL *ssl, int severity, const char *pszCallSource, const char *pszOsslApi) {
499 unsigned long un_error = 0;
500 int iSSLErr = 0;
501 if (ssl == NULL) {
502 /* Output Error Info*/
503 DBGPRINTF("lastOpenSSLErrorMsg: Error in '%s' with ret=%d\n", pszCallSource, ret);
504 } else {
505 /* if object is set, get error code */
506 iSSLErr = SSL_get_error(ssl, ret);
507 /* Output Debug as well */
508 DBGPRINTF(
509 "lastOpenSSLErrorMsg: %s Error in '%s': '%s(%d)' with ret=%d, errno=%d(%s), sslapi='%s'\n",
510 (iSSLErr == SSL_ERROR_SSL ? "SSL_ERROR_SSL"
511 : (iSSLErr == SSL_ERROR_SYSCALL ? "SSL_ERROR_SYSCALL" : "SSL_ERROR_UNKNOWN")),
512 pszCallSource, ERR_error_string(iSSLErr, NULL), iSSLErr, ret, errno, strerror(errno), pszOsslApi);
513
514 /* Output error message */
515 LogMsg(0, RS_RET_NO_ERRCODE, severity, "%s Error in '%s': '%s(%d)' with ret=%d, errno=%d(%s), sslapi='%s'\n",
516 (iSSLErr == SSL_ERROR_SSL ? "SSL_ERROR_SSL"
517 : (iSSLErr == SSL_ERROR_SYSCALL ? "SSL_ERROR_SYSCALL" : "SSL_ERROR_UNKNOWN")),
518 pszCallSource, ERR_error_string(iSSLErr, NULL), iSSLErr, ret, errno, strerror(errno), pszOsslApi);
519 }
520
521 /* Loop through ERR_get_error */
522 while ((un_error = ERR_get_error()) > 0) {
523 LogMsg(0, RS_RET_NO_ERRCODE, severity, "net_ossl:remote '%s' OpenSSL Error Stack: %s", fromHost,
524 ERR_error_string(un_error, NULL));
525 }
526 }
527
528 #if OPENSSL_VERSION_NUMBER >= 0x10002000L && !defined(LIBRESSL_VERSION_NUMBER) && !defined(ENABLE_WOLFSSL)
529 /* initialize tls config commands in openssl context
530 */
531 rsRetVal net_ossl_apply_tlscgfcmd(net_ossl_t *pThis, uchar *tlscfgcmd) {
532 DEFiRet;
533 char *pCurrentPos;
534 char *pNextPos;
535 char *pszCmd;
536 char *pszValue;
537 int iConfErr;
538
539 if (tlscfgcmd == NULL) {
540 FINALIZE;
541 }
542
543 dbgprintf("net_ossl_apply_tlscgfcmd: Apply tlscfgcmd: '%s'\n", tlscfgcmd);
544
545 /* Set working pointer */
546 pCurrentPos = (char *)tlscfgcmd;
547 if (pCurrentPos != NULL && strlen(pCurrentPos) > 0) {
548 // Create CTX Config Helper
549 SSL_CONF_CTX *cctx;
550 cctx = SSL_CONF_CTX_new();
551 if (pThis->sslState == osslServer) {
552 SSL_CONF_CTX_set_flags(cctx, SSL_CONF_FLAG_SERVER);
553 } else {
554 SSL_CONF_CTX_set_flags(cctx, SSL_CONF_FLAG_CLIENT);
555 }
556 SSL_CONF_CTX_set_flags(cctx, SSL_CONF_FLAG_FILE);
557 SSL_CONF_CTX_set_flags(cctx, SSL_CONF_FLAG_SHOW_ERRORS);
558 SSL_CONF_CTX_set_ssl_ctx(cctx, pThis->ctx);
559
560 do {
561 pNextPos = index(pCurrentPos, '=');
562 if (pNextPos != NULL) {
563 while (*pCurrentPos != '\0' && (*pCurrentPos == ' ' || *pCurrentPos == '\t')) pCurrentPos++;
564 pszCmd = strndup(pCurrentPos, pNextPos - pCurrentPos);
565 pCurrentPos = pNextPos + 1;
566 pNextPos = index(pCurrentPos, '\n');
567 pNextPos = (pNextPos == NULL ? index(pCurrentPos, ';') : pNextPos);
568 pszValue = (pNextPos == NULL ? strdup(pCurrentPos) : strndup(pCurrentPos, pNextPos - pCurrentPos));
569 pCurrentPos = (pNextPos == NULL ? NULL : pNextPos + 1);
570
571 /* Add SSL Conf Command */
572 iConfErr = SSL_CONF_cmd(cctx, pszCmd, pszValue);
573 if (iConfErr > 0) {
574 dbgprintf(
575 "net_ossl_apply_tlscgfcmd: Successfully added Command "
576 "'%s':'%s'\n",
577 pszCmd, pszValue);
578 } else {
579 LogError(0, RS_RET_SYS_ERR,
580 "Failed to add OpenSSL command %s:'%s' "
581 "in net_ossl_apply_tlscgfcmd with error '%d'. "
582 "The command or value may be unsupported by "
583 "this native OpenSSL build.",
584 pszCmd, pszValue, iConfErr);
585 }
586
587 free(pszCmd);
588 free(pszValue);
589 } else {
590 /* Abort further parsing */
591 pCurrentPos = NULL;
592 }
593 } while (pCurrentPos != NULL);
594
595 /* Finalize SSL Conf */
596 iConfErr = SSL_CONF_CTX_finish(cctx);
597 if (!iConfErr) {
598 LogError(0, RS_RET_SYS_ERR,
599 "Error: setting openssl command parameters: %s. "
600 "Requested settings may be unavailable on this native "
601 "OpenSSL build. "
602 "OpenSSL error info may follow in next messages",
603 tlscfgcmd);
604 net_ossl_lastOpenSSLErrorMsg(NULL, 0, NULL, LOG_ERR, "net_ossl_apply_tlscgfcmd", "SSL_CONF_CTX_finish");
605 }
606 SSL_CONF_CTX_free(cctx);
607 }
608
609 finalize_it:
610 RETiRet;
611 }
612 #endif // OPENSSL_VERSION_NUMBER >= 0x10002000L
613
614 /* Convert a fingerprint to printable data. The conversion is carried out
615 * according IETF I-D syslog-transport-tls-12. The fingerprint string is
616 * returned in a new cstr object. It is the caller's responsibility to
617 * destruct that object.
618 * rgerhards, 2008-05-08
619 */
620 static rsRetVal net_ossl_genfingerprintstr(uchar *pFingerprint,
621 size_t sizeFingerprint,
622 cstr_t **ppStr,
623 const char *prefix) {
624 cstr_t *pStr = NULL;
625 uchar buf[4];
626 size_t i;
627 DEFiRet;
628
629 CHKiRet(rsCStrConstruct(&pStr));
630 CHKiRet(rsCStrAppendStrWithLen(pStr, (uchar *)prefix, strlen(prefix)));
631 for (i = 0; i < sizeFingerprint; ++i) {
632 snprintf((char *)buf, sizeof(buf), ":%2.2X", pFingerprint[i]);
633 CHKiRet(rsCStrAppendStrWithLen(pStr, buf, 3));
634 }
635 cstrFinalize(pStr);
636
637 *ppStr = pStr;
638
639 finalize_it:
640 if (iRet != RS_RET_OK) {
641 if (pStr != NULL) rsCStrDestruct(&pStr);
642 }
643 RETiRet;
644 }
645
646
647 /* Perform a match on ONE peer name obtained from the certificate. This name
648 * is checked against the set of configured credentials. *pbFoundPositiveMatch is
649 * set to 1 if the ID matches. *pbFoundPositiveMatch must have been initialized
650 * to 0 by the caller (this is a performance enhancement as we expect to be
651 * called multiple times).
652 * TODO: implemet wildcards?
653 * rgerhards, 2008-05-26
654 */
655 static rsRetVal net_ossl_chkonepeername(net_ossl_t *pThis,
656 X509 *certpeer,
657 uchar *pszPeerID,
658 int *pbFoundPositiveMatch) {
659 permittedPeers_t *pPeer;
660 #if OPENSSL_VERSION_NUMBER >= 0x10002000L
661 int osslRet;
662 unsigned int x509flags = 0;
663 #endif
664 char *x509name = NULL;
665 DEFiRet;
666
667 if (certpeer == NULL) {
668 ABORT_FINALIZE(RS_RET_TLS_NO_CERT);
669 }
670
671 ISOBJ_TYPE_assert(pThis, net_ossl);
672 assert(pszPeerID != NULL);
673 assert(pbFoundPositiveMatch != NULL);
674
675 /* Obtain Namex509 name from subject */
676 x509name = X509_NAME_oneline(RSYSLOG_X509_NAME_oneline(certpeer), NULL, 0);
677
678 if (pThis->pPermPeers) { /* do we have configured peer IDs? */
679 pPeer = pThis->pPermPeers;
680 while (pPeer != NULL) {
681 CHKiRet(net.PermittedPeerWildcardMatch(pPeer, pszPeerID, pbFoundPositiveMatch));
682 if (*pbFoundPositiveMatch) break;
683
684 #if OPENSSL_VERSION_NUMBER >= 0x10002000L
685 /* if we did not succeed so far, try ossl X509_check_host
686 * ( Includes check against SubjectAlternativeName )
687 * if prioritizeSAN set, only check against SAN
688 */
689 if (pThis->bSANpriority == 1) {
690 #if OPENSSL_VERSION_NUMBER >= 0x10100004L && !defined(LIBRESSL_VERSION_NUMBER)
691 x509flags = X509_CHECK_FLAG_NEVER_CHECK_SUBJECT;
692 #else
693 dbgprintf("net_ossl_chkonepeername: PrioritizeSAN not supported before OpenSSL 1.1.0\n");
694 #endif // OPENSSL_VERSION_NUMBER >= 0x10100004L
695 }
696 osslRet = X509_check_host(certpeer, (const char *)pPeer->pszID, strlen((const char *)pPeer->pszID),
697 x509flags, NULL);
698 if (osslRet == 1) {
699 /* Found Peer cert in allowed Peerslist */
700 dbgprintf("net_ossl_chkonepeername: Client ('%s') is allowed (X509_check_host)\n", x509name);
701 *pbFoundPositiveMatch = 1;
702 break;
703 } else if (osslRet < 0) {
704 net_ossl_lastOpenSSLErrorMsg(NULL, osslRet, NULL, LOG_ERR, "net_ossl_chkonepeername",
705 "X509_check_host");
706 ABORT_FINALIZE(RS_RET_NO_ERRCODE);
707 }
708 #endif
709 /* Check next peer */
710 pPeer = pPeer->pNext;
711 }
712 } else {
713 LogMsg(0, RS_RET_TLS_NO_CERT, LOG_WARNING,
714 "net_ossl_chkonepeername: Peername check could not be done: "
715 "no peernames configured.");
716 }
717 finalize_it:
718 if (x509name != NULL) {
719 OPENSSL_free(x509name);
720 }
721
722 RETiRet;
723 }
724
725
726 /* Check the peer's ID in fingerprint auth mode.
727 * rgerhards, 2008-05-22
728 */
729 rsRetVal net_ossl_peerfingerprint(net_ossl_t *pThis, X509 *certpeer, uchar *fromHostIP) {
730 DEFiRet;
731 unsigned int n;
732 uchar fingerprint[20 /*EVP_MAX_MD_SIZE**/];
733 uchar fingerprintSha256[32 /*EVP_MAX_MD_SIZE**/];
734 size_t size;
735 size_t sizeSha256;
736 cstr_t *pstrFingerprint = NULL;
737 cstr_t *pstrFingerprintSha256 = NULL;
738 int bFoundPositiveMatch;
739 permittedPeers_t *pPeer;
740 const EVP_MD *fdig = EVP_sha1();
741 const EVP_MD *fdigSha256 = EVP_sha256();
742
743 ISOBJ_TYPE_assert(pThis, net_ossl);
744
745 if (certpeer == NULL) {
746 ABORT_FINALIZE(RS_RET_TLS_NO_CERT);
747 }
748
749 /* obtain the SHA1 fingerprint */
750 size = sizeof(fingerprint);
751 if (!X509_digest(certpeer, fdig, fingerprint, &n)) {
752 dbgprintf("net_ossl_peerfingerprint: error X509cert is not valid!\n");
753 ABORT_FINALIZE(RS_RET_INVALID_FINGERPRINT);
754 }
755 sizeSha256 = sizeof(fingerprintSha256);
756 if (!X509_digest(certpeer, fdigSha256, fingerprintSha256, &n)) {
757 dbgprintf("net_ossl_peerfingerprint: error X509cert is not valid!\n");
758 ABORT_FINALIZE(RS_RET_INVALID_FINGERPRINT);
759 }
760 CHKiRet(net_ossl_genfingerprintstr(fingerprint, size, &pstrFingerprint, "SHA1"));
761 dbgprintf("net_ossl_peerfingerprint: peer's certificate SHA1 fingerprint: %s\n",
762 cstrGetSzStrNoNULL(pstrFingerprint));
763 CHKiRet(net_ossl_genfingerprintstr(fingerprintSha256, sizeSha256, &pstrFingerprintSha256, "SHA256"));
764 dbgprintf("net_ossl_peerfingerprint: peer's certificate SHA256 fingerprint: %s\n",
765 cstrGetSzStrNoNULL(pstrFingerprintSha256));
766
767 /* now search through the permitted peers to see if we can find a permitted one */
768 bFoundPositiveMatch = 0;
769 pPeer = pThis->pPermPeers;
770 while (pPeer != NULL && !bFoundPositiveMatch) {
771 if (!rsCStrSzStrCmp(pstrFingerprint, pPeer->pszID, strlen((char *)pPeer->pszID))) {
772 dbgprintf("net_ossl_peerfingerprint: peer's certificate SHA1 MATCH found: %s\n", pPeer->pszID);
773 bFoundPositiveMatch = 1;
774 } else if (!rsCStrSzStrCmp(pstrFingerprintSha256, pPeer->pszID, strlen((char *)pPeer->pszID))) {
775 dbgprintf("net_ossl_peerfingerprint: peer's certificate SHA256 MATCH found: %s\n", pPeer->pszID);
776 bFoundPositiveMatch = 1;
777 } else {
778 dbgprintf("net_ossl_peerfingerprint: NOMATCH peer certificate: %s\n", pPeer->pszID);
779 pPeer = pPeer->pNext;
780 }
781 }
782
783 if (!bFoundPositiveMatch) {
784 dbgprintf("net_ossl_peerfingerprint: invalid peer fingerprint, not permitted to talk to it\n");
785 if (pThis->bReportAuthErr == 1) {
786 errno = 0;
787 LogMsg(0, RS_RET_INVALID_FINGERPRINT, LOG_WARNING,
788 "net_ossl:TLS session terminated with remote syslog server '%s': "
789 "Fingerprint check failed, not permitted to talk to %s",
790 fromHostIP, cstrGetSzStrNoNULL(pstrFingerprint));
791 pThis->bReportAuthErr = 0;
792 }
793 ABORT_FINALIZE(RS_RET_INVALID_FINGERPRINT);
794 }
795
796 finalize_it:
797 if (pstrFingerprint != NULL) cstrDestruct(&pstrFingerprint);
798 if (pstrFingerprintSha256 != NULL) cstrDestruct(&pstrFingerprintSha256);
799 RETiRet;
800 }
801
802
803 /* Check the peer's ID in name auth mode.
804 */
805 rsRetVal net_ossl_chkpeername(net_ossl_t *pThis, X509 *certpeer, uchar *fromHostIP) {
806 DEFiRet;
807 uchar lnBuf[256];
808 int bFoundPositiveMatch;
809 cstr_t *pStr = NULL;
810 char *x509name = NULL;
811
812 ISOBJ_TYPE_assert(pThis, net_ossl);
813
814 bFoundPositiveMatch = 0;
815 CHKiRet(rsCStrConstruct(&pStr));
816
817 /* Obtain Namex509 name from subject */
818 x509name = X509_NAME_oneline(RSYSLOG_X509_NAME_oneline(certpeer), NULL, 0);
819
820 dbgprintf("net_ossl_chkpeername: checking - peername '%s' on server '%s'\n", x509name, fromHostIP);
821 snprintf((char *)lnBuf, sizeof(lnBuf), "name: %s; ", x509name);
822 CHKiRet(rsCStrAppendStr(pStr, lnBuf));
823 CHKiRet(net_ossl_chkonepeername(pThis, certpeer, (uchar *)x509name, &bFoundPositiveMatch));
824
825 if (!bFoundPositiveMatch) {
826 dbgprintf("net_ossl_chkpeername: invalid peername, not permitted to talk to it\n");
827 if (pThis->bReportAuthErr == 1) {
828 cstrFinalize(pStr);
829 errno = 0;
830 LogMsg(0, RS_RET_INVALID_FINGERPRINT, LOG_WARNING,
831 "net_ossl:TLS session terminated with remote syslog server: "
832 "peer name not authorized, not permitted to talk to %s",
833 cstrGetSzStrNoNULL(pStr));
834 pThis->bReportAuthErr = 0;
835 }
836 ABORT_FINALIZE(RS_RET_INVALID_FINGERPRINT);
837 } else {
838 dbgprintf("net_ossl_chkpeername: permitted to talk!\n");
839 }
840
841 finalize_it:
842 if (x509name != NULL) {
843 OPENSSL_free(x509name);
844 }
845
846 if (pStr != NULL) rsCStrDestruct(&pStr);
847 RETiRet;
848 }
849
850
851 /* check the ID of the remote peer - used for both fingerprint and
852 * name authentication.
853 */
854 X509 *net_ossl_getpeercert(net_ossl_t *pThis, SSL *ssl, uchar *fromHostIP) {
855 X509 *certpeer;
856
857 ISOBJ_TYPE_assert(pThis, net_ossl);
858
859 /* Get peer certificate from SSL */
860 certpeer = SSL_get_peer_certificate(ssl);
861 if (certpeer == NULL) {
862 if (pThis->bReportAuthErr == 1 && 1) {
863 errno = 0;
864 pThis->bReportAuthErr = 0;
865 LogMsg(0, RS_RET_TLS_NO_CERT, LOG_WARNING,
866 "net_ossl:TLS session terminated with remote syslog server '%s': "
867 "Peer check failed, peer did not provide a certificate.",
868 fromHostIP);
869 }
870 }
871 return certpeer;
872 }
873
874
875 /* Verify the validity of the remote peer's certificate.
876 */
877 rsRetVal net_ossl_chkpeercertvalidity(net_ossl_t __attribute__((unused)) * pThis, SSL *ssl, uchar *fromHostIP) {
878 DEFiRet;
879 int iVerErr = X509_V_OK;
880
881 ISOBJ_TYPE_assert(pThis, net_ossl);
882 PermitExpiredCerts *pPermitExpiredCerts = (PermitExpiredCerts *)SSL_get_ex_data(ssl, 1);
883
884 #ifdef ENABLE_WOLFSSL
885 iVerErr = wolfSSL_get_verify_result(ssl);
886 #else
887 iVerErr = SSL_get_verify_result(ssl);
888 #endif
889 if (iVerErr != X509_V_OK) {
890 if (iVerErr == X509_V_ERR_CERT_HAS_EXPIRED) {
891 if (pPermitExpiredCerts != NULL && *pPermitExpiredCerts == OSSL_EXPIRED_DENY) {
892 LogMsg(0, RS_RET_CERT_EXPIRED, LOG_INFO,
893 "net_ossl:TLS session terminated with remote syslog server '%s': "
894 "not permitted to talk to peer, certificate invalid: "
895 "Certificate expired: %s",
896 fromHostIP, X509_verify_cert_error_string(iVerErr));
897 ABORT_FINALIZE(RS_RET_CERT_EXPIRED);
898 } else if (pPermitExpiredCerts != NULL && *pPermitExpiredCerts == OSSL_EXPIRED_WARN) {
899 LogMsg(0, RS_RET_NO_ERRCODE, LOG_WARNING,
900 "net_ossl:CertValidity check - warning talking to peer '%s': "
901 "certificate expired: %s",
902 fromHostIP, X509_verify_cert_error_string(iVerErr));
903 } else {
904 dbgprintf(
905 "net_ossl_chkpeercertvalidity: talking to peer '%s': "
906 "certificate expired: %s\n",
907 fromHostIP, X509_verify_cert_error_string(iVerErr));
908 } /* Else do nothing */
909 } else if (iVerErr == X509_V_ERR_CERT_REVOKED) {
910 LogMsg(0, RS_RET_CERT_REVOKED, LOG_INFO,
911 "net_ossl:TLS session terminated with remote syslog server '%s': "
912 "not permitted to talk to peer, certificate invalid: "
913 "certificate revoked '%s'",
914 fromHostIP, X509_verify_cert_error_string(iVerErr));
915 ABORT_FINALIZE(RS_RET_CERT_EXPIRED);
916 } else {
917 LogMsg(0, RS_RET_CERT_INVALID, LOG_INFO,
918 "net_ossl:TLS session terminated with remote syslog server '%s': "
919 "not permitted to talk to peer, certificate validation failed: %s",
920 fromHostIP, X509_verify_cert_error_string(iVerErr));
921 ABORT_FINALIZE(RS_RET_CERT_INVALID);
922 }
923 } else {
924 dbgprintf("net_ossl_chkpeercertvalidity: client certificate validation success: %s\n",
925 X509_verify_cert_error_string(iVerErr));
926 }
927
928 finalize_it:
929 RETiRet;
930 }
931
932 /*--------------------------------------OCSP Support ------------------------------------------*/
933
934 #ifndef ENABLE_WOLFSSL
935 /* OCSP is not available in WolfSSL builds */
936
937 /* OCSP Response Cache
938 *
939 * Concurrency & Locking:
940 * - Cache is shared across all workers (global state)
941 * - Protected by ocsp_cache_mutex (pthread_mutex_t)
942 * - All cache operations (lookup/store/cleanup) acquire mutex before access
943 * - Cache entries store OCSP responses with expiration times
944 *
945 * Non-blocking I/O:
946 * - Socket operations use non-blocking mode during connect with timeout
947 * - Once connected, sockets use SO_RCVTIMEO/SO_SNDTIMEO for bounded I/O
948 * - Maximum timeout per OCSP responder: OCSP_TIMEOUT (5 seconds)
949 *
950 * Cache Strategy:
951 * - Key: certificate serial number + issuer name hash (SHA-256)
952 * - TTL: Based on OCSP response nextUpdate field, or OCSP_CACHE_DEFAULT_TTL (1 hour)
953 * - Eviction: Prefers expired entries, then FIFO from tail when cache reaches MAX_ENTRIES
954 * - Expired entries removed during lookup to maintain cache efficiency
955 * - Thread-safe: All cache operations protected by mutex
956 */
957 typedef struct ocsp_cache_entry_s {
958 char *cache_key; /* cert serial + issuer hash */
959 int cert_status; /* V_OCSP_CERTSTATUS_* */
960 time_t expires_at; /* when this entry expires */
961 struct ocsp_cache_entry_s *next;
962 } ocsp_cache_entry_t;
963
964 static ocsp_cache_entry_t *ocsp_cache_head = NULL;
965 static int ocsp_cache_count = 0;
966 static pthread_mutex_t ocsp_cache_mutex = PTHREAD_MUTEX_INITIALIZER;
967
968 static char *ocsp_make_cache_key(X509 *cert, X509 *issuer) {
969 DEFiRet;
970 ASN1_INTEGER *serial = X509_get_serialNumber(cert);
971 unsigned char md[EVP_MAX_MD_SIZE];
972 unsigned int md_len = 0;
973 unsigned char key_md[EVP_MAX_MD_SIZE];
974 unsigned int key_md_len = 0;
975 char *key = NULL;
976 int key_len;
977 BIGNUM *bn = NULL;
978 char *serial_hex = NULL;
979
980 if (!serial || !issuer) ABORT_FINALIZE(RS_RET_ERR);
981
982 /* Hash issuer name for compact key */
983 X509_NAME *issuer_name = X509_get_subject_name(issuer);
984 if (!X509_NAME_digest(issuer_name, EVP_sha256(), md, &md_len)) {
985 ABORT_FINALIZE(RS_RET_ERR);
986 }
987
988 /* Hash issuer public key to avoid collisions across key rollovers */
989 if (!X509_pubkey_digest(issuer, EVP_sha256(), key_md, &key_md_len)) {
990 ABORT_FINALIZE(RS_RET_ERR);
991 }
992
993 /* Format: serial-number:issuer-name-hash:issuer-key-hash */
994 bn = ASN1_INTEGER_to_BN(serial, NULL);
995 if (!bn) ABORT_FINALIZE(RS_RET_ERR);
996
997 serial_hex = BN_bn2hex(bn);
998 if (!serial_hex) ABORT_FINALIZE(RS_RET_ERR);
999
1000 key_len = strlen(serial_hex) + (md_len * 2) + (key_md_len * 2) + 3;
1001 CHKmalloc(key = malloc(key_len));
1002
1003 char *p = key;
1004 int written = snprintf(p, key_len, "%s:", serial_hex);
1005 if (written < 0 || written >= key_len) {
1006 ABORT_FINALIZE(RS_RET_ERR);
1007 }
1008 p += written;
1009 size_t remaining = (size_t)key_len - (size_t)written;
1010 for (unsigned int i = 0; i < md_len; i++) {
1011 if (remaining < 3) {
1012 ABORT_FINALIZE(RS_RET_ERR);
1013 }
1014 written = snprintf(p, remaining, "%02x", md[i]);
1015 if (written != 2) {
1016 ABORT_FINALIZE(RS_RET_ERR);
1017 }
1018 p += written;
1019 remaining -= (size_t)written;
1020 }
1021 if (remaining < 2) {
1022 ABORT_FINALIZE(RS_RET_ERR);
1023 }
1024 *p++ = ':';
1025 *p = '\0';
1026 remaining--;
1027 for (unsigned int i = 0; i < key_md_len; i++) {
1028 if (remaining < 3) {
1029 ABORT_FINALIZE(RS_RET_ERR);
1030 }
1031 written = snprintf(p, remaining, "%02x", key_md[i]);
1032 if (written != 2) {
1033 ABORT_FINALIZE(RS_RET_ERR);
1034 }
1035 p += written;
1036 remaining -= (size_t)written;
1037 }
1038
1039 finalize_it:
1040 if (iRet != RS_RET_OK) {
1041 free(key);
1042 key = NULL;
1043 }
1044 if (bn) BN_free(bn);
1045 if (serial_hex) OPENSSL_free(serial_hex);
1046 return key;
1047 }
1048
1049 static int ocsp_cache_lookup(const char *cache_key, int *cert_status) {
1050 int found = 0;
1051 time_t now = time(NULL);
1052
1053 pthread_mutex_lock(&ocsp_cache_mutex);
1054
1055 ocsp_cache_entry_t **pp = &ocsp_cache_head;
1056 while (*pp) {
1057 ocsp_cache_entry_t *entry = *pp;
1058 if (strcmp(entry->cache_key, cache_key) == 0) {
1059 if (entry->expires_at > now) {
1060 *cert_status = entry->cert_status;
1061 found = 1;
1062 dbgprintf("OCSP: Cache hit for key %s, status=%d\n", cache_key, *cert_status);
1063 } else {
1064 /* Remove expired entry */
1065 dbgprintf("OCSP: Removing expired cache entry for key %s\n", cache_key);
1066 *pp = entry->next;
1067 free(entry->cache_key);
1068 free(entry);
1069 ocsp_cache_count--;
1070 }
1071 break;
1072 }
1073 pp = &(*pp)->next;
1074 }
1075
1076 pthread_mutex_unlock(&ocsp_cache_mutex);
1077 return found;
1078 }
1079
1080 static void ocsp_cache_store(const char *cache_key, int cert_status, time_t ttl) {
1081 DEFiRet;
1082 pthread_mutex_lock(&ocsp_cache_mutex);
1083
1084 /* Check if already exists and update */
1085 ocsp_cache_entry_t *entry = ocsp_cache_head;
1086 while (entry) {
1087 if (strcmp(entry->cache_key, cache_key) == 0) {
1088 entry->cert_status = cert_status;
1089 entry->expires_at = time(NULL) + ttl;
1090 dbgprintf("OCSP: Cache updated for key %s\n", cache_key);
1091 pthread_mutex_unlock(&ocsp_cache_mutex);
1092 return;
1093 }
1094 entry = entry->next;
1095 }
1096
1097 /* Try to evict expired entries first before removing valid ones */
1098 if (ocsp_cache_count >= OCSP_CACHE_MAX_ENTRIES) {
1099 time_t now = time(NULL);
1100 ocsp_cache_entry_t **pp = &ocsp_cache_head;
1101 ocsp_cache_entry_t *expired_entry = NULL;
1102
1103 /* Find first expired entry */
1104 while (*pp) {
1105 if ((*pp)->expires_at <= now) {
1106 expired_entry = *pp;
1107 *pp = expired_entry->next;
1108 free(expired_entry->cache_key);
1109 free(expired_entry);
1110 ocsp_cache_count--;
1111 break;
1112 }
1113 pp = &(*pp)->next;
1114 }
1115
1116 /* If no expired entries found, evict from tail (true FIFO) */
1117 if (!expired_entry && ocsp_cache_head) {
1118 pp = &ocsp_cache_head;
1119 while ((*pp)->next) {
1120 pp = &(*pp)->next;
1121 }
1122 ocsp_cache_entry_t *to_remove = *pp;
1123 *pp = NULL;
1124 free(to_remove->cache_key);
1125 free(to_remove);
1126 ocsp_cache_count--;
1127 }
1128 }
1129
1130 /* Add new entry */
1131 ocsp_cache_entry_t *new_entry = NULL;
1132 CHKmalloc(new_entry = malloc(sizeof(ocsp_cache_entry_t)));
1133 CHKmalloc(new_entry->cache_key = strdup(cache_key));
1134 new_entry->cert_status = cert_status;
1135 new_entry->expires_at = time(NULL) + ttl;
1136 new_entry->next = ocsp_cache_head;
1137 ocsp_cache_head = new_entry;
1138 ocsp_cache_count++;
1139 dbgprintf("OCSP: Cache stored for key %s, count=%d\n", cache_key, ocsp_cache_count);
1140
1141 finalize_it:
1142 if (iRet == RS_RET_OUT_OF_MEMORY) {
1143 LogError(0, RS_RET_OUT_OF_MEMORY, "OCSP: Failed to allocate cache entry\n");
1144 }
1145 if (iRet != RS_RET_OK) {
1146 if (new_entry) {
1147 free(new_entry->cache_key);
1148 free(new_entry);
1149 }
1150 }
1151 pthread_mutex_unlock(&ocsp_cache_mutex);
1152 }
1153
1154 void ocsp_cache_cleanup(void) {
1155 pthread_mutex_lock(&ocsp_cache_mutex);
1156
1157 ocsp_cache_entry_t *entry = ocsp_cache_head;
1158 while (entry) {
1159 ocsp_cache_entry_t *next = entry->next;
1160 free(entry->cache_key);
1161 free(entry);
1162 entry = next;
1163 }
1164 ocsp_cache_head = NULL;
1165 ocsp_cache_count = 0;
1166
1167 pthread_mutex_unlock(&ocsp_cache_mutex);
1168 }
1169
1170 /*
1171 * CRL is not implemented!
1172 *
1173 * This is just a sanity-check stub, to fail on CRL-only certificates.
1174 * CRL-only certificate means: Certificate CRL DP, but not OCSP/AuthorityInfoAccess information.
1175 *
1176 * Returns:
1177 * 0: if CRL check failed (Error, or Revoked when is_revoked is set)
1178 * 1: if the certificate status is "GOOD"
1179 * 2: if the certificate holds no CRL URL
1180 */
1181 static int crl_check(X509 *current_cert, int *is_revoked) {
1182 int ret = 0;
1183 STACK_OF(DIST_POINT) * crldp;
1184 STACK_OF(OPENSSL_STRING) * ocsp_uris;
1185
1186 /* Reset revoked status. Needs to be set in case CRL gets implemented. */
1187 if (is_revoked) *is_revoked = 0;
1188
1189 crldp = X509_get_ext_d2i(current_cert, NID_crl_distribution_points, NULL, NULL);
1190 ocsp_uris = X509_get1_ocsp(current_cert);
1191 if (crldp && ocsp_uris == NULL) {
1192 LogError(0, RS_RET_NO_ERRCODE,
1193 "CRL support is not implemented. "
1194 "CRL-only certificates can't be validated!\n");
1195 ret = 0; /* abort verification. CRL-only not supported. */
1196 } else if (!crldp) {
1197 ret = 2;
1198 }
1199
1200 if (ocsp_uris) X509_email_free(ocsp_uris);
1201
1202 if (crldp) sk_DIST_POINT_pop_free(crldp, DIST_POINT_free);
1203
1204 return ret;
1205 }
1206
1207 /*
1208 * Find the issuer certificate, which is mandatory to generate
1209 * a OCSP request.
1210 *
1211 * Query first locally configured and trusted certificates (e.g CAs).
1212 *
1213 * Last resort: Use the certificate chain of the peer, to get hold of
1214 * untrusted certificates (e.g. intermediate certificates).
1215 *
1216 * The resulting issuer certificate might be an untrusted certificate,
1217 * which should be used to generate OCSP requests.
1218 */
1219 static X509 *ocsp_find_issuer(X509 *target_cert,
1220 const char *cert_name,
1221 SSL_CTX *ctx,
1222 STACK_OF(X509) * untrusted_peer_certs) {
1223 X509 *issuer = NULL;
1224 X509_STORE *store = SSL_CTX_get_cert_store(ctx);
1225 STACK_OF(X509_OBJECT) * objs;
1226
1227 /* find issuer among local trusted issuers */
1228 if (store != NULL) {
1229 #if OPENSSL_VERSION_NUMBER >= 0x10100000L
1230 objs = X509_STORE_get0_objects(store);
1231 for (int i = 0; i < sk_X509_OBJECT_num(objs); i++) {
1232 X509 *cert = X509_OBJECT_get0_X509(sk_X509_OBJECT_value(objs, i));
1233 if (cert && X509_check_issued(cert, target_cert) == X509_V_OK) {
1234 issuer = cert;
1235 break;
1236 }
1237 }
1238 #else
1239 /* OpenSSL 1.0.2 compatibility: direct access to store fields */
1240 objs = store->objs;
1241 for (int i = 0; i < sk_X509_OBJECT_num(objs); i++) {
1242 X509_OBJECT *x509obj = sk_X509_OBJECT_value(objs, i);
1243 X509 *cert = x509obj->type == X509_LU_X509 ? x509obj->data.x509 : NULL;
1244 if (cert && X509_check_issued(cert, target_cert) == X509_V_OK) {
1245 issuer = cert;
1246 break;
1247 }
1248 }
1249 #endif
1250 }
1251
1252 if (!issuer) {
1253 /* Look for intermediate certificates in the remote cert-chain */
1254 for (int i = 0; i < sk_X509_num(untrusted_peer_certs); i++) {
1255 X509 *cert = sk_X509_value(untrusted_peer_certs, i);
1256 if (X509_check_issued(cert, target_cert) == X509_V_OK) {
1257 issuer = cert;
1258 break;
1259 }
1260 }
1261 }
1262
1263 /* No issuer, no revocation check possible */
1264 if (!issuer) {
1265 LogError(0, RS_RET_NO_ERRCODE, "OCSP: Could not find any issuer for: \"%s\"\n", cert_name);
1266 }
1267
1268 return issuer;
1269 }
1270
1271 static const char *ocsp_get_response_status_err(int c) {
1272 switch (c) {
1273 case OCSP_RESPONSE_STATUS_SUCCESSFUL:
1274 return "Successful";
1275 case OCSP_RESPONSE_STATUS_MALFORMEDREQUEST:
1276 return "Malformed request";
1277 case OCSP_RESPONSE_STATUS_INTERNALERROR:
1278 return "Internal error in OCSP responder";
1279 case OCSP_RESPONSE_STATUS_TRYLATER:
1280 return "Try again later";
1281 case OCSP_RESPONSE_STATUS_SIGREQUIRED:
1282 return "Must sign the request";
1283 case OCSP_RESPONSE_STATUS_UNAUTHORIZED:
1284 return "Request unauthorized";
1285 default:
1286 return "Unknown Response Status";
1287 }
1288 }
1289
1290 /*
1291 * Returns 1 if the cert status is "GOOD"
1292 * Stores result in cache if successful
1293 */
1294 static int ocsp_check_validate_response_and_cert(OCSP_RESPONSE *rsp,
1295 OCSP_REQUEST *req,
1296 STACK_OF(X509) * untrusted_peer_certs,
1297 OCSP_CERTID *id,
1298 SSL_CTX *ctx,
1299 const char *cert_name,
1300 X509 *cert,
1301 X509 *issuer,
1302 int *is_revoked) {
1303 int s, ret = 0;
1304 long leeway_sec = 300; /* 5 Minutes */
1305 long maxage = -1; /* No maximum age for ThisUpdate response */
1306
1307 int status, reason;
1308 ASN1_GENERALIZEDTIME *rev, *thisupd, *nextupd;
1309 OCSP_BASICRESP *bs = NULL;
1310 X509_STORE *store = SSL_CTX_get_cert_store(ctx);
1311
1312 bs = OCSP_response_get1_basic(rsp);
1313 if (bs == NULL) {
1314 LogError(0, RS_RET_NO_ERRCODE, "Failed to decode the basic OCSP response.\n");
1315 goto err;
1316 }
1317
1318 s = OCSP_check_nonce(req, bs);
1319 if (s == -1) {
1320 LogMsg(0, RS_RET_NO_ERRCODE, LOG_WARNING,
1321 "Warning: no Nonce in OCSP response from peer. "
1322 "(No replay attack protection available)\n");
1323 } else if (s == 0) {
1324 LogError(0, RS_RET_NO_ERRCODE, "Nonce mismatch in OCSP response.\n");
1325 goto err;
1326 }
1327
1328 s = OCSP_basic_verify(bs, untrusted_peer_certs, store, 0);
1329 if (s <= 0) {
1330 LogError(0, RS_RET_NO_ERRCODE, "OCSP response verification failed.\n");
1331 goto err;
1332 }
1333
1334 if (!OCSP_resp_find_status(bs, id, &status, &reason, &rev, &thisupd, &nextupd)) {
1335 LogError(0, RS_RET_NO_ERRCODE, "Failed to get OCSP response status for: %s\n", cert_name);
1336 goto err;
1337 }
1338
1339 s = OCSP_check_validity(thisupd, nextupd, leeway_sec, maxage);
1340 if (s == 0) {
1341 LogError(0, RS_RET_NO_ERRCODE, "OCSP response is not valid (either expired or not yet valid).\n");
1342 goto err;
1343 }
1344
1345 /* Check certificate status */
1346 switch (status) {
1347 case V_OCSP_CERTSTATUS_GOOD:
1348 dbgprintf("OCSP: Certificate status is GOOD for: %s\n", cert_name);
1349 ret = 1;
1350 break;
1351 case V_OCSP_CERTSTATUS_REVOKED:
1352 LogMsg(0, RS_RET_CERT_REVOKED, LOG_ERR, "OCSP: Certificate status is REVOKED for: %s (reason: %s)\n",
1353 cert_name, OCSP_crl_reason_str(reason));
1354 if (is_revoked) *is_revoked = 1;
1355 ret = 0;
1356 break;
1357 case V_OCSP_CERTSTATUS_UNKNOWN:
1358 LogError(0, RS_RET_NO_ERRCODE, "OCSP: Certificate status is UNKNOWN for: %s\n", cert_name);
1359 ret = 0;
1360 break;
1361 default:
1362 LogError(0, RS_RET_NO_ERRCODE, "OCSP: Unknown certificate status for: %s\n", cert_name);
1363 ret = 0;
1364 break;
1365 }
1366
1367 /* Store result in cache */
1368 char *cache_key = ocsp_make_cache_key(cert, issuer);
1369 if (cache_key) {
1370 time_t cache_ttl = OCSP_CACHE_DEFAULT_TTL;
1371 /* Use nextUpdate if available for more accurate cache expiry */
1372 if (nextupd) {
1373 /* Use ASN1_TIME_diff() which properly handles UTC times without timezone issues */
1374 int pday, psec;
1375 if (ASN1_TIME_diff(&pday, &psec, NULL, nextupd) == 1) {
1376 /* nextupd is in the future */
1377 time_t seconds_until_expiry = (pday * 86400) + psec;
1378 if (seconds_until_expiry > 0) {
1379 cache_ttl = seconds_until_expiry;
1380 }
1381 } else {
1382 dbgprintf("OCSP: ASN1_TIME_diff() failed, using default TTL\n");
1383 }
1384 }
1385 ocsp_cache_store(cache_key, status, cache_ttl);
1386 free(cache_key);
1387 }
1388
1389 err:
1390 if (bs) OCSP_BASICRESP_free(bs);
1391
1392 return ret;
1393 }
1394
1395 static BIO *ocsp_connect(const char *host, const char *port, const char *device) {
1396 BIO *bio = NULL;
1397 int sock = -1;
1398 struct addrinfo hints, *res = NULL, *rp;
1399 int s;
1400 int flags;
1401
1402 memset(&hints, 0, sizeof(hints));
1403 hints.ai_family = AF_UNSPEC;
1404 hints.ai_socktype = SOCK_STREAM;
1405
1406 /* TODO: DNS resolution is blocking with no timeout. A malicious certificate
1407 * with OCSP responder URLs pointing to slow/unresponsive DNS names can cause
1408 * the TLS handshake to block indefinitely. This is called from the TLS verify
1409 * callback. Consider using async DNS resolution or making OCSP optional.
1410 */
1411 s = getaddrinfo(host, port, &hints, &res);
1412 if (s != 0) {
1413 LogError(0, RS_RET_NO_ERRCODE, "OCSP: getaddrinfo failed for %s:%s: %s\n", host, port, gai_strerror(s));
1414 goto err;
1415 }
1416
1417 for (rp = res; rp != NULL; rp = rp->ai_next) {
1418 sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
1419 if (sock == -1) continue;
1420
1421 if (device && *device) {
1422 #ifdef SO_BINDTODEVICE
1423 if (setsockopt(sock, SOL_SOCKET, SO_BINDTODEVICE, device, strlen(device)) < 0) {
1424 LogError(errno, RS_RET_NO_ERRCODE, "OCSP: Failed to bind socket to device %s\n", device);
1425 close(sock);
1426 sock = -1;
1427 continue;
1428 }
1429 #else
1430 LogMsg(0, RS_RET_NO_ERRCODE, LOG_WARNING,
1431 "OCSP: SO_BINDTODEVICE not supported, ignoring device parameter\n");
1432 #endif
1433 }
1434
1435 /* Set socket to non-blocking for timeout support */
1436 flags = fcntl(sock, F_GETFL, 0);
1437 if (flags != -1) {
1438 fcntl(sock, F_SETFL, flags | O_NONBLOCK);
1439 }
1440
1441 if (connect(sock, rp->ai_addr, rp->ai_addrlen) == 0) {
1442 break; /* Success */
1443 }
1444
1445 if (errno == EINPROGRESS) {
1446 fd_set wfds;
1447 struct timeval tv;
1448 FD_ZERO(&wfds);
1449 FD_SET(sock, &wfds);
1450 tv.tv_sec = OCSP_TIMEOUT;
1451 tv.tv_usec = 0;
1452
1453 s = select(sock + 1, NULL, &wfds, NULL, &tv);
1454 if (s > 0) {
1455 int error = 0;
1456 socklen_t len = sizeof(error);
1457 if (getsockopt(sock, SOL_SOCKET, SO_ERROR, &error, &len) == 0 && error == 0) {
1458 break; /* Success */
1459 }
1460 }
1461 }
1462
1463 close(sock);
1464 sock = -1;
1465 }
1466
1467 if (sock == -1 || rp == NULL) {
1468 LogError(0, RS_RET_NO_ERRCODE, "OCSP: Failed to connect to %s:%s\n", host, port);
1469 goto err;
1470 }
1471
1472 /* Set socket back to blocking mode with read/write timeout */
1473 flags = fcntl(sock, F_GETFL, 0);
1474 if (flags != -1) {
1475 fcntl(sock, F_SETFL, flags & ~O_NONBLOCK);
1476 }
1477
1478 /* Set socket read and write timeouts to prevent indefinite blocking during OCSP I/O */
1479 struct timeval timeout;
1480 timeout.tv_sec = OCSP_TIMEOUT;
1481 timeout.tv_usec = 0;
1482
1483 if (setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)) < 0) {
1484 LogMsg(0, RS_RET_NO_ERRCODE, LOG_WARNING,
1485 "OCSP: Failed to set socket read timeout (errno %d), continuing without timeout\n", errno);
1486 }
1487
1488 if (setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(timeout)) < 0) {
1489 LogMsg(0, RS_RET_NO_ERRCODE, LOG_WARNING,
1490 "OCSP: Failed to set socket write timeout (errno %d), continuing without timeout\n", errno);
1491 }
1492
1493 bio = BIO_new_socket(sock, BIO_CLOSE);
1494 if (!bio) {
1495 LogError(0, RS_RET_NO_ERRCODE, "OCSP: Failed to create BIO\n");
1496 close(sock);
1497 goto err;
1498 }
1499
1500 err:
1501 if (res) freeaddrinfo(res);
1502
1503 return bio;
1504 }
1505
1506 static OCSP_RESPONSE *ocsp_send_and_receive(BIO *bio, const char *host, const char *path, OCSP_REQUEST *req) {
1507 OCSP_RESPONSE *rsp = NULL;
1508 char *req_data = NULL;
1509 int req_len;
1510 int rv;
1511
1512 /* Encode OCSP request */
1513 req_len = i2d_OCSP_REQUEST(req, (unsigned char **)&req_data);
1514 if (req_len <= 0) {
1515 LogError(0, RS_RET_NO_ERRCODE, "OCSP: Failed to encode OCSP request\n");
1516 goto err;
1517 }
1518
1519 /* Send HTTP POST request */
1520 rv = BIO_printf(bio,
1521 "POST %s HTTP/1.0\r\n"
1522 "Host: %s\r\n"
1523 "Content-Type: application/ocsp-request\r\n"
1524 "Content-Length: %d\r\n"
1525 "\r\n",
1526 path, host, req_len);
1527
1528 if (rv <= 0) {
1529 LogError(0, RS_RET_NO_ERRCODE, "OCSP: Failed to send HTTP header\n");
1530 goto err;
1531 }
1532
1533 /* Send request data */
1534 if (BIO_write(bio, req_data, req_len) != req_len) {
1535 LogError(0, RS_RET_NO_ERRCODE, "OCSP: Failed to send OCSP request data\n");
1536 goto err;
1537 }
1538
1539 if (BIO_flush(bio) != 1) {
1540 LogError(0, RS_RET_NO_ERRCODE, "OCSP: Failed to flush BIO\n");
1541 goto err;
1542 }
1543
1544 /* Read HTTP response - skip headers */
1545 char buf[1024];
1546 int in_headers = 1;
1547 long content_length = -1;
1548 const long MAX_OCSP_RESPONSE_SIZE = 1024 * 1024; /* 1MB limit */
1549
1550 while (in_headers) {
1551 rv = BIO_gets(bio, buf, sizeof(buf));
1552 if (rv <= 0) {
1553 LogError(0, RS_RET_NO_ERRCODE, "OCSP: Failed to read HTTP response headers\n");
1554 goto err;
1555 }
1556
1557 /* Parse Content-Length header */
1558 if (strncasecmp(buf, "Content-Length:", 15) == 0) {
1559 content_length = atol(buf + 15);
1560 if (content_length > MAX_OCSP_RESPONSE_SIZE) {
1561 LogError(0, RS_RET_NO_ERRCODE,
1562 "OCSP: Response Content-Length (%ld) exceeds maximum allowed size (%ld)\n", content_length,
1563 MAX_OCSP_RESPONSE_SIZE);
1564 goto err;
1565 }
1566 }
1567
1568 /* Empty line marks end of headers */
1569 if (strcmp(buf, "\r\n") == 0 || strcmp(buf, "\n") == 0) {
1570 in_headers = 0;
1571 }
1572 }
1573
1574 /* Read OCSP response with size limit */
1575 if (content_length > 0 && content_length <= MAX_OCSP_RESPONSE_SIZE) {
1576 /* Size is within limits, proceed with reading */
1577 rsp = d2i_OCSP_RESPONSE_bio(bio, NULL);
1578 } else if (content_length == -1) {
1579 /* No Content-Length header - read with caution */
1580 LogMsg(0, RS_RET_NO_ERRCODE, LOG_WARNING,
1581 "OCSP: No Content-Length header in response, reading without size validation\n");
1582 rsp = d2i_OCSP_RESPONSE_bio(bio, NULL);
1583 }
1584
1585 if (!rsp) {
1586 LogError(0, RS_RET_NO_ERRCODE, "OCSP: Failed to parse OCSP response\n");
1587 goto err;
1588 }
1589
1590 err:
1591 if (req_data) OPENSSL_free(req_data);
1592
1593 return rsp;
1594 }
1595
1596 static int ocsp_is_supported_protocol(const char *url) {
1597 return (strncmp(url, "http://", 7) == 0);
1598 }
1599
1600 static int ocsp_request_per_responder(const char *url,
1601 X509 *cert,
1602 X509 *issuer,
1603 STACK_OF(X509) * untrusted_peer_certs,
1604 SSL_CTX *ctx,
1605 const char *device,
1606 int *is_revoked) {
1607 int ret = 0;
1608 char *host = NULL, *port = NULL, *path = NULL;
1609 int use_ssl = 0;
1610 BIO *bio = NULL;
1611 OCSP_REQUEST *req = NULL;
1612 OCSP_RESPONSE *rsp = NULL;
1613 OCSP_CERTID *id = NULL;
1614 char cert_name[256];
1615
1616 X509_NAME_oneline(X509_get_subject_name(cert), cert_name, sizeof(cert_name));
1617
1618 /* Parse URL */
1619 if (!OCSP_parse_url((char *)url, &host, &port, &path, &use_ssl)) {
1620 LogError(0, RS_RET_NO_ERRCODE, "OCSP: Failed to parse URL: %s\n", url);
1621 goto err;
1622 }
1623
1624 /* Only HTTP is supported */
1625 if (use_ssl) {
1626 dbgprintf("OCSP: HTTPS not supported, skipping %s\n", url);
1627 goto err;
1628 }
1629
1630 dbgprintf("OCSP: Connecting to %s:%s%s\n", host, port, path);
1631
1632 /* Connect to OCSP responder */
1633 bio = ocsp_connect(host, port, device);
1634 if (!bio) {
1635 goto err;
1636 }
1637
1638 /* Create OCSP request */
1639 req = OCSP_REQUEST_new();
1640 if (!req) {
1641 LogError(0, RS_RET_NO_ERRCODE, "OCSP: Failed to create OCSP request\n");
1642 goto err;
1643 }
1644
1645 id = OCSP_cert_to_id(NULL, cert, issuer);
1646 if (!id) {
1647 LogError(0, RS_RET_NO_ERRCODE, "OCSP: Failed to create OCSP certificate ID\n");
1648 goto err;
1649 }
1650
1651 if (!OCSP_request_add0_id(req, id)) {
1652 LogError(0, RS_RET_NO_ERRCODE, "OCSP: Failed to add certificate ID to OCSP request\n");
1653 OCSP_CERTID_free(id);
1654 goto err;
1655 }
1656
1657 /* Add nonce extension for replay attack protection */
1658 OCSP_request_add1_nonce(req, NULL, -1);
1659
1660 /* Send request and receive response */
1661 rsp = ocsp_send_and_receive(bio, host, path, req);
1662 if (!rsp) {
1663 goto err;
1664 }
1665
1666 /* Check response status */
1667 int response_status = OCSP_response_status(rsp);
1668 if (response_status != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
1669 LogError(0, RS_RET_NO_ERRCODE, "OCSP: Response status: %s\n", ocsp_get_response_status_err(response_status));
1670 goto err;
1671 }
1672
1673 /* Validate response and check certificate status */
1674 ret = ocsp_check_validate_response_and_cert(rsp, req, untrusted_peer_certs, id, ctx, cert_name, cert, issuer,
1675 is_revoked);
1676
1677 err:
1678 if (rsp) OCSP_RESPONSE_free(rsp);
1679 if (req) OCSP_REQUEST_free(req);
1680 if (bio) BIO_free_all(bio);
1681 if (host) OPENSSL_free(host);
1682 if (port) OPENSSL_free(port);
1683 if (path) OPENSSL_free(path);
1684
1685 return ret;
1686 }
1687
1688 static int ocsp_check(
1689 X509 *current_cert, STACK_OF(X509) * untrusted_peer_certs, SSL_CTX *ctx, const char *device, int *is_revoked) {
1690 int ret = 0;
1691 char cert_name[256];
1692 X509 *issuer = NULL;
1693 STACK_OF(OPENSSL_STRING) *ocsp_responders = NULL;
1694 const char *url = NULL;
1695 int at_least_one_responder = 0;
1696 char *cache_key = NULL;
1697 int cached_status;
1698
1699 X509_NAME_oneline(X509_get_subject_name(current_cert), cert_name, sizeof(cert_name));
1700
1701 /* Reset revoked status */
1702 if (is_revoked) *is_revoked = 0;
1703
1704 /*
1705 * 1. Lookup the issuer cert of the current certificate, required to marshal a OCSP request.
1706 */
1707 if (!(issuer = ocsp_find_issuer(current_cert, cert_name, ctx, untrusted_peer_certs))) goto err;
1708
1709 /*
1710 * 2. Check cache first to avoid network I/O
1711 */
1712 cache_key = ocsp_make_cache_key(current_cert, issuer);
1713 if (cache_key && ocsp_cache_lookup(cache_key, &cached_status)) {
1714 if (cached_status == V_OCSP_CERTSTATUS_GOOD) {
1715 dbgprintf("OCSP: Cache indicates certificate is GOOD for: %s\n", cert_name);
1716 ret = 1;
1717 goto err;
1718 } else if (cached_status == V_OCSP_CERTSTATUS_REVOKED) {
1719 LogMsg(0, RS_RET_CERT_REVOKED, LOG_ERR, "OCSP: Cached status shows certificate is REVOKED for: %s\n",
1720 cert_name);
1721 if (is_revoked) *is_revoked = 1;
1722 goto err;
1723 }
1724 /* UNKNOWN status: fall through to network check */
1725 }
1726
1727 /*
1728 * 3. Sanity check prior generating OCSP request.
1729 *
1730 * - No OCSP URL, no OCSP revocation verification required, skip the current cert.
1731 * - Only HTTP protocol is supported. If no OCSP responder with a supported protocol
1732 * is available, this MUST fail the OCSP verification and abort the TLS handshake.
1733 */
1734 ocsp_responders = X509_get1_ocsp(current_cert);
1735 if (ocsp_responders == NULL) {
1736 ret = 2;
1737 goto err; /* continue with cert path validation */
1738 }
1739
1740 for (int i = 0; i < sk_OPENSSL_STRING_num(ocsp_responders); i++) {
1741 url = sk_OPENSSL_STRING_value(ocsp_responders, i);
1742 if (ocsp_is_supported_protocol(url)) {
1743 at_least_one_responder = 1;
1744 break;
1745 }
1746 }
1747
1748 if (!at_least_one_responder) {
1749 LogError(0, RS_RET_NO_ERRCODE,
1750 "None of the OCSP responders are supported by "
1751 "this implementation:\n");
1752 for (int i = 0; i < sk_OPENSSL_STRING_num(ocsp_responders); i++) {
1753 url = sk_OPENSSL_STRING_value(ocsp_responders, i);
1754 LogError(0, RS_RET_NO_ERRCODE, "\t%s\n", url);
1755 }
1756 goto err;
1757 }
1758
1759 /*
1760 * Try all supported OCSP responders one by one.
1761 *
1762 * One successful OCSP status response is enough. Not all responders
1763 * need to be queried.
1764 */
1765 for (int i = 0; i < sk_OPENSSL_STRING_num(ocsp_responders); i++) {
1766 url = sk_OPENSSL_STRING_value(ocsp_responders, i);
1767 if (ocsp_request_per_responder(url, current_cert, issuer, untrusted_peer_certs, ctx, device, is_revoked)) {
1768 ret = 1;
1769 goto err;
1770 }
1771
1772 /* When revoked don't try other sources/OCSP responders */
1773 if (is_revoked && *is_revoked) goto err;
1774
1775 /* If the status is unknown, try the next available responder */
1776 }
1777
1778 err:
1779 if (ocsp_responders) X509_email_free(ocsp_responders);
1780 if (cache_key) free(cache_key);
1781
1782 return ret;
1783 }
1784
1785 #endif /* !ENABLE_WOLFSSL */
1786
1787 /*--------------------------------------End OCSP Support ------------------------------------------*/
1788
1789 /* Verify Callback for X509 Certificate validation. Force visibility as this function is not called anywhere but
1790 * only used as callback!
1791 */
1792 int net_ossl_verify_callback(int status, X509_STORE_CTX *store) {
1793 char szdbgdata1[256];
1794 char szdbgdata2[256];
1795
1796 dbgprintf("verify_callback: status %d\n", status);
1797
1798 if (status == 0) {
1799 /* Retrieve all needed pointers */
1800 X509 *cert = X509_STORE_CTX_get_current_cert(store);
1801 int depth = X509_STORE_CTX_get_error_depth(store);
1802 SSL *ssl = X509_STORE_CTX_get_ex_data(store, SSL_get_ex_data_X509_STORE_CTX_idx());
1803 int err = X509_STORE_CTX_get_error(store);
1804 int iVerifyMode = SSL_get_verify_mode(ssl);
1805 nsd_t *pNsdTcp = (nsd_t *)SSL_get_ex_data(ssl, 0);
1806 PermitExpiredCerts *pPermitExpiredCerts = (PermitExpiredCerts *)SSL_get_ex_data(ssl, 1);
1807
1808 dbgprintf("verify_callback: Certificate validation failed, Mode (%d)!\n", iVerifyMode);
1809
1810 X509_NAME_oneline(X509_get_issuer_name(cert), szdbgdata1, sizeof(szdbgdata1));
1811 X509_NAME_oneline(RSYSLOG_X509_NAME_oneline(cert), szdbgdata2, sizeof(szdbgdata2));
1812
1813 uchar *fromHost = NULL;
1814 if (pNsdTcp != NULL) {
1815 nsd_ptcp.GetRemoteHName(pNsdTcp, &fromHost);
1816 }
1817
1818 if (iVerifyMode != SSL_VERIFY_NONE) {
1819 /* Handle expired Certificates **/
1820 if (err == X509_V_OK || err == X509_V_ERR_CERT_HAS_EXPIRED) {
1821 if (pPermitExpiredCerts != NULL && *pPermitExpiredCerts == OSSL_EXPIRED_PERMIT) {
1822 dbgprintf(
1823 "verify_callback: EXPIRED cert but PERMITTED at depth: %d \n\t"
1824 "issuer = %s\n\t"
1825 "subject = %s\n\t"
1826 "err %d:%s\n",
1827 depth, szdbgdata1, szdbgdata2, err, X509_verify_cert_error_string(err));
1828
1829 /* Set Status to OK*/
1830 status = 1;
1831 } else if (pPermitExpiredCerts != NULL && *pPermitExpiredCerts == OSSL_EXPIRED_WARN) {
1832 LogMsg(0, RS_RET_CERT_EXPIRED, LOG_WARNING,
1833 "Certificate EXPIRED warning at depth: %d \n\t"
1834 "issuer = %s\n\t"
1835 "subject = %s\n\t"
1836 "err %d:%s peer '%s'",
1837 depth, szdbgdata1, szdbgdata2, err, X509_verify_cert_error_string(err), fromHost);
1838
1839 /* Set Status to OK*/
1840 status = 1;
1841 } else /* also default - if (pPermitExpiredCerts == OSSL_EXPIRED_DENY)*/ {
1842 LogMsg(0, RS_RET_CERT_EXPIRED, LOG_ERR,
1843 "Certificate EXPIRED at depth: %d \n\t"
1844 "issuer = %s\n\t"
1845 "subject = %s\n\t"
1846 "err %d:%s\n\t"
1847 "not permitted to talk to peer '%s', certificate invalid: "
1848 "certificate expired",
1849 depth, szdbgdata1, szdbgdata2, err, X509_verify_cert_error_string(err), fromHost);
1850 }
1851 } else if (err == X509_V_ERR_CERT_REVOKED) {
1852 LogMsg(0, RS_RET_CERT_REVOKED, LOG_ERR,
1853 "Certificate REVOKED at depth: %d \n\t"
1854 "issuer = %s\n\t"
1855 "subject = %s\n\t"
1856 "err %d:%s\n\t"
1857 "not permitted to talk to peer '%s', certificate invalid: "
1858 "certificate revoked",
1859 depth, szdbgdata1, szdbgdata2, err, X509_verify_cert_error_string(err), fromHost);
1860 } else {
1861 /* all other error codes cause failure */
1862 LogMsg(0, RS_RET_NO_ERRCODE, LOG_ERR,
1863 "Certificate error at depth: %d \n\t"
1864 "issuer = %s\n\t"
1865 "subject = %s\n\t"
1866 "err %d:%s - peer '%s'",
1867 depth, szdbgdata1, szdbgdata2, err, X509_verify_cert_error_string(err), fromHost);
1868 }
1869 } else {
1870 /* do not verify certs in ANON mode, just log into debug */
1871 dbgprintf(
1872 "verify_callback: Certificate validation DISABLED but Error at depth: %d \n\t"
1873 "issuer = %s\n\t"
1874 "subject = %s\n\t"
1875 "err %d:%s\n",
1876 depth, szdbgdata1, szdbgdata2, err, X509_verify_cert_error_string(err));
1877
1878 /* Set Status to OK*/
1879 status = 1;
1880 }
1881 free(fromHost);
1882 }
1883
1884 if (status == 0) return 0; /* Verification failed */
1885
1886 #ifndef ENABLE_WOLFSSL
1887 /* OCSP revocation checking is not available in WolfSSL builds */
1888
1889 /*
1890 * Certificate revocation checks (only if enabled via StreamDriver.TlsRevocationCheck)
1891 */
1892 X509 *cert = X509_STORE_CTX_get_current_cert(store);
1893 SSL *ssl = X509_STORE_CTX_get_ex_data(store, SSL_get_ex_data_X509_STORE_CTX_idx());
1894
1895 /* Check if revocation checking is enabled
1896 * Note: Using index 3 to avoid collision with imdtls which uses index 2
1897 * Index allocation: 0=pTcp, 1=permitExpiredCerts, 2=imdtls instance, 3=revocationCheck
1898 */
1899 int *pTlsRevocationCheck = (int *)SSL_get_ex_data(ssl, 3);
1900 int tlsRevocationCheck = (pTlsRevocationCheck != NULL) ? *pTlsRevocationCheck : 0;
1901
1902 if (tlsRevocationCheck == 0) {
1903 /* Revocation checking is disabled, skip OCSP/CRL checks */
1904 return status;
1905 }
1906
1907 STACK_OF(X509) *untrusted_peer_certs = X509_STORE_CTX_get1_chain(store);
1908 SSL_CTX *ctx = SSL_get_SSL_CTX(ssl);
1909 int ret, is_revoked = 0;
1910 const char *device = NULL;
1911
1912 /* Try to get device name from nsd object if available */
1913 /* Note: device binding is not currently supported in the refactored code */
1914 /* This is left here for future enhancement */
1915
1916 /* 1. OCSP with caching and non-blocking I/O */
1917 /* Note: OCSP checks use non-blocking sockets with OCSP_TIMEOUT (5 sec) per responder.
1918 * Results are cached to minimize network I/O on subsequent TLS handshakes.
1919 * See: https://github.com/rsyslog/rsyslog/issues/6469
1920 */
1921 ret = ocsp_check(cert, untrusted_peer_certs, ctx, device, &is_revoked);
1922 if (ret == 1) {
1923 /* Status is OK */
1924 status = 1;
1925 goto done;
1926 } else if (ret == 2) {
1927 /* No OCSP URL, give CRL a chance */
1928 status = 1;
1929 } else if (is_revoked) {
1930 /* Cert is revoked, fail verification */
1931 status = 0;
1932 goto done;
1933 } else {
1934 /* If OCSP failed, but cert was not revoked, then the Status might be still OK.
1935 * Try alternative sources (e.g. CRL), in compliance with RFC 6960, Chapter 2.2, Page 7-8.
1936 */
1937 status = 0;
1938 }
1939
1940 /* 2. CRL */
1941
1942 /* CRL support is not implemented.
1943 * This stub will fail if the cert holds a CRL Distribution Point. */
1944 ret = crl_check(cert, &is_revoked);
1945 if (ret == 1) {
1946 /* Status is OK */
1947 status = 1;
1948 } else if (ret == 2) {
1949 /* No CRL, keep the existing status */
1950 ;
1951 } else {
1952 /* Cert is revoked, or check failed -> fail verification */
1953 status = 0;
1954 }
1955
1956 done:
1957 if (untrusted_peer_certs) sk_X509_pop_free(untrusted_peer_certs, X509_free);
1958 #endif /* !ENABLE_WOLFSSL */
1959
1960 return status;
1961 }
1962
1963
1964 #ifndef ENABLE_WOLFSSL
1965 #if OPENSSL_VERSION_NUMBER >= 0x30000000L && !defined(LIBRESSL_VERSION_NUMBER)
1966 static long RSYSLOG_BIO_debug_callback_ex(BIO *bio,
1967 int cmd,
1968 const char __attribute__((unused)) * argp,
1969 size_t __attribute__((unused)) len,
1970 int argi,
1971 long __attribute__((unused)) argl,
1972 int ret,
1973 size_t __attribute__((unused)) * processed)
1974 #else
1975 static long RSYSLOG_BIO_debug_callback(
1976 BIO *bio, int cmd, const char __attribute__((unused)) * argp, int argi, long __attribute__((unused)) argl, long ret)
1977 #endif
1978 {
1979 long ret2 = ret;
1980 long r = 1;
1981 if (BIO_CB_RETURN & cmd) r = ret;
1982 dbgprintf("openssl debugmsg: BIO[%p]: ", (void *)bio);
1983 switch (cmd) {
1984 case BIO_CB_FREE:
1985 dbgprintf("Free - %s\n", RSYSLOG_BIO_method_name(bio));
1986 break;
1987 /* Disabled due API changes for OpenSSL 1.1.0+ */
1988 #if OPENSSL_VERSION_NUMBER < 0x10100000L
1989 case BIO_CB_READ:
1990 if (bio->method->type & BIO_TYPE_DESCRIPTOR)
1991 dbgprintf("read(%d,%lu) - %s fd=%d\n", RSYSLOG_BIO_number_read(bio), (unsigned long)argi,
1992 RSYSLOG_BIO_method_name(bio), RSYSLOG_BIO_number_read(bio));
1993 else
1994 dbgprintf("read(%d,%lu) - %s\n", RSYSLOG_BIO_number_read(bio), (unsigned long)argi,
1995 RSYSLOG_BIO_method_name(bio));
1996 break;
1997 case BIO_CB_WRITE:
1998 if (bio->method->type & BIO_TYPE_DESCRIPTOR)
1999 dbgprintf("write(%d,%lu) - %s fd=%d\n", RSYSLOG_BIO_number_written(bio), (unsigned long)argi,
2000 RSYSLOG_BIO_method_name(bio), RSYSLOG_BIO_number_written(bio));
2001 else
2002 dbgprintf("write(%d,%lu) - %s\n", RSYSLOG_BIO_number_written(bio), (unsigned long)argi,
2003 RSYSLOG_BIO_method_name(bio));
2004 break;
2005 #else
2006 case BIO_CB_READ:
2007 dbgprintf("read %s\n", RSYSLOG_BIO_method_name(bio));
2008 break;
2009 case BIO_CB_WRITE:
2010 dbgprintf("write %s\n", RSYSLOG_BIO_method_name(bio));
2011 break;
2012 #endif
2013 case BIO_CB_PUTS:
2014 dbgprintf("puts() - %s\n", RSYSLOG_BIO_method_name(bio));
2015 break;
2016 case BIO_CB_GETS:
2017 dbgprintf("gets(%lu) - %s\n", (unsigned long)argi, RSYSLOG_BIO_method_name(bio));
2018 break;
2019 case BIO_CB_CTRL:
2020 dbgprintf("ctrl(%lu) - %s\n", (unsigned long)argi, RSYSLOG_BIO_method_name(bio));
2021 break;
2022 case BIO_CB_RETURN | BIO_CB_READ:
2023 dbgprintf("read return %ld\n", ret2);
2024 break;
2025 case BIO_CB_RETURN | BIO_CB_WRITE:
2026 dbgprintf("write return %ld\n", ret2);
2027 break;
2028 case BIO_CB_RETURN | BIO_CB_GETS:
2029 dbgprintf("gets return %ld\n", ret2);
2030 break;
2031 case BIO_CB_RETURN | BIO_CB_PUTS:
2032 dbgprintf("puts return %ld\n", ret2);
2033 break;
2034 case BIO_CB_RETURN | BIO_CB_CTRL:
2035 dbgprintf("ctrl return %ld\n", ret2);
2036 break;
2037 default:
2038 dbgprintf("bio callback - unknown type (%d)\n", cmd);
2039 break;
2040 }
2041
2042 return (r);
2043 }
2044 #endif /* !ENABLE_WOLFSSL */
2045
2046 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && !defined(ENABLE_WOLFSSL)
2047 // Requires at least OpenSSL v1.1.1
2048 PRAGMA_DIAGNOSTIC_PUSH
2049 PRAGMA_IGNORE_Wunused_parameter static int net_ossl_generate_cookie(SSL *ssl,
2050 unsigned char *cookie,
2051 unsigned int *cookie_len) {
2052 unsigned char result[EVP_MAX_MD_SIZE];
2053 unsigned int resultlength;
2054 unsigned char *sslHello;
2055 unsigned int length;
2056
2057 sslHello = (unsigned char *)"rsyslog";
2058 length = strlen((char *)sslHello);
2059
2060 // Generate the cookie using SHA256 hash
2061 if (!EVP_Digest(sslHello, length, result, &resultlength, EVP_sha256(), NULL)) {
2062 return 0;
2063 }
2064
2065 memcpy(cookie, result, resultlength);
2066 *cookie_len = resultlength;
2067 dbgprintf("net_ossl_generate_cookie: generate cookie SUCCESS\n");
2068
2069 return 1;
2070 }
2071 PRAGMA_DIAGNOSTIC_POP
2072
2073 static int net_ossl_verify_cookie(SSL *ssl, const unsigned char *cookie, unsigned int cookie_len) {
2074 unsigned char cookie_gen[EVP_MAX_MD_SIZE];
2075 unsigned int cookie_gen_len;
2076
2077 // Generate a cookie using the same method as in net_ossl_generate_cookie
2078 if (!net_ossl_generate_cookie(ssl, cookie_gen, &cookie_gen_len)) {
2079 dbgprintf("net_ossl_verify_cookie: generate cookie FAILED\n");
2080 return 0;
2081 }
2082
2083 // Check if the generated cookie matches the cookie received
2084 if (cookie_len == cookie_gen_len && memcmp(cookie, cookie_gen, cookie_len) == 0) {
2085 dbgprintf("net_ossl_verify_cookie: compare cookie SUCCESS\n");
2086 return 1;
2087 }
2088
2089 dbgprintf("net_ossl_verify_cookie: compare cookie FAILED\n");
2090 return 0;
2091 }
2092
2093 static rsRetVal net_ossl_init_engine(__attribute__((unused)) net_ossl_t *pThis) {
2094 // OpenSSL Engine Support feature relies on an outdated version of OpenSSL and is
2095 // strictly experimental. No support or guarantees are provided. Use at your own risk.
2096 DEFiRet;
2097 #ifndef OPENSSL_NO_ENGINE
2098 const char *engine_id = NULL;
2099 const char *engine_name = NULL;
2100
2101 PRAGMA_DIAGNOSTIC_PUSH
2102 PRAGMA_IGNORE_Wdeprecated_declarations
2103 // Get the default RSA engine
2104 ENGINE *default_engine = ENGINE_get_default_RSA();
2105 if (default_engine) {
2106 engine_id = ENGINE_get_id(default_engine);
2107 engine_name = ENGINE_get_name(default_engine);
2108 DBGPRINTF("net_ossl_init_engine: Default RSA Engine: ID = %s, Name = %s\n", engine_id, engine_name);
2109
2110 // Free the engine reference when done
2111 ENGINE_free(default_engine);
2112 } else {
2113 DBGPRINTF("net_ossl_init_engine: No default RSA Engine set.\n");
2114 }
2115
2116 /* Setting specific Engine */
2117 if (runConf != NULL && glbl.GetDfltOpensslEngine(runConf) != NULL) {
2118 default_engine = ENGINE_by_id((char *)glbl.GetDfltOpensslEngine(runConf));
2119 if (default_engine && ENGINE_init(default_engine)) {
2120 /* engine initialised */
2121 ENGINE_set_default_DSA(default_engine);
2122 ENGINE_set_default_ciphers(default_engine);
2123
2124 /* Switch to Engine */
2125 DBGPRINTF("net_ossl_init_engine: Changed default Engine to %s\n", glbl.GetDfltOpensslEngine(runConf));
2126
2127 /* Release the functional reference from ENGINE_init() */
2128 ENGINE_finish(default_engine);
2129 } else {
2130 LogError(0, RS_RET_VALUE_NOT_SUPPORTED,
2131 "error: ENGINE_init failed to load Engine '%s'"
2132 "ossl netstream driver",
2133 glbl.GetDfltOpensslEngine(runConf));
2134 net_ossl_lastOpenSSLErrorMsg(NULL, 0, NULL, LOG_ERR, "net_ossl_init_engine", "ENGINE_init");
2135 }
2136 // Free the engine reference when done
2137 ENGINE_free(default_engine);
2138 } else {
2139 DBGPRINTF("net_ossl_init_engine: use openssl default Engine");
2140 }
2141 PRAGMA_DIAGNOSTIC_POP
2142 #else
2143 DBGPRINTF("net_ossl_init_engine: OpenSSL compiled without ENGINE support - ENGINE support disabled\n");
2144 #endif /* OPENSSL_NO_ENGINE */
2145
2146 RETiRet;
2147 }
2148
2149
2150 static rsRetVal net_ossl_ctx_init_cookie(net_ossl_t *pThis) {
2151 DEFiRet;
2152 // Set our cookie generation and verification callbacks
2153 SSL_CTX_set_options(pThis->ctx, SSL_OP_COOKIE_EXCHANGE);
2154 SSL_CTX_set_cookie_generate_cb(pThis->ctx, net_ossl_generate_cookie);
2155 SSL_CTX_set_cookie_verify_cb(pThis->ctx, net_ossl_verify_cookie);
2156 RETiRet;
2157 }
2158 #endif // OPENSSL_VERSION_NUMBER >= 0x10100000L
2159
2160 /* ------------------------------ end OpenSSL helpers ------------------------------------------*/
2161
2162 /* ------------------------------ OpenSSL Callback set helpers ---------------------------------*/
2163 void net_ossl_set_ssl_verify_callback(SSL *pSsl, int flags) {
2164 /* Enable certificate valid checking */
2165 SSL_set_verify(pSsl, flags, net_ossl_verify_callback);
2166 }
2167
2168 void net_ossl_set_ctx_verify_callback(SSL_CTX *pCtx, int flags) {
2169 /* Enable certificate valid checking */
2170 SSL_CTX_set_verify(pCtx, flags, net_ossl_verify_callback);
2171 }
2172
2173 void net_ossl_set_bio_callback(BIO *conn) {
2174 #ifndef ENABLE_WOLFSSL
2175 #if OPENSSL_VERSION_NUMBER >= 0x30000000L && !defined(LIBRESSL_VERSION_NUMBER)
2176 BIO_set_callback_ex(conn, RSYSLOG_BIO_debug_callback_ex);
2177 #else
2178 BIO_set_callback(conn, RSYSLOG_BIO_debug_callback);
2179 #endif // OPENSSL_VERSION_NUMBER >= 0x10100000L
2180 #else
2181 (void)conn;
2182 #endif
2183 }
2184 /* ------------------------------ End OpenSSL Callback set helpers -----------------------------*/
2185
2186
2187 /* Standard-Constructor */
2188 BEGINobjConstruct(net_ossl) /* be sure to specify the object type also in END macro! */
2189 DBGPRINTF("net_ossl_construct: [%p]\n", pThis);
2190 pThis->bReportAuthErr = 1;
2191 pThis->bSANpriority = 0;
2192 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && !defined(ENABLE_WOLFSSL)
2193 CHKiRet(net_ossl_init_engine(pThis));
2194 finalize_it:
2195 #endif
2196 ENDobjConstruct(net_ossl)
2197
2198 /* destructor for the net_ossl object */
2199 BEGINobjDestruct(net_ossl) /* be sure to specify the object type also in END and CODESTART macros! */
2200 CODESTARTobjDestruct(net_ossl);
2201 DBGPRINTF("net_ossl_destruct: [%p]\n", pThis);
2202 /* Free SSL obj also if we do not have a session - or are NOT in TLS mode! */
2203 if (pThis->ssl != NULL) {
2204 DBGPRINTF("net_ossl_destruct: [%p] FREE pThis->ssl \n", pThis);
2205 SSL_free(pThis->ssl);
2206 pThis->ssl = NULL;
2207 }
2208 if (pThis->ctx != NULL && !pThis->ctx_is_copy) {
2209 SSL_CTX_free(pThis->ctx);
2210 pThis->ctx = NULL;
2211 }
2212 free((void *)pThis->pszCAFile);
2213 free((void *)pThis->pszCRLFile);
2214 free((void *)pThis->pszKeyFile);
2215 free((void *)pThis->pszCertFile);
2216 free((void *)pThis->pszExtraCAFiles);
2217 ENDobjDestruct(net_ossl)
2218
2219 /* queryInterface function */
2220 BEGINobjQueryInterface(net_ossl)
2221 CODESTARTobjQueryInterface(net_ossl);
2222 DBGPRINTF("netosslQueryInterface\n");
2223 if (pIf->ifVersion != net_osslCURR_IF_VERSION) { /* check for current version, increment on each change */
2224 ABORT_FINALIZE(RS_RET_INTERFACE_NOT_SUPPORTED);
2225 }
2226 pIf->Construct = (rsRetVal(*)(net_ossl_t **))net_osslConstruct;
2227 pIf->Destruct = (rsRetVal(*)(net_ossl_t **))net_osslDestruct;
2228 pIf->osslCtxInit = net_ossl_osslCtxInit;
2229 pIf->osslChkpeername = net_ossl_chkpeername;
2230 pIf->osslPeerfingerprint = net_ossl_peerfingerprint;
2231 pIf->osslGetpeercert = net_ossl_getpeercert;
2232 pIf->osslChkpeercertvalidity = net_ossl_chkpeercertvalidity;
2233 #if OPENSSL_VERSION_NUMBER >= 0x10002000L && !defined(LIBRESSL_VERSION_NUMBER) && !defined(ENABLE_WOLFSSL)
2234 pIf->osslApplyTlscgfcmd = net_ossl_apply_tlscgfcmd;
2235 #endif // OPENSSL_VERSION_NUMBER >= 0x10002000L
2236 pIf->osslSetBioCallback = net_ossl_set_bio_callback;
2237 pIf->osslSetCtxVerifyCallback = net_ossl_set_ctx_verify_callback;
2238 pIf->osslSetSslVerifyCallback = net_ossl_set_ssl_verify_callback;
2239 pIf->osslLastOpenSSLErrorMsg = net_ossl_lastOpenSSLErrorMsg;
2240 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && !defined(ENABLE_WOLFSSL)
2241 pIf->osslCtxInitCookie = net_ossl_ctx_init_cookie;
2242 pIf->osslInitEngine = net_ossl_init_engine;
2243 #endif
2244 finalize_it:
2245 ENDobjQueryInterface(net_ossl)
2246
2247
2248 /* exit our class
2249 */
2250 BEGINObjClassExit(net_ossl, OBJ_IS_CORE_MODULE) /* CHANGE class also in END MACRO! */
2251 CODESTARTObjClassExit(net_ossl);
2252 DBGPRINTF("netosslClassExit\n");
2253 /* release objects we no longer need */
2254 objRelease(nsd_ptcp, LM_NSD_PTCP_FILENAME);
2255 objRelease(net, LM_NET_FILENAME);
2256 objRelease(glbl, CORE_COMPONENT);
2257 /* shut down OpenSSL */
2258 osslGlblExit();
2259 ENDObjClassExit(net_ossl)
2260
2261
2262 /* Initialize the net_ossl class. Must be called as the very first method
2263 * before anything else is called inside this class.
2264 */
2265 BEGINObjClassInit(net_ossl, 1, OBJ_IS_CORE_MODULE) /* class, version */
2266 DBGPRINTF("net_osslClassInit\n");
2267 // request objects we use
2268 CHKiRet(objUse(glbl, CORE_COMPONENT));
2269 CHKiRet(objUse(net, LM_NET_FILENAME));
2270 CHKiRet(objUse(nsd_ptcp, LM_NSD_PTCP_FILENAME));
2271 // Do global TLS init stuff
2272 osslGlblInit();
2273 ENDObjClassInit(net_ossl)
2274
2275 /* --------------- here now comes the plumbing that makes as a library module --------------- */
2276
2277 /* vi:set ai:
2278 */