1 /*
2 ** Zabbix
3 ** Copyright (C) 2001-2021 Zabbix SIA
4 **
5 ** This program is free software; you can redistribute it and/or modify
6 ** it under the terms of the GNU General Public License as published by
7 ** the Free Software Foundation; either version 2 of the License, or
8 ** (at your option) any later version.
9 **
10 ** This program is distributed in the hope that it will be useful,
11 ** but WITHOUT ANY WARRANTY; without even the implied warranty of
12 ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 ** GNU General Public License for more details.
14 **
15 ** You should have received a copy of the GNU General Public License
16 ** along with this program; if not, write to the Free Software
17 ** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 **/
19
20 #include "common.h"
21
22 #if defined(HAVE_POLARSSL) || defined(HAVE_GNUTLS) || defined(HAVE_OPENSSL)
23
24 #include "comms.h"
25 #include "threads.h"
26 #include "log.h"
27 #include "tls.h"
28 #include "tls_tcp.h"
29 #include "tls_tcp_active.h"
30
31 #if defined(HAVE_POLARSSL)
32 # include <polarssl/entropy.h>
33 # include <polarssl/ctr_drbg.h>
34 # include <polarssl/ssl.h>
35 # include <polarssl/error.h>
36 # include <polarssl/debug.h>
37 # include <polarssl/oid.h>
38 # include <polarssl/version.h>
39 #elif defined(HAVE_GNUTLS)
40 # include <gnutls/gnutls.h>
41 # include <gnutls/x509.h>
42 #elif defined(HAVE_OPENSSL)
43 # include <openssl/ssl.h>
44 # include <openssl/err.h>
45 # include <openssl/rand.h>
46 #endif
47
48 /* Currently use only TLS 1.2, which has number 3.3. In 2015 a new standard for TLS 1.3 is expected. */
49 /* Then we might need to support both TLS 1.2 and 1.3 to work with older Zabbix agents. */
50 #if defined(HAVE_POLARSSL)
51 # define ZBX_TLS_MIN_MAJOR_VER SSL_MAJOR_VERSION_3
52 # define ZBX_TLS_MIN_MINOR_VER SSL_MINOR_VERSION_3
53 # define ZBX_TLS_MAX_MAJOR_VER SSL_MAJOR_VERSION_3
54 # define ZBX_TLS_MAX_MINOR_VER SSL_MINOR_VERSION_3
55 # define ZBX_TLS_CIPHERSUITE_CERT 0 /* select only certificate ciphersuites */
56 # define ZBX_TLS_CIPHERSUITE_PSK 1 /* select only pre-shared key ciphersuites */
57 # define ZBX_TLS_CIPHERSUITE_ALL 2 /* select ciphersuites with certificate and PSK */
58 #endif
59
60 #if defined(HAVE_OPENSSL) && OPENSSL_VERSION_NUMBER < 0x1010000fL || defined(LIBRESSL_VERSION_NUMBER)
61 /* for OpenSSL 1.0.1/1.0.2 (before 1.1.0) or LibreSSL */
62
63 /* mutexes for multi-threaded OpenSSL (see "man 3ssl threads" and example in crypto/threads/mttest.c) */
64
65 #ifdef _WINDOWS
66 #include "mutexs.h"
67
68 static zbx_mutex_t *crypto_mutexes = NULL;
69
zbx_openssl_locking_cb(int mode,int n,const char * file,int line)70 static void zbx_openssl_locking_cb(int mode, int n, const char *file, int line)
71 {
72 if (0 != (mode & CRYPTO_LOCK))
73 __zbx_mutex_lock(file, line, *(crypto_mutexes + n));
74 else
75 __zbx_mutex_unlock(file, line, *(crypto_mutexes + n));
76 }
77
zbx_openssl_thread_setup(void)78 static void zbx_openssl_thread_setup(void)
79 {
80 const char *__function_name = "zbx_openssl_thread_setup";
81
82 int i, num_locks;
83
84 num_locks = CRYPTO_num_locks();
85
86 if (NULL == (crypto_mutexes = zbx_malloc(crypto_mutexes, num_locks * sizeof(zbx_mutex_t))))
87 {
88 zabbix_log(LOG_LEVEL_CRIT, "cannot allocate mutexes for OpenSSL library");
89 exit(EXIT_FAILURE);
90 }
91
92 zabbix_log(LOG_LEVEL_DEBUG, "%s() creating %d mutexes", __function_name, num_locks);
93
94 for (i = 0; i < num_locks; i++)
95 {
96 char *error = NULL;
97
98 if (SUCCEED != zbx_mutex_create(crypto_mutexes + i, NULL, &error))
99 {
100 zabbix_log(LOG_LEVEL_CRIT, "cannot create mutex #%d for OpenSSL library: %s", i, error);
101 zbx_free(error);
102 exit(EXIT_FAILURE);
103 }
104 }
105
106 CRYPTO_set_locking_callback((void (*)(int, int, const char *, int))zbx_openssl_locking_cb);
107
108 /* do not register our own threadid_func() callback, use OpenSSL default one */
109 }
110
zbx_openssl_thread_cleanup(void)111 static void zbx_openssl_thread_cleanup(void)
112 {
113 int i, num_locks;
114
115 CRYPTO_set_locking_callback(NULL);
116
117 num_locks = CRYPTO_num_locks();
118
119 for (i = 0; i < num_locks; i++)
120 zbx_mutex_destroy(crypto_mutexes + i);
121
122 zbx_free(crypto_mutexes);
123 }
124 #endif /* _WINDOWS */
125
126 #if !defined(LIBRESSL_VERSION_NUMBER)
127 #define OPENSSL_INIT_LOAD_SSL_STRINGS 0
128 #define OPENSSL_INIT_LOAD_CRYPTO_STRINGS 0
129 #define OPENSSL_VERSION SSLEAY_VERSION
130 #endif
131 #define OpenSSL_version SSLeay_version
132 #define TLS_method TLSv1_2_method
133 #define TLS_client_method TLSv1_2_client_method
134 #define SSL_CTX_get_ciphers(ciphers) ((ciphers)->cipher_list)
135 #if !defined(LIBRESSL_VERSION_NUMBER)
136 #define SSL_CTX_set_min_proto_version(ctx, TLSv) 1
137 #endif
138
zbx_openssl_init_ssl(int opts,void * settings)139 static int zbx_openssl_init_ssl(int opts, void *settings)
140 {
141 #if defined(HAVE_OPENSSL) && OPENSSL_VERSION_NUMBER < 0x1010000fL
142 ZBX_UNUSED(opts);
143 ZBX_UNUSED(settings);
144
145 SSL_load_error_strings();
146 ERR_load_BIO_strings();
147 SSL_library_init();
148 #endif
149 #ifdef _WINDOWS
150 ZBX_UNUSED(opts);
151 ZBX_UNUSED(settings);
152 zbx_openssl_thread_setup();
153 #endif
154 return 1;
155 }
156
OPENSSL_cleanup(void)157 static void OPENSSL_cleanup(void)
158 {
159 RAND_cleanup();
160 ERR_free_strings();
161 #ifdef _WINDOWS
162 zbx_openssl_thread_cleanup();
163 #endif
164 }
165 #endif /* defined(HAVE_OPENSSL) && OPENSSL_VERSION_NUMBER < 0x1010000fL || defined(LIBRESSL_VERSION_NUMBER) */
166
167 #if defined(HAVE_OPENSSL) && OPENSSL_VERSION_NUMBER >= 0x1010000fL && !defined(LIBRESSL_VERSION_NUMBER)
168 /* OpenSSL 1.1.0 or newer, not LibreSSL */
zbx_openssl_init_ssl(int opts,void * settings)169 static int zbx_openssl_init_ssl(int opts, void *settings)
170 {
171 return OPENSSL_init_ssl(opts, settings);
172 }
173 #endif
174
175 struct zbx_tls_context
176 {
177 #if defined(HAVE_POLARSSL)
178 ssl_context *ctx;
179 #elif defined(HAVE_GNUTLS)
180 gnutls_session_t ctx;
181 gnutls_psk_client_credentials_t psk_client_creds;
182 gnutls_psk_server_credentials_t psk_server_creds;
183 #elif defined(HAVE_OPENSSL)
184 SSL *ctx;
185 #endif
186 };
187
188 extern unsigned int configured_tls_connect_mode;
189 extern unsigned int configured_tls_accept_modes;
190
191 extern unsigned char program_type;
192
193 extern int CONFIG_PASSIVE_FORKS;
194 extern int CONFIG_ACTIVE_FORKS;
195
196 extern char *CONFIG_TLS_CONNECT;
197 extern char *CONFIG_TLS_ACCEPT;
198 extern char *CONFIG_TLS_CA_FILE;
199 extern char *CONFIG_TLS_CRL_FILE;
200 extern char *CONFIG_TLS_SERVER_CERT_ISSUER;
201 extern char *CONFIG_TLS_SERVER_CERT_SUBJECT;
202 extern char *CONFIG_TLS_CERT_FILE;
203 extern char *CONFIG_TLS_KEY_FILE;
204 extern char *CONFIG_TLS_PSK_IDENTITY;
205 extern char *CONFIG_TLS_PSK_FILE;
206
207 extern char *CONFIG_TLS_CIPHER_CERT13; /* parameter 'TLSCipherCert13' from server/proxy/agent config file */
208 extern char *CONFIG_TLS_CIPHER_CERT; /* parameter 'TLSCipherCert' from server/proxy/agent config file */
209 extern char *CONFIG_TLS_CIPHER_PSK13; /* parameter 'TLSCipherPSK13' from server/proxy/agent config file */
210 extern char *CONFIG_TLS_CIPHER_PSK; /* parameter 'TLSCipherPSK' from server/proxy/agent config file */
211 extern char *CONFIG_TLS_CIPHER_ALL13; /* parameter 'TLSCipherAll13' from server/proxy/agent config file */
212 extern char *CONFIG_TLS_CIPHER_ALL; /* parameter 'TLSCipherAll' from server/proxy/agent config file */
213 extern char *CONFIG_TLS_CIPHER_CMD13; /* parameter '--tls-cipher13' from sender or zabbix_get command line */
214 extern char *CONFIG_TLS_CIPHER_CMD; /* parameter '--tls-cipher' from sender or zabbix_get command line */
215
216 ZBX_THREAD_LOCAL static char *my_psk_identity = NULL;
217 ZBX_THREAD_LOCAL static size_t my_psk_identity_len = 0;
218 ZBX_THREAD_LOCAL static char *my_psk = NULL;
219 ZBX_THREAD_LOCAL static size_t my_psk_len = 0;
220
221 /* Pointer to DCget_psk_by_identity() initialized at runtime. This is a workaround for linking. */
222 /* Server and proxy link with src/libs/zbxdbcache/dbconfig.o where DCget_psk_by_identity() resides */
223 /* but other components (e.g. agent) do not link dbconfig.o. */
224 size_t (*find_psk_in_cache)(const unsigned char *, unsigned char *, size_t) = NULL;
225
226 #if defined(HAVE_POLARSSL)
227 ZBX_THREAD_LOCAL static x509_crt *ca_cert = NULL;
228 ZBX_THREAD_LOCAL static x509_crl *crl = NULL;
229 ZBX_THREAD_LOCAL static x509_crt *my_cert = NULL;
230 ZBX_THREAD_LOCAL static pk_context *my_priv_key = NULL;
231 ZBX_THREAD_LOCAL static entropy_context *entropy = NULL;
232 ZBX_THREAD_LOCAL static ctr_drbg_context *ctr_drbg = NULL;
233 ZBX_THREAD_LOCAL static char *err_msg = NULL;
234 ZBX_THREAD_LOCAL static int *ciphersuites_cert = NULL;
235 ZBX_THREAD_LOCAL static int *ciphersuites_psk = NULL;
236 ZBX_THREAD_LOCAL static int *ciphersuites_all = NULL;
237 #elif defined(HAVE_GNUTLS)
238 ZBX_THREAD_LOCAL static gnutls_certificate_credentials_t my_cert_creds = NULL;
239 ZBX_THREAD_LOCAL static gnutls_psk_client_credentials_t my_psk_client_creds = NULL;
240 ZBX_THREAD_LOCAL static gnutls_psk_server_credentials_t my_psk_server_creds = NULL;
241 ZBX_THREAD_LOCAL static gnutls_priority_t ciphersuites_cert = NULL;
242 ZBX_THREAD_LOCAL static gnutls_priority_t ciphersuites_psk = NULL;
243 ZBX_THREAD_LOCAL static gnutls_priority_t ciphersuites_all = NULL;
244 static int init_done = 0;
245 #elif defined(HAVE_OPENSSL)
246 ZBX_THREAD_LOCAL static const SSL_METHOD *method = NULL;
247 ZBX_THREAD_LOCAL static SSL_CTX *ctx_cert = NULL;
248 #ifdef HAVE_OPENSSL_WITH_PSK
249 ZBX_THREAD_LOCAL static SSL_CTX *ctx_psk = NULL;
250 ZBX_THREAD_LOCAL static SSL_CTX *ctx_all = NULL;
251 /* variables for passing required PSK identity and PSK info to client callback function */
252 ZBX_THREAD_LOCAL static const char *psk_identity_for_cb = NULL;
253 ZBX_THREAD_LOCAL static size_t psk_identity_len_for_cb = 0;
254 ZBX_THREAD_LOCAL static char *psk_for_cb = NULL;
255 ZBX_THREAD_LOCAL static size_t psk_len_for_cb = 0;
256 #endif
257 static int init_done = 0;
258 #ifdef HAVE_OPENSSL_WITH_PSK
259 /* variables for capturing PSK identity from server callback function */
260 ZBX_THREAD_LOCAL static int incoming_connection_has_psk = 0;
261 ZBX_THREAD_LOCAL static char incoming_connection_psk_id[PSK_MAX_IDENTITY_LEN + 1];
262 #endif
263 /* buffer for messages produced by zbx_openssl_info_cb() */
264 ZBX_THREAD_LOCAL char info_buf[256];
265 #endif
266
267 #if defined(HAVE_POLARSSL)
268 /**********************************************************************************
269 * *
270 * Function: zbx_make_personalization_string *
271 * *
272 * Purpose: provide additional entropy for initialization of crypto library *
273 * *
274 * Comments: *
275 * For more information about why and how to use personalization strings see *
276 * https://polarssl.org/module-level-design-rng *
277 * http://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-90Ar1.pdf *
278 * *
279 **********************************************************************************/
zbx_make_personalization_string(unsigned char pers[64])280 static void zbx_make_personalization_string(unsigned char pers[64])
281 {
282 long int thread_id;
283 zbx_timespec_t ts;
284 sha512_context ctx;
285
286 sha512_init(&ctx);
287 sha512_starts(&ctx, 1); /* use SHA-384 mode */
288
289 thread_id = zbx_get_thread_id();
290 sha512_update(&ctx, (const unsigned char *)&thread_id, sizeof(thread_id));
291
292 zbx_timespec(&ts);
293
294 if (0 != ts.ns)
295 sha512_update(&ctx, (const unsigned char *)&ts.ns, sizeof(ts.ns));
296
297 sha512_finish(&ctx, pers);
298 sha512_free(&ctx);
299 }
300 #endif
301
302 #if defined(HAVE_POLARSSL)
303 /******************************************************************************
304 * *
305 * Function: polarssl_debug_cb *
306 * *
307 * Purpose: write a PolarSSL debug message into Zabbix log *
308 * *
309 * Comments: *
310 * Parameter 'tls_ctx' is not used but cannot be removed because this is *
311 * a callback function, its arguments are defined in PolarSSL. *
312 * *
313 ******************************************************************************/
polarssl_debug_cb(void * tls_ctx,int level,const char * str)314 static void polarssl_debug_cb(void *tls_ctx, int level, const char *str)
315 {
316 char msg[1024]; /* Apparently 1024 bytes is the longest message which can come from PolarSSL 1.3.9 */
317
318 ZBX_UNUSED(tls_ctx);
319
320 /* remove '\n' from the end of debug message */
321 zbx_strlcpy(msg, str, sizeof(msg));
322 zbx_rtrim(msg, "\n");
323 zabbix_log(LOG_LEVEL_TRACE, "PolarSSL debug: level=%d \"%s\"", level, msg);
324 }
325 #elif defined(HAVE_GNUTLS)
326 /******************************************************************************
327 * *
328 * Function: zbx_gnutls_debug_cb *
329 * *
330 * Purpose: write a GnuTLS debug message into Zabbix log *
331 * *
332 * Comments: *
333 * This is a callback function, its arguments are defined in GnuTLS. *
334 * *
335 ******************************************************************************/
zbx_gnutls_debug_cb(int level,const char * str)336 static void zbx_gnutls_debug_cb(int level, const char *str)
337 {
338 char msg[1024];
339
340 /* remove '\n' from the end of debug message */
341 zbx_strlcpy(msg, str, sizeof(msg));
342 zbx_rtrim(msg, "\n");
343 zabbix_log(LOG_LEVEL_TRACE, "GnuTLS debug: level=%d \"%s\"", level, msg);
344 }
345
346 /******************************************************************************
347 * *
348 * Function: zbx_gnutls_audit_cb *
349 * *
350 * Purpose: write a GnuTLS audit message into Zabbix log *
351 * *
352 * Comments: *
353 * This is a callback function, its arguments are defined in GnuTLS. *
354 * *
355 ******************************************************************************/
zbx_gnutls_audit_cb(gnutls_session_t session,const char * str)356 static void zbx_gnutls_audit_cb(gnutls_session_t session, const char *str)
357 {
358 char msg[1024];
359
360 ZBX_UNUSED(session);
361
362 /* remove '\n' from the end of debug message */
363 zbx_strlcpy(msg, str, sizeof(msg));
364 zbx_rtrim(msg, "\n");
365
366 zabbix_log(LOG_LEVEL_WARNING, "GnuTLS audit: \"%s\"", msg);
367 }
368 #endif /* defined(HAVE_GNUTLS) */
369
370 #if defined(HAVE_OPENSSL)
371 /******************************************************************************
372 * *
373 * Function: zbx_openssl_info_cb *
374 * *
375 * Purpose: get state, alert, error information on TLS connection *
376 * *
377 * Comments: *
378 * This is a callback function, its arguments are defined in OpenSSL. *
379 * *
380 ******************************************************************************/
zbx_openssl_info_cb(const SSL * ssl,int where,int ret)381 static void zbx_openssl_info_cb(const SSL *ssl, int where, int ret)
382 {
383 /* There was an idea of using SSL_CB_LOOP and SSL_state_string_long() to write state changes into Zabbix log */
384 /* if logging level is LOG_LEVEL_TRACE. Unfortunately if OpenSSL for security is compiled without SSLv3 */
385 /* (i.e. OPENSSL_NO_SSL3 is defined) then SSL_state_string_long() does not provide descriptions of many */
386 /* states anymore. The idea was dropped but the code is here for debugging hard problems. */
387 #if 0
388 if (0 != (where & SSL_CB_LOOP))
389 {
390 zabbix_log(LOG_LEVEL_TRACE, "OpenSSL debug: state=0x%x \"%s\"", (unsigned int)SSL_state(ssl),
391 SSL_state_string_long(ssl));
392 }
393 #else
394 ZBX_UNUSED(ssl);
395 #endif
396 if (0 != (where & SSL_CB_ALERT)) /* alert sent or received */
397 {
398 const char *handshake, *direction, *rw;
399
400 if (0 != (where & SSL_CB_EXIT))
401 handshake = " handshake";
402 else
403 handshake = "";
404
405 if (0 != (where & SSL_ST_CONNECT))
406 direction = " connect";
407 else if (0 != (where & SSL_ST_ACCEPT))
408 direction = " accept";
409 else
410 direction = "";
411
412 if (0 != (where & SSL_CB_READ))
413 rw = " read";
414 else if (0 != (where & SSL_CB_WRITE))
415 rw = " write";
416 else
417 rw = "";
418
419 zbx_snprintf(info_buf, sizeof(info_buf), ": TLS%s%s%s %s alert \"%s\"", handshake, direction, rw,
420 SSL_alert_type_string_long(ret), SSL_alert_desc_string_long(ret));
421 }
422 }
423 #endif
424
425 /******************************************************************************
426 * *
427 * Function: zbx_tls_error_msg *
428 * *
429 * Purpose: compose a TLS error message *
430 * *
431 ******************************************************************************/
432 #if defined(HAVE_POLARSSL)
zbx_tls_error_msg(int error_code,const char * msg,char ** error)433 static void zbx_tls_error_msg(int error_code, const char *msg, char **error)
434 {
435 char err[128]; /* 128 bytes are enough for PolarSSL error messages */
436
437 polarssl_strerror(error_code, err, sizeof(err));
438 *error = zbx_dsprintf(*error, "%s%s", msg, err);
439 }
440 #elif defined(HAVE_OPENSSL)
zbx_tls_error_msg(char ** error,size_t * error_alloc,size_t * error_offset)441 void zbx_tls_error_msg(char **error, size_t *error_alloc, size_t *error_offset)
442 {
443 unsigned long error_code;
444 const char *file, *data;
445 int line, flags;
446 char err[1024];
447
448 /* concatenate all error messages in the queue into one string */
449
450 while (0 != (error_code = ERR_get_error_line_data(&file, &line, &data, &flags)))
451 {
452 ERR_error_string_n(error_code, err, sizeof(err));
453
454 zbx_snprintf_alloc(error, error_alloc, error_offset, " file %s line %d: %s", file, line, err);
455
456 if (NULL != data && 0 != (flags & ERR_TXT_STRING))
457 zbx_snprintf_alloc(error, error_alloc, error_offset, ": %s", data);
458 }
459 }
460 #endif
461
462 #if defined(HAVE_POLARSSL)
463 /******************************************************************************
464 * *
465 * Function: zbx_tls_cert_error_msg *
466 * *
467 * Purpose: *
468 * compose a certificate validation error message by decoding PolarSSL *
469 * ssl_get_verify_result() return value *
470 * *
471 * Parameters: *
472 * flags - [IN] result returned by PolarSSL ssl_get_verify_result() *
473 * error - [OUT] dynamically allocated memory with error message *
474 * *
475 ******************************************************************************/
zbx_tls_cert_error_msg(unsigned int flags,char ** error)476 static void zbx_tls_cert_error_msg(unsigned int flags, char **error)
477 {
478 const unsigned int bits[] = { BADCERT_EXPIRED, BADCERT_REVOKED, BADCERT_CN_MISMATCH,
479 BADCERT_NOT_TRUSTED, BADCRL_NOT_TRUSTED,
480 BADCRL_EXPIRED, BADCERT_MISSING, BADCERT_SKIP_VERIFY, BADCERT_OTHER,
481 BADCERT_FUTURE, BADCRL_FUTURE,
482 #if 0x01030B00 <= POLARSSL_VERSION_NUMBER /* 1.3.11 */
483 BADCERT_KEY_USAGE, BADCERT_EXT_KEY_USAGE, BADCERT_NS_CERT_TYPE,
484 #endif
485 0 };
486 const char *msgs[] = { "expired", "revoked", "Common Name mismatch",
487 "self-signed or not signed by trusted CA", "CRL not signed by trusted CA",
488 "CRL expired", "certificate missing", "verification skipped", "other reason",
489 "validity starts in future", "CRL validity starts in future"
490 #if 0x01030B00 <= POLARSSL_VERSION_NUMBER /* 1.3.11 */
491 , "actual use does not match keyUsage extension",
492 "actual use does not match extendedKeyUsage extension",
493 "actual use does not match nsCertType extension"
494 #endif
495 };
496 int i = 0, k = 0;
497
498 *error = zbx_strdup(*error, "invalid peer certificate: ");
499
500 while (0 != flags && 0 != bits[i])
501 {
502 if (0 != (flags & bits[i]))
503 {
504 flags &= ~bits[i]; /* reset the checked bit to detect no-more-set-bits without checking */
505 /* every bit */
506 if (0 != k)
507 *error = zbx_strdcat(*error, ", ");
508 else
509 k = 1;
510
511 *error = zbx_strdcat(*error, msgs[i]);
512 }
513
514 i++;
515 }
516 }
517 #endif
518
519 /******************************************************************************
520 * *
521 * Function: zbx_tls_version *
522 * *
523 * Purpose: print tls library version on stdout by application request with *
524 * parameter '-V' *
525 * *
526 ******************************************************************************/
zbx_tls_version(void)527 void zbx_tls_version(void)
528 {
529 #if defined(HAVE_POLARSSL)
530 printf("Compiled with %s\n", POLARSSL_VERSION_STRING_FULL);
531 #elif defined(HAVE_GNUTLS)
532 printf("Compiled with GnuTLS %s\nRunning with GnuTLS %s\n", GNUTLS_VERSION, gnutls_check_version(NULL));
533 #elif defined(HAVE_OPENSSL)
534 printf("This product includes software developed by the OpenSSL Project\n"
535 "for use in the OpenSSL Toolkit (http://www.openssl.org/).\n\n");
536 printf("Compiled with %s\nRunning with %s\n", OPENSSL_VERSION_TEXT, OpenSSL_version(OPENSSL_VERSION));
537 #endif
538 }
539
540 /******************************************************************************
541 * *
542 * Function: zbx_tls_parameter_name *
543 * *
544 * Purpose: *
545 * return the name of a configuration file or command line parameter that *
546 * the value of the given parameter comes from *
547 * *
548 * Parameters: *
549 * type - [IN] type of parameter (file or command line) *
550 * param - [IN] address of the global parameter variable *
551 * *
552 ******************************************************************************/
553 #define ZBX_TLS_PARAMETER_CONFIG_FILE 0
554 #define ZBX_TLS_PARAMETER_COMMAND_LINE 1
zbx_tls_parameter_name(int type,char ** param)555 static const char *zbx_tls_parameter_name(int type, char **param)
556 {
557 if (&CONFIG_TLS_CONNECT == param)
558 return ZBX_TLS_PARAMETER_CONFIG_FILE == type ? "TLSConnect" : "--tls-connect";
559
560 if (&CONFIG_TLS_ACCEPT == param)
561 return "TLSAccept";
562
563 if (&CONFIG_TLS_CA_FILE == param)
564 return ZBX_TLS_PARAMETER_CONFIG_FILE == type ? "TLSCAFile" : "--tls-ca-file";
565
566 if (&CONFIG_TLS_CRL_FILE == param)
567 return ZBX_TLS_PARAMETER_CONFIG_FILE == type ? "TLSCRLFile" : "--tls-crl-file";
568
569 if (&CONFIG_TLS_SERVER_CERT_ISSUER == param)
570 {
571 if (ZBX_TLS_PARAMETER_CONFIG_FILE == type)
572 return "TLSServerCertIssuer";
573
574 if (0 != (program_type & ZBX_PROGRAM_TYPE_GET))
575 return "--tls-agent-cert-issuer";
576 else
577 return "--tls-server-cert-issuer";
578 }
579
580 if (&CONFIG_TLS_SERVER_CERT_SUBJECT == param)
581 {
582 if (ZBX_TLS_PARAMETER_CONFIG_FILE == type)
583 return "TLSServerCertSubject";
584
585 if (0 != (program_type & ZBX_PROGRAM_TYPE_GET))
586 return "--tls-agent-cert-subject";
587 else
588 return "--tls-server-cert-subject";
589 }
590
591 if (&CONFIG_TLS_CERT_FILE == param)
592 return ZBX_TLS_PARAMETER_CONFIG_FILE == type ? "TLSCertFile" : "--tls-cert-file";
593
594 if (&CONFIG_TLS_KEY_FILE == param)
595 return ZBX_TLS_PARAMETER_CONFIG_FILE == type ? "TLSKeyFile" : "--tls-key-file";
596
597 if (&CONFIG_TLS_PSK_IDENTITY == param)
598 return ZBX_TLS_PARAMETER_CONFIG_FILE == type ? "TLSPSKIdentity" : "--tls-psk-identity";
599
600 if (&CONFIG_TLS_PSK_FILE == param)
601 return ZBX_TLS_PARAMETER_CONFIG_FILE == type ? "TLSPSKFile" : "--tls-psk-file";
602
603 if (&CONFIG_TLS_CIPHER_CERT13 == param)
604 return "TLSCipherCert13";
605
606 if (&CONFIG_TLS_CIPHER_CERT == param)
607 return "TLSCipherCert";
608
609 if (&CONFIG_TLS_CIPHER_PSK13 == param)
610 return "TLSCipherPSK13";
611
612 if (&CONFIG_TLS_CIPHER_PSK == param)
613 return "TLSCipherPSK";
614
615 if (&CONFIG_TLS_CIPHER_ALL13 == param)
616 return "TLSCipherAll13";
617
618 if (&CONFIG_TLS_CIPHER_ALL == param)
619 return "TLSCipherAll";
620
621 if (&CONFIG_TLS_CIPHER_CMD13 == param)
622 return "--tls-cipher13";
623
624 if (&CONFIG_TLS_CIPHER_CMD == param)
625 return "--tls-cipher";
626
627 THIS_SHOULD_NEVER_HAPPEN;
628
629 zbx_tls_free();
630 exit(EXIT_FAILURE);
631 }
632
633 /******************************************************************************
634 * *
635 * Function: zbx_tls_parameter_not_empty *
636 * *
637 * Purpose: *
638 * Helper function: check if a configuration parameter is defined it must *
639 * not be empty. Otherwise log error and exit. *
640 * *
641 * Parameters: *
642 * param - [IN] address of the global parameter variable *
643 * *
644 ******************************************************************************/
zbx_tls_parameter_not_empty(char ** param)645 static void zbx_tls_parameter_not_empty(char **param)
646 {
647 const char *value = *param;
648
649 if (NULL != value)
650 {
651 while ('\0' != *value)
652 {
653 if (0 == isspace(*value++))
654 return;
655 }
656
657 if (0 != (program_type & ZBX_PROGRAM_TYPE_SENDER))
658 {
659 const char *name1, *name2;
660
661 name1 = zbx_tls_parameter_name(ZBX_TLS_PARAMETER_CONFIG_FILE, param);
662 name2 = zbx_tls_parameter_name(ZBX_TLS_PARAMETER_COMMAND_LINE, param);
663
664 if (0 != strcmp(name1, name2))
665 {
666 zabbix_log(LOG_LEVEL_CRIT, "configuration parameter \"%s\" or \"%s\" is defined but"
667 " empty", name1, name2);
668 }
669 else
670 {
671 zabbix_log(LOG_LEVEL_CRIT, "configuration parameter \"%s\" is defined but empty",
672 name1);
673 }
674 }
675 else if (0 != (program_type & ZBX_PROGRAM_TYPE_GET))
676 {
677 zabbix_log(LOG_LEVEL_CRIT, "configuration parameter \"%s\" is defined but empty",
678 zbx_tls_parameter_name(ZBX_TLS_PARAMETER_COMMAND_LINE, param));
679 }
680 else
681 {
682 zabbix_log(LOG_LEVEL_CRIT, "configuration parameter \"%s\" is defined but empty",
683 zbx_tls_parameter_name(ZBX_TLS_PARAMETER_CONFIG_FILE, param));
684 }
685
686 zbx_tls_free();
687 exit(EXIT_FAILURE);
688 }
689 }
690
691 /******************************************************************************
692 * *
693 * Function: zbx_tls_validation_error *
694 * *
695 * Purpose: *
696 * Helper function: log error message depending on program type and exit. *
697 * *
698 * Parameters: *
699 * type - [IN] type of TLS validation error *
700 * param1 - [IN] address of the first global parameter variable *
701 * param2 - [IN] address of the second global parameter variable (if any) *
702 * *
703 ******************************************************************************/
704 #define ZBX_TLS_VALIDATION_INVALID 0
705 #define ZBX_TLS_VALIDATION_DEPENDENCY 1
706 #define ZBX_TLS_VALIDATION_REQUIREMENT 2
707 #define ZBX_TLS_VALIDATION_UTF8 3
708 #define ZBX_TLS_VALIDATION_NO_PSK 4
zbx_tls_validation_error(int type,char ** param1,char ** param2)709 static void zbx_tls_validation_error(int type, char **param1, char **param2)
710 {
711 if (ZBX_TLS_VALIDATION_INVALID == type)
712 {
713 if (0 != (program_type & ZBX_PROGRAM_TYPE_SENDER))
714 {
715 zabbix_log(LOG_LEVEL_CRIT, "invalid value of \"%s\" or \"%s\" parameter",
716 zbx_tls_parameter_name(ZBX_TLS_PARAMETER_CONFIG_FILE, param1),
717 zbx_tls_parameter_name(ZBX_TLS_PARAMETER_COMMAND_LINE, param1));
718 }
719 else if (0 != (program_type & ZBX_PROGRAM_TYPE_GET))
720 {
721 zabbix_log(LOG_LEVEL_CRIT, "invalid value of \"%s\" parameter",
722 zbx_tls_parameter_name(ZBX_TLS_PARAMETER_COMMAND_LINE, param1));
723 }
724 else
725 {
726 zabbix_log(LOG_LEVEL_CRIT, "invalid value of \"%s\" parameter",
727 zbx_tls_parameter_name(ZBX_TLS_PARAMETER_CONFIG_FILE, param1));
728 }
729 }
730 else if (ZBX_TLS_VALIDATION_DEPENDENCY == type)
731 {
732 if (0 != (program_type & ZBX_PROGRAM_TYPE_SENDER))
733 {
734 zabbix_log(LOG_LEVEL_CRIT, "parameter \"%s\" or \"%s\" is defined,"
735 " but neither \"%s\" nor \"%s\" is defined",
736 zbx_tls_parameter_name(ZBX_TLS_PARAMETER_CONFIG_FILE, param1),
737 zbx_tls_parameter_name(ZBX_TLS_PARAMETER_COMMAND_LINE, param1),
738 zbx_tls_parameter_name(ZBX_TLS_PARAMETER_CONFIG_FILE, param2),
739 zbx_tls_parameter_name(ZBX_TLS_PARAMETER_COMMAND_LINE, param2));
740 }
741 else if (0 != (program_type & ZBX_PROGRAM_TYPE_GET))
742 {
743 zabbix_log(LOG_LEVEL_CRIT, "parameter \"%s\" is defined, but \"%s\" is not defined",
744 zbx_tls_parameter_name(ZBX_TLS_PARAMETER_COMMAND_LINE, param1),
745 zbx_tls_parameter_name(ZBX_TLS_PARAMETER_COMMAND_LINE, param2));
746 }
747 else
748 {
749 zabbix_log(LOG_LEVEL_CRIT, "parameter \"%s\" is defined, but \"%s\" is not defined",
750 zbx_tls_parameter_name(ZBX_TLS_PARAMETER_CONFIG_FILE, param1),
751 zbx_tls_parameter_name(ZBX_TLS_PARAMETER_CONFIG_FILE, param2));
752 }
753 }
754 else if (ZBX_TLS_VALIDATION_REQUIREMENT == type)
755 {
756 if (0 != (program_type & ZBX_PROGRAM_TYPE_SENDER))
757 {
758 zabbix_log(LOG_LEVEL_CRIT, "parameter \"%s\" or \"%s\" value requires \"%s\" or \"%s\","
759 " but neither of them is defined",
760 zbx_tls_parameter_name(ZBX_TLS_PARAMETER_CONFIG_FILE, param1),
761 zbx_tls_parameter_name(ZBX_TLS_PARAMETER_COMMAND_LINE, param1),
762 zbx_tls_parameter_name(ZBX_TLS_PARAMETER_CONFIG_FILE, param2),
763 zbx_tls_parameter_name(ZBX_TLS_PARAMETER_COMMAND_LINE, param2));
764 }
765 else if (0 != (program_type & ZBX_PROGRAM_TYPE_GET))
766 {
767 zabbix_log(LOG_LEVEL_CRIT, "parameter \"%s\" value requires \"%s\", but it is not defined",
768 zbx_tls_parameter_name(ZBX_TLS_PARAMETER_COMMAND_LINE, param1),
769 zbx_tls_parameter_name(ZBX_TLS_PARAMETER_COMMAND_LINE, param2));
770 }
771 else
772 {
773 zabbix_log(LOG_LEVEL_CRIT, "parameter \"%s\" value requires \"%s\", but it is not defined",
774 zbx_tls_parameter_name(ZBX_TLS_PARAMETER_CONFIG_FILE, param1),
775 zbx_tls_parameter_name(ZBX_TLS_PARAMETER_CONFIG_FILE, param2));
776 }
777 }
778 else if (ZBX_TLS_VALIDATION_UTF8 == type)
779 {
780 if (0 != (program_type & ZBX_PROGRAM_TYPE_SENDER))
781 {
782 zabbix_log(LOG_LEVEL_CRIT, "parameter \"%s\" or \"%s\" value is not a valid UTF-8 string",
783 zbx_tls_parameter_name(ZBX_TLS_PARAMETER_CONFIG_FILE, param1),
784 zbx_tls_parameter_name(ZBX_TLS_PARAMETER_COMMAND_LINE, param1));
785 }
786 else if (0 != (program_type & ZBX_PROGRAM_TYPE_GET))
787 {
788 zabbix_log(LOG_LEVEL_CRIT, "parameter \"%s\" value is not a valid UTF-8 string",
789 zbx_tls_parameter_name(ZBX_TLS_PARAMETER_COMMAND_LINE, param1));
790 }
791 else
792 {
793 zabbix_log(LOG_LEVEL_CRIT, "parameter \"%s\" value is not a valid UTF-8 string",
794 zbx_tls_parameter_name(ZBX_TLS_PARAMETER_CONFIG_FILE, param1));
795 }
796 }
797 else if (ZBX_TLS_VALIDATION_NO_PSK == type)
798 {
799 if (0 != (program_type & ZBX_PROGRAM_TYPE_SENDER))
800 {
801 zabbix_log(LOG_LEVEL_CRIT, "value of parameter \"%s\" or \"%s\" requires support of encrypted"
802 " connection with PSK but support for PSK was not compiled in",
803 zbx_tls_parameter_name(ZBX_TLS_PARAMETER_CONFIG_FILE, param1),
804 zbx_tls_parameter_name(ZBX_TLS_PARAMETER_COMMAND_LINE, param1));
805 }
806 else if (0 != (program_type & ZBX_PROGRAM_TYPE_GET))
807 {
808 zabbix_log(LOG_LEVEL_CRIT, "value of parameter \"%s\" requires support of encrypted"
809 " connection with PSK but support for PSK was not compiled in",
810 zbx_tls_parameter_name(ZBX_TLS_PARAMETER_COMMAND_LINE, param1));
811 }
812 else
813 {
814 zabbix_log(LOG_LEVEL_CRIT, "value of parameter \"%s\" requires support of encrypted"
815 " connection with PSK but support for PSK was not compiled in",
816 zbx_tls_parameter_name(ZBX_TLS_PARAMETER_CONFIG_FILE, param1));
817 }
818 }
819 else
820 THIS_SHOULD_NEVER_HAPPEN;
821
822 zbx_tls_free();
823 exit(EXIT_FAILURE);
824 }
825
826 /******************************************************************************
827 * *
828 * Function: zbx_tls_validation_error2 *
829 * *
830 * Purpose: *
831 * Helper function: log error message depending on program type and exit *
832 * *
833 * Parameters: *
834 * type - [IN] type of TLS validation error *
835 * param1 - [IN] address of the first global parameter variable *
836 * param2 - [IN] address of the second global parameter variable *
837 * param3 - [IN] address of the third global parameter variable *
838 * *
839 ******************************************************************************/
zbx_tls_validation_error2(int type,char ** param1,char ** param2,char ** param3)840 static void zbx_tls_validation_error2(int type, char **param1, char **param2, char **param3)
841 {
842 if (ZBX_TLS_VALIDATION_DEPENDENCY == type)
843 {
844 if (0 != (program_type & ZBX_PROGRAM_TYPE_AGENTD))
845 {
846 zabbix_log(LOG_LEVEL_CRIT, "parameter \"%s\" is defined,"
847 " but neither \"%s\" nor \"%s\" is defined",
848 zbx_tls_parameter_name(ZBX_TLS_PARAMETER_CONFIG_FILE, param1),
849 zbx_tls_parameter_name(ZBX_TLS_PARAMETER_CONFIG_FILE, param2),
850 zbx_tls_parameter_name(ZBX_TLS_PARAMETER_CONFIG_FILE, param3));
851 }
852 else if (0 != (program_type & ZBX_PROGRAM_TYPE_GET))
853 {
854 zabbix_log(LOG_LEVEL_CRIT, "parameter \"%s\" is defined,"
855 " but neither \"%s\" nor \"%s\" is defined",
856 zbx_tls_parameter_name(ZBX_TLS_PARAMETER_COMMAND_LINE, param1),
857 zbx_tls_parameter_name(ZBX_TLS_PARAMETER_COMMAND_LINE, param2),
858 zbx_tls_parameter_name(ZBX_TLS_PARAMETER_COMMAND_LINE, param3));
859 }
860 else if (0 != (program_type & ZBX_PROGRAM_TYPE_SENDER))
861 {
862 zabbix_log(LOG_LEVEL_CRIT, "parameter \"%s\" is defined,"
863 " but neither \"%s\", nor \"%s\", nor \"%s\", nor \"%s\" is defined",
864 zbx_tls_parameter_name(ZBX_TLS_PARAMETER_COMMAND_LINE, param1),
865 zbx_tls_parameter_name(ZBX_TLS_PARAMETER_CONFIG_FILE, param2),
866 zbx_tls_parameter_name(ZBX_TLS_PARAMETER_COMMAND_LINE, param2),
867 zbx_tls_parameter_name(ZBX_TLS_PARAMETER_CONFIG_FILE, param3),
868 zbx_tls_parameter_name(ZBX_TLS_PARAMETER_COMMAND_LINE, param3));
869 }
870 }
871 else
872 THIS_SHOULD_NEVER_HAPPEN;
873
874 zbx_tls_free();
875 exit(EXIT_FAILURE);
876 }
877
878 /******************************************************************************
879 * *
880 * Function: zbx_tls_validate_config *
881 * *
882 * Purpose: check for allowed combinations of TLS configuration parameters *
883 * *
884 * Comments: *
885 * Valid combinations: *
886 * - either all 3 certificate parameters - CONFIG_TLS_CERT_FILE, *
887 * CONFIG_TLS_KEY_FILE, CONFIG_TLS_CA_FILE - are defined and not *
888 * empty or none of them. Parameter CONFIG_TLS_CRL_FILE is optional *
889 * but may be defined only together with the 3 certificate *
890 * parameters, *
891 * - either both PSK parameters - CONFIG_TLS_PSK_IDENTITY and *
892 * CONFIG_TLS_PSK_FILE - are defined and not empty or none of them, *
893 * (if CONFIG_TLS_PSK_IDENTITY is defined it must be a valid UTF-8 *
894 * string), *
895 * - in active agent, active proxy, zabbix_get, and zabbix_sender the *
896 * certificate and PSK parameters must match the value of *
897 * CONFIG_TLS_CONNECT parameter, *
898 * - in passive agent and passive proxy the certificate and PSK *
899 * parameters must match the value of CONFIG_TLS_ACCEPT parameter. *
900 * *
901 ******************************************************************************/
zbx_tls_validate_config(void)902 void zbx_tls_validate_config(void)
903 {
904 zbx_tls_parameter_not_empty(&CONFIG_TLS_CONNECT);
905 zbx_tls_parameter_not_empty(&CONFIG_TLS_ACCEPT);
906 zbx_tls_parameter_not_empty(&CONFIG_TLS_CA_FILE);
907 zbx_tls_parameter_not_empty(&CONFIG_TLS_CRL_FILE);
908 zbx_tls_parameter_not_empty(&CONFIG_TLS_SERVER_CERT_ISSUER);
909 zbx_tls_parameter_not_empty(&CONFIG_TLS_SERVER_CERT_SUBJECT);
910 zbx_tls_parameter_not_empty(&CONFIG_TLS_CERT_FILE);
911 zbx_tls_parameter_not_empty(&CONFIG_TLS_KEY_FILE);
912 zbx_tls_parameter_not_empty(&CONFIG_TLS_PSK_IDENTITY);
913 zbx_tls_parameter_not_empty(&CONFIG_TLS_PSK_FILE);
914
915 zbx_tls_parameter_not_empty(&CONFIG_TLS_CIPHER_CERT13);
916 zbx_tls_parameter_not_empty(&CONFIG_TLS_CIPHER_PSK13);
917 zbx_tls_parameter_not_empty(&CONFIG_TLS_CIPHER_ALL13);
918 zbx_tls_parameter_not_empty(&CONFIG_TLS_CIPHER_CMD13);
919
920 zbx_tls_parameter_not_empty(&CONFIG_TLS_CIPHER_CERT);
921 zbx_tls_parameter_not_empty(&CONFIG_TLS_CIPHER_PSK);
922 zbx_tls_parameter_not_empty(&CONFIG_TLS_CIPHER_ALL);
923 zbx_tls_parameter_not_empty(&CONFIG_TLS_CIPHER_CMD);
924
925 /* parse and validate 'TLSConnect' parameter (in zabbix_proxy.conf, zabbix_agentd.conf) and '--tls-connect' */
926 /* parameter (in zabbix_get and zabbix_sender) */
927
928 if (NULL != CONFIG_TLS_CONNECT)
929 {
930 /* 'configured_tls_connect_mode' is shared between threads on MS Windows */
931
932 if (0 == strcmp(CONFIG_TLS_CONNECT, ZBX_TCP_SEC_UNENCRYPTED_TXT))
933 configured_tls_connect_mode = ZBX_TCP_SEC_UNENCRYPTED;
934 else if (0 == strcmp(CONFIG_TLS_CONNECT, ZBX_TCP_SEC_TLS_CERT_TXT))
935 configured_tls_connect_mode = ZBX_TCP_SEC_TLS_CERT;
936 else if (0 == strcmp(CONFIG_TLS_CONNECT, ZBX_TCP_SEC_TLS_PSK_TXT))
937 #if defined(HAVE_POLARSSL) || defined(HAVE_GNUTLS) || (defined(HAVE_OPENSSL) && defined(HAVE_OPENSSL_WITH_PSK))
938 configured_tls_connect_mode = ZBX_TCP_SEC_TLS_PSK;
939 #else
940 zbx_tls_validation_error(ZBX_TLS_VALIDATION_NO_PSK, &CONFIG_TLS_CONNECT, NULL);
941 #endif
942 else
943 zbx_tls_validation_error(ZBX_TLS_VALIDATION_INVALID, &CONFIG_TLS_CONNECT, NULL);
944 }
945
946 /* parse and validate 'TLSAccept' parameter (in zabbix_proxy.conf, zabbix_agentd.conf) */
947
948 if (NULL != CONFIG_TLS_ACCEPT)
949 {
950 char *s, *p, *delim;
951 unsigned int accept_modes_tmp = 0; /* 'configured_tls_accept_modes' is shared between threads on */
952 /* MS Windows. To avoid races make a local temporary */
953 /* variable, modify it and write into */
954 /* 'configured_tls_accept_modes' when done. */
955
956 p = s = zbx_strdup(NULL, CONFIG_TLS_ACCEPT);
957
958 while (1)
959 {
960 delim = strchr(p, ',');
961
962 if (NULL != delim)
963 *delim = '\0';
964
965 if (0 == strcmp(p, ZBX_TCP_SEC_UNENCRYPTED_TXT))
966 accept_modes_tmp |= ZBX_TCP_SEC_UNENCRYPTED;
967 else if (0 == strcmp(p, ZBX_TCP_SEC_TLS_CERT_TXT))
968 accept_modes_tmp |= ZBX_TCP_SEC_TLS_CERT;
969 else if (0 == strcmp(p, ZBX_TCP_SEC_TLS_PSK_TXT))
970 #if defined(HAVE_POLARSSL) || defined(HAVE_GNUTLS) || (defined(HAVE_OPENSSL) && defined(HAVE_OPENSSL_WITH_PSK))
971 accept_modes_tmp |= ZBX_TCP_SEC_TLS_PSK;
972 #else
973 zbx_tls_validation_error(ZBX_TLS_VALIDATION_NO_PSK, &CONFIG_TLS_ACCEPT, NULL);
974 #endif
975 else
976 {
977 zbx_free(s);
978 zbx_tls_validation_error(ZBX_TLS_VALIDATION_INVALID, &CONFIG_TLS_ACCEPT, NULL);
979 }
980
981 if (NULL == delim)
982 break;
983
984 p = delim + 1;
985 }
986
987 configured_tls_accept_modes = accept_modes_tmp;
988
989 zbx_free(s);
990 }
991
992 /* either both a certificate and a private key must be defined or none of them */
993
994 if (NULL != CONFIG_TLS_CERT_FILE && NULL == CONFIG_TLS_KEY_FILE)
995 zbx_tls_validation_error(ZBX_TLS_VALIDATION_DEPENDENCY, &CONFIG_TLS_CERT_FILE, &CONFIG_TLS_KEY_FILE);
996
997 if (NULL != CONFIG_TLS_KEY_FILE && NULL == CONFIG_TLS_CERT_FILE)
998 zbx_tls_validation_error(ZBX_TLS_VALIDATION_DEPENDENCY, &CONFIG_TLS_KEY_FILE, &CONFIG_TLS_CERT_FILE);
999
1000 /* CA file must be defined only together with a certificate */
1001
1002 if (NULL != CONFIG_TLS_CERT_FILE && NULL == CONFIG_TLS_CA_FILE)
1003 zbx_tls_validation_error(ZBX_TLS_VALIDATION_DEPENDENCY, &CONFIG_TLS_CERT_FILE, &CONFIG_TLS_CA_FILE);
1004
1005 if (NULL != CONFIG_TLS_CA_FILE && NULL == CONFIG_TLS_CERT_FILE)
1006 zbx_tls_validation_error(ZBX_TLS_VALIDATION_DEPENDENCY, &CONFIG_TLS_CA_FILE, &CONFIG_TLS_CERT_FILE);
1007
1008 /* CRL file is optional but must be defined only together with a certificate */
1009
1010 if (NULL == CONFIG_TLS_CERT_FILE && NULL != CONFIG_TLS_CRL_FILE)
1011 zbx_tls_validation_error(ZBX_TLS_VALIDATION_DEPENDENCY, &CONFIG_TLS_CRL_FILE, &CONFIG_TLS_CERT_FILE);
1012
1013 /* Server certificate issuer is optional but must be defined only together with a certificate */
1014
1015 if (NULL == CONFIG_TLS_CERT_FILE && NULL != CONFIG_TLS_SERVER_CERT_ISSUER)
1016 {
1017 zbx_tls_validation_error(ZBX_TLS_VALIDATION_DEPENDENCY, &CONFIG_TLS_SERVER_CERT_ISSUER,
1018 &CONFIG_TLS_CERT_FILE);
1019 }
1020
1021 /* Server certificate subject is optional but must be defined only together with a certificate */
1022
1023 if (NULL == CONFIG_TLS_CERT_FILE && NULL != CONFIG_TLS_SERVER_CERT_SUBJECT)
1024 {
1025 zbx_tls_validation_error(ZBX_TLS_VALIDATION_DEPENDENCY, &CONFIG_TLS_SERVER_CERT_SUBJECT,
1026 &CONFIG_TLS_CERT_FILE);
1027 }
1028
1029 /* either both a PSK and a PSK identity must be defined or none of them */
1030
1031 if (NULL != CONFIG_TLS_PSK_FILE && NULL == CONFIG_TLS_PSK_IDENTITY)
1032 zbx_tls_validation_error(ZBX_TLS_VALIDATION_DEPENDENCY, &CONFIG_TLS_PSK_FILE, &CONFIG_TLS_PSK_IDENTITY);
1033
1034 if (NULL != CONFIG_TLS_PSK_IDENTITY && NULL == CONFIG_TLS_PSK_FILE)
1035 zbx_tls_validation_error(ZBX_TLS_VALIDATION_DEPENDENCY, &CONFIG_TLS_PSK_IDENTITY, &CONFIG_TLS_PSK_FILE);
1036
1037 /* PSK identity must be a valid UTF-8 string (RFC 4279 says Unicode) */
1038 if (NULL != CONFIG_TLS_PSK_IDENTITY && SUCCEED != zbx_is_utf8(CONFIG_TLS_PSK_IDENTITY))
1039 zbx_tls_validation_error(ZBX_TLS_VALIDATION_UTF8, &CONFIG_TLS_PSK_IDENTITY, NULL);
1040
1041 /* active agentd, active proxy, zabbix_get, and zabbix_sender specific validation */
1042
1043 if ((0 != (program_type & ZBX_PROGRAM_TYPE_AGENTD) && 0 != CONFIG_ACTIVE_FORKS) ||
1044 (0 != (program_type & (ZBX_PROGRAM_TYPE_PROXY_ACTIVE | ZBX_PROGRAM_TYPE_GET |
1045 ZBX_PROGRAM_TYPE_SENDER))))
1046 {
1047 /* 'TLSConnect' is the master parameter to be matched by certificate and PSK parameters. */
1048
1049 if (NULL != CONFIG_TLS_CERT_FILE && NULL == CONFIG_TLS_CONNECT)
1050 {
1051 zbx_tls_validation_error(ZBX_TLS_VALIDATION_DEPENDENCY, &CONFIG_TLS_CERT_FILE,
1052 &CONFIG_TLS_CONNECT);
1053 }
1054
1055 if (NULL != CONFIG_TLS_PSK_FILE && NULL == CONFIG_TLS_CONNECT)
1056 {
1057 zbx_tls_validation_error(ZBX_TLS_VALIDATION_DEPENDENCY, &CONFIG_TLS_PSK_FILE,
1058 &CONFIG_TLS_CONNECT);
1059 }
1060
1061 if (0 != (configured_tls_connect_mode & ZBX_TCP_SEC_TLS_CERT) && NULL == CONFIG_TLS_CERT_FILE)
1062 {
1063 zbx_tls_validation_error(ZBX_TLS_VALIDATION_REQUIREMENT, &CONFIG_TLS_CONNECT,
1064 &CONFIG_TLS_CERT_FILE);
1065 }
1066
1067 if (0 != (configured_tls_connect_mode & ZBX_TCP_SEC_TLS_PSK) && NULL == CONFIG_TLS_PSK_FILE)
1068 {
1069 zbx_tls_validation_error(ZBX_TLS_VALIDATION_REQUIREMENT, &CONFIG_TLS_CONNECT,
1070 &CONFIG_TLS_PSK_FILE);
1071 }
1072 }
1073
1074 /* passive agentd and passive proxy specific validation */
1075
1076 if ((0 != (program_type & ZBX_PROGRAM_TYPE_AGENTD) && 0 != CONFIG_PASSIVE_FORKS) ||
1077 0 != (program_type & ZBX_PROGRAM_TYPE_PROXY_PASSIVE))
1078 {
1079 /* 'TLSAccept' is the master parameter to be matched by certificate and PSK parameters */
1080
1081 if (NULL != CONFIG_TLS_CERT_FILE && NULL == CONFIG_TLS_ACCEPT)
1082 {
1083 zbx_tls_validation_error(ZBX_TLS_VALIDATION_DEPENDENCY, &CONFIG_TLS_CERT_FILE,
1084 &CONFIG_TLS_ACCEPT);
1085 }
1086
1087 if (NULL != CONFIG_TLS_PSK_FILE && NULL == CONFIG_TLS_ACCEPT)
1088 {
1089 zbx_tls_validation_error(ZBX_TLS_VALIDATION_DEPENDENCY, &CONFIG_TLS_PSK_FILE,
1090 &CONFIG_TLS_ACCEPT);
1091 }
1092
1093 if (0 != (configured_tls_accept_modes & ZBX_TCP_SEC_TLS_CERT) && NULL == CONFIG_TLS_CERT_FILE)
1094 {
1095 zbx_tls_validation_error(ZBX_TLS_VALIDATION_REQUIREMENT, &CONFIG_TLS_ACCEPT,
1096 &CONFIG_TLS_CERT_FILE);
1097 }
1098
1099 if (0 != (configured_tls_accept_modes & ZBX_TCP_SEC_TLS_PSK) && NULL == CONFIG_TLS_PSK_FILE)
1100 {
1101 zbx_tls_validation_error(ZBX_TLS_VALIDATION_REQUIREMENT, &CONFIG_TLS_ACCEPT,
1102 &CONFIG_TLS_PSK_FILE);
1103 }
1104 }
1105
1106 /* TLSCipher* and --tls-cipher* parameter validation */
1107
1108 /* parameters 'TLSCipherCert13' and 'TLSCipherCert' can be used only with certificate */
1109
1110 if (NULL != CONFIG_TLS_CIPHER_CERT13 && NULL == CONFIG_TLS_CERT_FILE)
1111 {
1112 zbx_tls_validation_error(ZBX_TLS_VALIDATION_DEPENDENCY, &CONFIG_TLS_CIPHER_CERT13,
1113 &CONFIG_TLS_CERT_FILE);
1114 }
1115
1116 if (NULL != CONFIG_TLS_CIPHER_CERT && NULL == CONFIG_TLS_CERT_FILE)
1117 zbx_tls_validation_error(ZBX_TLS_VALIDATION_DEPENDENCY, &CONFIG_TLS_CIPHER_CERT, &CONFIG_TLS_CERT_FILE);
1118
1119 /* For server and proxy 'TLSCipherPSK13' and 'TLSCipherPSK' are optional and do not depend on other */
1120 /* TLS parameters. Validate only in case of agent, zabbix_get and sender. */
1121
1122 if (0 != (program_type & (ZBX_PROGRAM_TYPE_AGENTD | ZBX_PROGRAM_TYPE_GET | ZBX_PROGRAM_TYPE_SENDER)))
1123 {
1124 if (NULL != CONFIG_TLS_CIPHER_PSK13 && NULL == CONFIG_TLS_PSK_IDENTITY)
1125 {
1126 zbx_tls_validation_error(ZBX_TLS_VALIDATION_DEPENDENCY, &CONFIG_TLS_CIPHER_PSK13,
1127 &CONFIG_TLS_PSK_IDENTITY);
1128
1129 }
1130
1131 if (NULL != CONFIG_TLS_CIPHER_PSK && NULL == CONFIG_TLS_PSK_IDENTITY)
1132 {
1133 zbx_tls_validation_error(ZBX_TLS_VALIDATION_DEPENDENCY, &CONFIG_TLS_CIPHER_PSK,
1134 &CONFIG_TLS_PSK_IDENTITY);
1135 }
1136 }
1137
1138 /* Parameters 'TLSCipherAll13' and 'TLSCipherAll' are used only for incoming connections if a combined list */
1139 /* of certificate- and PSK-based ciphersuites is used. They may be defined without other TLS parameters on */
1140 /* server and proxy (at least some hosts may be connecting with PSK). */
1141 /* 'zabbix_get' and sender do not use these parameters. Validate only in case of agent. */
1142
1143 if (0 != (program_type & ZBX_PROGRAM_TYPE_AGENTD) &&
1144 NULL == CONFIG_TLS_CERT_FILE && NULL == CONFIG_TLS_PSK_IDENTITY)
1145 {
1146 if (NULL != CONFIG_TLS_CIPHER_ALL13)
1147 {
1148 zbx_tls_validation_error2(ZBX_TLS_VALIDATION_DEPENDENCY, &CONFIG_TLS_CIPHER_ALL13,
1149 &CONFIG_TLS_CERT_FILE, &CONFIG_TLS_PSK_IDENTITY);
1150 }
1151
1152 if (NULL != CONFIG_TLS_CIPHER_ALL)
1153 {
1154 zbx_tls_validation_error2(ZBX_TLS_VALIDATION_DEPENDENCY, &CONFIG_TLS_CIPHER_ALL,
1155 &CONFIG_TLS_CERT_FILE, &CONFIG_TLS_PSK_IDENTITY);
1156 }
1157 }
1158
1159 /* Parameters '--tls-cipher13' and '--tls-cipher' can be used only in zabbix_get and sender with */
1160 /* certificate or PSK. */
1161
1162 if (0 != (program_type & (ZBX_PROGRAM_TYPE_GET | ZBX_PROGRAM_TYPE_SENDER)) &&
1163 NULL == CONFIG_TLS_CERT_FILE && NULL == CONFIG_TLS_PSK_IDENTITY)
1164 {
1165 if (NULL != CONFIG_TLS_CIPHER_CMD13)
1166 {
1167 zbx_tls_validation_error2(ZBX_TLS_VALIDATION_DEPENDENCY, &CONFIG_TLS_CIPHER_CMD13,
1168 &CONFIG_TLS_CERT_FILE, &CONFIG_TLS_PSK_IDENTITY);
1169 }
1170
1171 if (NULL != CONFIG_TLS_CIPHER_CMD)
1172 {
1173 zbx_tls_validation_error2(ZBX_TLS_VALIDATION_DEPENDENCY, &CONFIG_TLS_CIPHER_CMD,
1174 &CONFIG_TLS_CERT_FILE, &CONFIG_TLS_PSK_IDENTITY);
1175 }
1176 }
1177 }
1178
1179 #if defined(HAVE_POLARSSL)
1180 /******************************************************************************
1181 * *
1182 * Function: zbx_is_ciphersuite_cert *
1183 * *
1184 * Purpose: does the specified ciphersuite ID refer to a non-PSK *
1185 * (i.e. certificate) ciphersuite supported for the specified TLS *
1186 * version range *
1187 * *
1188 * Comments: *
1189 * RFC 7465 "Prohibiting RC4 Cipher Suites" requires that RC4 should *
1190 * never be used. Also, discard weak encryptions. *
1191 * *
1192 ******************************************************************************/
zbx_is_ciphersuite_cert(const int * p)1193 static int zbx_is_ciphersuite_cert(const int *p)
1194 {
1195 const ssl_ciphersuite_t *info;
1196
1197 /* PolarSSL function ssl_ciphersuite_uses_psk() is not used here because it can be unavailable in some */
1198 /* installations. */
1199 if (NULL != (info = ssl_ciphersuite_from_id(*p)) && (POLARSSL_KEY_EXCHANGE_ECDHE_RSA == info->key_exchange ||
1200 POLARSSL_KEY_EXCHANGE_RSA == info->key_exchange) &&
1201 (POLARSSL_CIPHER_AES_128_GCM == info->cipher || POLARSSL_CIPHER_AES_128_CBC == info->cipher) &&
1202 0 == (info->flags & POLARSSL_CIPHERSUITE_WEAK) &&
1203 (ZBX_TLS_MIN_MAJOR_VER > info->min_major_ver || (ZBX_TLS_MIN_MAJOR_VER == info->min_major_ver &&
1204 ZBX_TLS_MIN_MINOR_VER >= info->min_minor_ver)) &&
1205 (ZBX_TLS_MAX_MAJOR_VER < info->max_major_ver || (ZBX_TLS_MAX_MAJOR_VER == info->max_major_ver &&
1206 ZBX_TLS_MAX_MINOR_VER <= info->max_minor_ver)))
1207 {
1208 return SUCCEED;
1209 }
1210 else
1211 return FAIL;
1212 }
1213
1214 /******************************************************************************
1215 * *
1216 * Function: zbx_is_ciphersuite_psk *
1217 * *
1218 * Purpose: does the specified ciphersuite ID refer to a PSK ciphersuite *
1219 * supported for the specified TLS version range *
1220 * *
1221 * Comments: *
1222 * RFC 7465 "Prohibiting RC4 Cipher Suites" requires that RC4 should *
1223 * never be used. Also, discard weak encryptions. *
1224 * *
1225 ******************************************************************************/
zbx_is_ciphersuite_psk(const int * p)1226 static int zbx_is_ciphersuite_psk(const int *p)
1227 {
1228 const ssl_ciphersuite_t *info;
1229
1230 if (NULL != (info = ssl_ciphersuite_from_id(*p)) && (POLARSSL_KEY_EXCHANGE_ECDHE_PSK == info->key_exchange ||
1231 POLARSSL_KEY_EXCHANGE_PSK == info->key_exchange) &&
1232 (POLARSSL_CIPHER_AES_128_GCM == info->cipher || POLARSSL_CIPHER_AES_128_CBC == info->cipher) &&
1233 0 == (info->flags & POLARSSL_CIPHERSUITE_WEAK) &&
1234 (ZBX_TLS_MIN_MAJOR_VER > info->min_major_ver || (ZBX_TLS_MIN_MAJOR_VER == info->min_major_ver &&
1235 ZBX_TLS_MIN_MINOR_VER >= info->min_minor_ver)) &&
1236 (ZBX_TLS_MAX_MAJOR_VER < info->max_major_ver || (ZBX_TLS_MAX_MAJOR_VER == info->max_major_ver &&
1237 ZBX_TLS_MAX_MINOR_VER <= info->max_minor_ver)))
1238 {
1239 return SUCCEED;
1240 }
1241 else
1242 return FAIL;
1243 }
1244
1245 /******************************************************************************
1246 * *
1247 * Function: zbx_is_ciphersuite_all *
1248 * *
1249 * Purpose: does the specified ciphersuite ID refer to a good ciphersuite *
1250 * supported for the specified TLS version range *
1251 * *
1252 * Comments: *
1253 * RFC 7465 "Prohibiting RC4 Cipher Suites" requires that RC4 should *
1254 * never be used. Also, discard weak encryptions. *
1255 * *
1256 ******************************************************************************/
zbx_is_ciphersuite_all(const int * p)1257 static int zbx_is_ciphersuite_all(const int *p)
1258 {
1259 const ssl_ciphersuite_t *info;
1260
1261 if (NULL != (info = ssl_ciphersuite_from_id(*p)) && (POLARSSL_KEY_EXCHANGE_ECDHE_RSA == info->key_exchange ||
1262 POLARSSL_KEY_EXCHANGE_RSA == info->key_exchange ||
1263 POLARSSL_KEY_EXCHANGE_ECDHE_PSK == info->key_exchange ||
1264 POLARSSL_KEY_EXCHANGE_PSK == info->key_exchange) &&
1265 (POLARSSL_CIPHER_AES_128_GCM == info->cipher || POLARSSL_CIPHER_AES_128_CBC == info->cipher) &&
1266 0 == (info->flags & POLARSSL_CIPHERSUITE_WEAK) &&
1267 (ZBX_TLS_MIN_MAJOR_VER > info->min_major_ver || (ZBX_TLS_MIN_MAJOR_VER == info->min_major_ver &&
1268 ZBX_TLS_MIN_MINOR_VER >= info->min_minor_ver)) &&
1269 (ZBX_TLS_MAX_MAJOR_VER < info->max_major_ver || (ZBX_TLS_MAX_MAJOR_VER == info->max_major_ver &&
1270 ZBX_TLS_MAX_MINOR_VER <= info->max_minor_ver)))
1271 {
1272 return SUCCEED;
1273 }
1274 else
1275 return FAIL;
1276 }
1277
1278 /******************************************************************************
1279 * *
1280 * Function: zbx_ciphersuites *
1281 * *
1282 * Purpose: copy a list of ciphersuites (certificate or PSK-related) from a *
1283 * list of all supported ciphersuites *
1284 * *
1285 ******************************************************************************/
zbx_ciphersuites(int type,int ** suites)1286 static unsigned int zbx_ciphersuites(int type, int **suites)
1287 {
1288 const int *supported_suites, *p;
1289 int *q;
1290 unsigned int count = 0;
1291
1292 supported_suites = ssl_list_ciphersuites();
1293
1294 /* count available relevant ciphersuites */
1295 for (p = supported_suites; 0 != *p; p++)
1296 {
1297 if (ZBX_TLS_CIPHERSUITE_CERT == type)
1298 {
1299 if (SUCCEED != zbx_is_ciphersuite_cert(p))
1300 continue;
1301 }
1302 else if (ZBX_TLS_CIPHERSUITE_PSK == type)
1303 {
1304 if (SUCCEED != zbx_is_ciphersuite_psk(p))
1305 continue;
1306 }
1307 else /* ZBX_TLS_CIPHERSUITE_ALL */
1308 {
1309 if (SUCCEED != zbx_is_ciphersuite_all(p))
1310 continue;
1311 }
1312
1313 count++;
1314 }
1315
1316 *suites = zbx_malloc(*suites, (count + 1) * sizeof(int));
1317
1318 /* copy the ciphersuites into array */
1319 for (p = supported_suites, q = *suites; 0 != *p; p++)
1320 {
1321 if (ZBX_TLS_CIPHERSUITE_CERT == type)
1322 {
1323 if (SUCCEED != zbx_is_ciphersuite_cert(p))
1324 continue;
1325 }
1326 else if (ZBX_TLS_CIPHERSUITE_PSK == type)
1327 {
1328 if (SUCCEED != zbx_is_ciphersuite_psk(p))
1329 continue;
1330 }
1331 else /* ZBX_TLS_CIPHERSUITE_ALL */
1332 {
1333 if (SUCCEED != zbx_is_ciphersuite_all(p))
1334 continue;
1335 }
1336
1337 *q++ = *p;
1338 }
1339
1340 *q = 0;
1341
1342 return count;
1343 }
1344 #endif
1345
1346 /******************************************************************************
1347 * *
1348 * Function: zbx_psk_hex2bin *
1349 * *
1350 * Purpose: *
1351 * convert a pre-shared key from a textual representation (ASCII hex *
1352 * digit string) to a binary representation (byte string) *
1353 * *
1354 * Parameters: *
1355 * p_hex - [IN] null-terminated input PSK hex-string *
1356 * buf - [OUT] output buffer *
1357 * buf_len - [IN] output buffer size *
1358 * *
1359 * Return value: *
1360 * Number of PSK bytes written into 'buf' on successful conversion. *
1361 * -1 - an error occurred. *
1362 * *
1363 * Comments: *
1364 * In case of error incomplete useless data may be written into 'buf'. *
1365 * *
1366 ******************************************************************************/
zbx_psk_hex2bin(const unsigned char * p_hex,unsigned char * buf,int buf_len)1367 static int zbx_psk_hex2bin(const unsigned char *p_hex, unsigned char *buf, int buf_len)
1368 {
1369 unsigned char *q, hi, lo;
1370 int len = 0;
1371
1372 q = buf;
1373
1374 while ('\0' != *p_hex)
1375 {
1376 if (0 != isxdigit(*p_hex) && 0 != isxdigit(*(p_hex + 1)) && buf_len > len)
1377 {
1378 hi = *p_hex & 0x0f;
1379
1380 if ('9' < *p_hex++)
1381 hi += 9u;
1382
1383 lo = *p_hex & 0x0f;
1384
1385 if ('9' < *p_hex++)
1386 lo += 9u;
1387
1388 *q++ = hi << 4 | lo;
1389 len++;
1390 }
1391 else
1392 return -1;
1393 }
1394
1395 return len;
1396 }
1397
1398 #if defined(HAVE_POLARSSL)
1399 /******************************************************************************
1400 * *
1401 * Function: zbx_psk_cb *
1402 * *
1403 * Purpose: *
1404 * find and set the requested pre-shared key upon PolarSSL request *
1405 * *
1406 * Parameters: *
1407 * par - [IN] not used *
1408 * tls_ctx - [IN] TLS connection context *
1409 * psk_identity - [IN] PSK identity for which the PSK should be *
1410 * searched and set *
1411 * psk_identity_len - [IN] size of 'psk_identity' *
1412 * *
1413 * Return value: *
1414 * 0 - required PSK successfully found and set *
1415 * -1 - an error occurred *
1416 * *
1417 * Comments: *
1418 * A callback function, its arguments are defined in PolarSSL. *
1419 * Used only in server and proxy. *
1420 * *
1421 ******************************************************************************/
zbx_psk_cb(void * par,ssl_context * tls_ctx,const unsigned char * psk_identity,size_t psk_identity_len)1422 static int zbx_psk_cb(void *par, ssl_context *tls_ctx, const unsigned char *psk_identity,
1423 size_t psk_identity_len)
1424 {
1425 const char *__function_name = "zbx_psk_cb";
1426 unsigned char *psk;
1427 size_t psk_len = 0;
1428 int psk_bin_len;
1429 unsigned char tls_psk_identity[HOST_TLS_PSK_IDENTITY_LEN_MAX], tls_psk_hex[HOST_TLS_PSK_LEN_MAX],
1430 psk_buf[HOST_TLS_PSK_LEN / 2];
1431
1432 ZBX_UNUSED(par);
1433
1434 /* special print: psk_identity is not '\0'-terminated */
1435 zabbix_log(LOG_LEVEL_DEBUG, "%s() requested PSK identity \"%.*s\"", __function_name, (int)psk_identity_len,
1436 psk_identity);
1437
1438 /* try PSK from configuration file first (it is already in binary form) */
1439
1440 if (0 < my_psk_identity_len && my_psk_identity_len == psk_identity_len &&
1441 0 == memcmp(my_psk_identity, psk_identity, psk_identity_len))
1442 {
1443 psk = (unsigned char *)my_psk;
1444 psk_len = my_psk_len;
1445 }
1446 else /* search the required PSK in configuration cache */
1447 {
1448 if (HOST_TLS_PSK_IDENTITY_LEN < psk_identity_len)
1449 {
1450 THIS_SHOULD_NEVER_HAPPEN;
1451 return -1;
1452 }
1453
1454 memcpy(tls_psk_identity, psk_identity, psk_identity_len);
1455 tls_psk_identity[psk_identity_len] = '\0';
1456
1457 /* call the function DCget_psk_by_identity() by pointer */
1458 if (0 < find_psk_in_cache(tls_psk_identity, tls_psk_hex, sizeof(tls_psk_hex)))
1459 {
1460 /* convert PSK to binary form */
1461 if (0 >= (psk_bin_len = zbx_psk_hex2bin(tls_psk_hex, psk_buf, sizeof(psk_buf))))
1462 {
1463 /* this should have been prevented by validation in frontend or API */
1464 zabbix_log(LOG_LEVEL_WARNING, "cannot convert PSK to binary form for PSK identity"
1465 " \"%.*s\"", (int)psk_identity_len, psk_identity);
1466 return -1;
1467 }
1468
1469 psk = psk_buf;
1470 psk_len = (size_t)psk_bin_len;
1471 }
1472 else
1473 {
1474 zabbix_log(LOG_LEVEL_DEBUG, "%s() cannot find requested PSK identity \"%.*s\"", __function_name,
1475 (int)psk_identity_len, psk_identity);
1476 }
1477 }
1478
1479 if (0 < psk_len)
1480 {
1481 int res;
1482
1483 if (0 == (res = ssl_set_psk(tls_ctx, psk, psk_len, psk_identity, psk_identity_len)))
1484 return 0;
1485
1486 zbx_tls_error_msg(res, "", &err_msg);
1487 zabbix_log(LOG_LEVEL_WARNING, "cannot set PSK for PSK identity \"%.*s\": %s", (int)psk_identity_len,
1488 psk_identity, err_msg);
1489 zbx_free(err_msg);
1490 }
1491
1492 return -1;
1493 }
1494 #elif defined(HAVE_GNUTLS)
1495 /******************************************************************************
1496 * *
1497 * Function: zbx_psk_cb *
1498 * *
1499 * Purpose: *
1500 * find and set the requested pre-shared key upon GnuTLS request *
1501 * *
1502 * Parameters: *
1503 * session - [IN] not used *
1504 * psk_identity - [IN] PSK identity for which the PSK should be searched *
1505 * and set *
1506 * key - [OUT pre-shared key allocated and set *
1507 * *
1508 * Return value: *
1509 * 0 - required PSK successfully found and set *
1510 * -1 - an error occurred *
1511 * *
1512 * Comments: *
1513 * A callback function, its arguments are defined in GnuTLS. *
1514 * Used in all programs accepting connections. *
1515 * *
1516 ******************************************************************************/
zbx_psk_cb(gnutls_session_t session,const char * psk_identity,gnutls_datum_t * key)1517 static int zbx_psk_cb(gnutls_session_t session, const char *psk_identity, gnutls_datum_t *key)
1518 {
1519 const char *__function_name = "zbx_psk_cb";
1520 char *psk;
1521 size_t psk_len = 0;
1522 int psk_bin_len;
1523 unsigned char tls_psk_hex[HOST_TLS_PSK_LEN_MAX], psk_buf[HOST_TLS_PSK_LEN / 2];
1524
1525 ZBX_UNUSED(session);
1526
1527 zabbix_log(LOG_LEVEL_DEBUG, "%s() requested PSK identity \"%s\"", __function_name, psk_identity);
1528
1529 /* try PSK from configuration file first (it is already in binary form) */
1530
1531 if (0 < my_psk_identity_len && 0 == strcmp(my_psk_identity, psk_identity))
1532 {
1533 psk = my_psk;
1534 psk_len = my_psk_len;
1535 }
1536 else if (0 != (program_type & (ZBX_PROGRAM_TYPE_PROXY | ZBX_PROGRAM_TYPE_SERVER)))
1537 {
1538 /* search the required PSK in configuration cache */
1539
1540 /* call the function DCget_psk_by_identity() by pointer */
1541 if (0 < find_psk_in_cache((const unsigned char *)psk_identity, tls_psk_hex, sizeof(tls_psk_hex)))
1542 {
1543 /* convert PSK to binary form */
1544 if (0 >= (psk_bin_len = zbx_psk_hex2bin(tls_psk_hex, psk_buf, sizeof(psk_buf))))
1545 {
1546 /* this should have been prevented by validation in frontend or API */
1547 zabbix_log(LOG_LEVEL_WARNING, "cannot convert PSK to binary form for PSK identity"
1548 " \"%s\"", psk_identity);
1549 return -1; /* fail */
1550 }
1551
1552 psk = (char *)psk_buf;
1553 psk_len = (size_t)psk_bin_len;
1554 }
1555 else
1556 zabbix_log(LOG_LEVEL_WARNING, "cannot find requested PSK identity \"%s\"", psk_identity);
1557 }
1558 else if (0 < my_psk_identity_len)
1559 {
1560 zabbix_log(LOG_LEVEL_WARNING, "cannot find requested PSK identity \"%s\", available PSK identity"
1561 " \"%s\"", psk_identity, my_psk_identity);
1562 }
1563
1564 if (0 < psk_len)
1565 {
1566 if (NULL == (key->data = gnutls_malloc(psk_len)))
1567 {
1568 zabbix_log(LOG_LEVEL_WARNING, "cannot allocate " ZBX_FS_SIZE_T " bytes of memory for PSK with"
1569 " identity \"%s\"", (zbx_fs_size_t)psk_len, psk_identity);
1570 return -1; /* fail */
1571 }
1572
1573 memcpy(key->data, psk, psk_len);
1574 key->size = (unsigned int)psk_len;
1575
1576 return 0; /* success */
1577 }
1578
1579 return -1; /* PSK not found */
1580 }
1581 #elif defined(HAVE_OPENSSL) && defined(HAVE_OPENSSL_WITH_PSK)
1582 /******************************************************************************
1583 * *
1584 * Function: zbx_psk_client_cb *
1585 * *
1586 * Purpose: *
1587 * set pre-shared key for outgoing TLS connection upon OpenSSL request *
1588 * *
1589 * Parameters: *
1590 * ssl - [IN] not used *
1591 * hint - [IN] not used *
1592 * identity - [OUT] buffer to write PSK identity into *
1593 * max_identity_len - [IN] size of the 'identity' buffer *
1594 * psk - [OUT] buffer to write PSK into *
1595 * max_psk_len - [IN] size of the 'psk' buffer *
1596 * *
1597 * Return value: *
1598 * > 0 - length of PSK in bytes *
1599 * 0 - an error occurred *
1600 * *
1601 * Comments: *
1602 * A callback function, its arguments are defined in OpenSSL. *
1603 * Used in all programs making outgoing TLS PSK connections. *
1604 * *
1605 * As a client we use different PSKs depending on connection to be made. *
1606 * Apparently there is no simple way to specify which PSK should be set *
1607 * by this callback function. We use global variables to pass this info. *
1608 * *
1609 ******************************************************************************/
zbx_psk_client_cb(SSL * ssl,const char * hint,char * identity,unsigned int max_identity_len,unsigned char * psk,unsigned int max_psk_len)1610 static unsigned int zbx_psk_client_cb(SSL *ssl, const char *hint, char *identity,
1611 unsigned int max_identity_len, unsigned char *psk, unsigned int max_psk_len)
1612 {
1613 const char *__function_name = "zbx_psk_client_cb";
1614
1615 ZBX_UNUSED(ssl);
1616 ZBX_UNUSED(hint);
1617
1618 zabbix_log(LOG_LEVEL_DEBUG, "%s() requested PSK identity \"%s\"", __function_name, psk_identity_for_cb);
1619
1620 if (max_identity_len < psk_identity_len_for_cb + 1) /* 1 byte for terminating '\0' */
1621 {
1622 zabbix_log(LOG_LEVEL_WARNING, "requested PSK identity \"%s\" does not fit into %u-byte buffer",
1623 psk_identity_for_cb, max_identity_len);
1624 return 0;
1625 }
1626
1627 if (max_psk_len < psk_len_for_cb)
1628 {
1629 zabbix_log(LOG_LEVEL_WARNING, "PSK associated with PSK identity \"%s\" does not fit into %u-byte"
1630 " buffer", psk_identity_for_cb, max_psk_len);
1631 return 0;
1632 }
1633
1634 zbx_strlcpy(identity, psk_identity_for_cb, max_identity_len);
1635 memcpy(psk, psk_for_cb, psk_len_for_cb);
1636
1637 return (unsigned int)psk_len_for_cb;
1638 }
1639
1640 /******************************************************************************
1641 * *
1642 * Function: zbx_psk_server_cb *
1643 * *
1644 * Purpose: *
1645 * set pre-shared key for incoming TLS connection upon OpenSSL request *
1646 * *
1647 * Parameters: *
1648 * ssl - [IN] not used *
1649 * identity - [IN] PSK identity sent by client *
1650 * psk - [OUT] buffer to write PSK into *
1651 * max_psk_len - [IN] size of the 'psk' buffer *
1652 * *
1653 * Return value: *
1654 * > 0 - length of PSK in bytes *
1655 * 0 - PSK identity not found *
1656 * *
1657 * Comments: *
1658 * A callback function, its arguments are defined in OpenSSL. *
1659 * Used in all programs accepting incoming TLS PSK connections. *
1660 * *
1661 ******************************************************************************/
zbx_psk_server_cb(SSL * ssl,const char * identity,unsigned char * psk,unsigned int max_psk_len)1662 static unsigned int zbx_psk_server_cb(SSL *ssl, const char *identity, unsigned char *psk,
1663 unsigned int max_psk_len)
1664 {
1665 const char *__function_name = "zbx_psk_server_cb";
1666 char *psk_loc;
1667 size_t psk_len = 0;
1668 int psk_bin_len;
1669 unsigned char tls_psk_hex[HOST_TLS_PSK_LEN_MAX], psk_buf[HOST_TLS_PSK_LEN / 2];
1670
1671 ZBX_UNUSED(ssl);
1672
1673 zabbix_log(LOG_LEVEL_DEBUG, "%s() requested PSK identity \"%s\"", __function_name, identity);
1674
1675 incoming_connection_has_psk = 1;
1676
1677 /* try PSK from configuration file first (it is already in binary form) */
1678
1679 if (0 < my_psk_identity_len && 0 == strcmp(my_psk_identity, identity))
1680 {
1681 psk_loc = my_psk;
1682 psk_len = my_psk_len;
1683 }
1684 else if (0 != (program_type & (ZBX_PROGRAM_TYPE_PROXY | ZBX_PROGRAM_TYPE_SERVER)))
1685 {
1686 /* search the required PSK in configuration cache */
1687
1688 /* call the function DCget_psk_by_identity() by pointer */
1689 if (0 < find_psk_in_cache((const unsigned char *)identity, tls_psk_hex, sizeof(tls_psk_hex)))
1690 {
1691 /* convert PSK to binary form */
1692 if (0 >= (psk_bin_len = zbx_psk_hex2bin(tls_psk_hex, psk_buf, sizeof(psk_buf))))
1693 {
1694 /* this should have been prevented by validation in frontend or API */
1695 zabbix_log(LOG_LEVEL_WARNING, "cannot convert PSK to binary form for PSK identity"
1696 " \"%s\"", identity);
1697 goto fail;
1698 }
1699
1700 psk_loc = (char *)psk_buf;
1701 psk_len = (size_t)psk_bin_len;
1702 }
1703 else
1704 {
1705 zabbix_log(LOG_LEVEL_WARNING, "cannot find requested PSK identity \"%s\"", identity);
1706 goto fail;
1707 }
1708 }
1709 else if (0 < my_psk_identity_len)
1710 {
1711 zabbix_log(LOG_LEVEL_WARNING, "cannot find requested PSK identity \"%s\", available PSK identity"
1712 " \"%s\"", identity, my_psk_identity);
1713 }
1714
1715 if (0 < psk_len)
1716 {
1717 if ((size_t)max_psk_len < psk_len)
1718 {
1719 zabbix_log(LOG_LEVEL_WARNING, "PSK associated with PSK identity \"%s\" does not fit into"
1720 " %u-byte buffer", identity, max_psk_len);
1721 goto fail;
1722 }
1723
1724 memcpy(psk, psk_loc, psk_len);
1725 zbx_strlcpy(incoming_connection_psk_id, identity, sizeof(incoming_connection_psk_id));
1726
1727 return (unsigned int)psk_len; /* success */
1728 }
1729 fail:
1730 incoming_connection_psk_id[0] = '\0';
1731 return 0; /* PSK not found */
1732 }
1733 #endif
1734
1735 /******************************************************************************
1736 * *
1737 * Function: zbx_check_psk_identity_len *
1738 * *
1739 * Purpose: Check PSK identity length. Exit if length exceeds the maximum. *
1740 * *
1741 ******************************************************************************/
zbx_check_psk_identity_len(size_t psk_identity_len)1742 static void zbx_check_psk_identity_len(size_t psk_identity_len)
1743 {
1744 if (HOST_TLS_PSK_IDENTITY_LEN < psk_identity_len)
1745 {
1746 zabbix_log(LOG_LEVEL_CRIT, "PSK identity length " ZBX_FS_SIZE_T " exceeds the maximum length of %d"
1747 " bytes.", (zbx_fs_size_t)psk_identity_len, HOST_TLS_PSK_IDENTITY_LEN);
1748 zbx_tls_free();
1749 exit(EXIT_FAILURE);
1750 }
1751 }
1752
1753 /******************************************************************************
1754 * *
1755 * Function: zbx_read_psk_file *
1756 * *
1757 * Purpose: *
1758 * read a pre-shared key from a configured file and convert it from *
1759 * textual representation (ASCII hex digit string) to a binary *
1760 * representation (byte string) *
1761 * *
1762 * Comments: *
1763 * Maximum length of PSK hex-digit string is defined by HOST_TLS_PSK_LEN. *
1764 * Currently it is 512 characters, which encodes a 2048-bit PSK and is *
1765 * supported by GnuTLS and OpenSSL libraries (compiled with default *
1766 * parameters). PolarSSL supports up to 256-bit PSK (compiled with *
1767 * default parameters). If the key is longer an error message *
1768 * "ssl_set_psk(): SSL - Bad input parameters to function" will be logged *
1769 * at runtime. *
1770 * *
1771 ******************************************************************************/
zbx_read_psk_file(void)1772 static void zbx_read_psk_file(void)
1773 {
1774 FILE *f;
1775 size_t len;
1776 int len_bin, ret = FAIL;
1777 char buf[HOST_TLS_PSK_LEN_MAX + 2]; /* up to 512 bytes of hex-digits, maybe 1-2 bytes for '\n', */
1778 /* 1 byte for terminating '\0' */
1779 char buf_bin[HOST_TLS_PSK_LEN / 2]; /* up to 256 bytes of binary PSK */
1780
1781 if (NULL == (f = fopen(CONFIG_TLS_PSK_FILE, "r")))
1782 {
1783 zabbix_log(LOG_LEVEL_CRIT, "cannot open file \"%s\": %s", CONFIG_TLS_PSK_FILE, zbx_strerror(errno));
1784 goto out;
1785 }
1786
1787 if (NULL == fgets(buf, (int)sizeof(buf), f))
1788 {
1789 zabbix_log(LOG_LEVEL_CRIT, "cannot read from file \"%s\" or file empty", CONFIG_TLS_PSK_FILE);
1790 goto out;
1791 }
1792
1793 buf[strcspn(buf, "\r\n")] = '\0'; /* discard newline at the end of string */
1794
1795 if (0 == (len = strlen(buf)))
1796 {
1797 zabbix_log(LOG_LEVEL_CRIT, "file \"%s\" is empty", CONFIG_TLS_PSK_FILE);
1798 goto out;
1799 }
1800
1801 if (HOST_TLS_PSK_LEN_MIN > len)
1802 {
1803 zabbix_log(LOG_LEVEL_CRIT, "PSK in file \"%s\" is too short. Minimum is %d hex-digits",
1804 CONFIG_TLS_PSK_FILE, HOST_TLS_PSK_LEN_MIN);
1805 goto out;
1806 }
1807
1808 if (HOST_TLS_PSK_LEN < len)
1809 {
1810 zabbix_log(LOG_LEVEL_CRIT, "PSK in file \"%s\" is too long. Maximum is %d hex-digits",
1811 CONFIG_TLS_PSK_FILE, HOST_TLS_PSK_LEN);
1812 goto out;
1813 }
1814
1815 if (0 >= (len_bin = zbx_psk_hex2bin((unsigned char *)buf, (unsigned char *)buf_bin, sizeof(buf_bin))))
1816 {
1817 zabbix_log(LOG_LEVEL_CRIT, "invalid PSK in file \"%s\"", CONFIG_TLS_PSK_FILE);
1818 goto out;
1819 }
1820
1821 my_psk_len = (size_t)len_bin;
1822 my_psk = zbx_malloc(my_psk, my_psk_len);
1823 memcpy(my_psk, buf_bin, my_psk_len);
1824
1825 ret = SUCCEED;
1826 out:
1827 if (NULL != f && 0 != fclose(f))
1828 {
1829 zabbix_log(LOG_LEVEL_CRIT, "cannot close file \"%s\": %s", CONFIG_TLS_PSK_FILE, zbx_strerror(errno));
1830 ret = FAIL;
1831 }
1832
1833 if (SUCCEED == ret)
1834 return;
1835
1836 zbx_tls_free();
1837 exit(EXIT_FAILURE);
1838 }
1839
1840 #if defined(HAVE_POLARSSL)
1841 /******************************************************************************
1842 * *
1843 * Function: zbx_log_ciphersuites *
1844 * *
1845 * Purpose: write names of enabled mbed TLS ciphersuites into Zabbix log for *
1846 * debugging *
1847 * *
1848 * Parameters: *
1849 * title1 - [IN] name of the calling function *
1850 * title2 - [IN] name of the group of ciphersuites *
1851 * cipher_ids - [IN] list of ciphersuite ids, terminated by 0 *
1852 * *
1853 ******************************************************************************/
zbx_log_ciphersuites(const char * title1,const char * title2,const int * cipher_ids)1854 static void zbx_log_ciphersuites(const char *title1, const char *title2, const int *cipher_ids)
1855 {
1856 if (SUCCEED == ZBX_CHECK_LOG_LEVEL(LOG_LEVEL_DEBUG))
1857 {
1858 char *msg = NULL;
1859 size_t msg_alloc = 0, msg_offset = 0;
1860 const int *p;
1861
1862 zbx_snprintf_alloc(&msg, &msg_alloc, &msg_offset, "%s() %s ciphersuites:", title1, title2);
1863
1864 for (p = cipher_ids; 0 != *p; p++)
1865 zbx_snprintf_alloc(&msg, &msg_alloc, &msg_offset, " %s", ssl_get_ciphersuite_name(*p));
1866
1867 zabbix_log(LOG_LEVEL_DEBUG, "%s", msg);
1868 zbx_free(msg);
1869 }
1870 }
1871 #elif defined(HAVE_GNUTLS)
1872 /******************************************************************************
1873 * *
1874 * Function: zbx_log_ciphersuites *
1875 * *
1876 * Purpose: write names of enabled GnuTLS ciphersuites into Zabbix log for *
1877 * debugging *
1878 * *
1879 * Parameters: *
1880 * title1 - [IN] name of the calling function *
1881 * title2 - [IN] name of the group of ciphersuites *
1882 * ciphers - [IN] list of ciphersuites *
1883 * *
1884 ******************************************************************************/
zbx_log_ciphersuites(const char * title1,const char * title2,gnutls_priority_t ciphers)1885 static void zbx_log_ciphersuites(const char *title1, const char *title2, gnutls_priority_t ciphers)
1886 {
1887 if (SUCCEED == ZBX_CHECK_LOG_LEVEL(LOG_LEVEL_DEBUG))
1888 {
1889 char *msg = NULL;
1890 size_t msg_alloc = 0, msg_offset = 0;
1891 int res;
1892 unsigned int idx = 0, sidx;
1893 const char *name;
1894
1895 zbx_snprintf_alloc(&msg, &msg_alloc, &msg_offset, "%s() %s ciphersuites:", title1, title2);
1896
1897 while (1)
1898 {
1899 if (GNUTLS_E_SUCCESS == (res = gnutls_priority_get_cipher_suite_index(ciphers, idx++, &sidx)))
1900 {
1901 if (NULL != (name = gnutls_cipher_suite_info(sidx, NULL, NULL, NULL, NULL, NULL)))
1902 zbx_snprintf_alloc(&msg, &msg_alloc, &msg_offset, " %s", name);
1903 }
1904 else if (GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE == res)
1905 {
1906 break;
1907 }
1908
1909 /* ignore the 3rd possibility GNUTLS_E_UNKNOWN_CIPHER_SUITE */
1910 /* (see "man gnutls_priority_get_cipher_suite_index") */
1911 }
1912
1913 zabbix_log(LOG_LEVEL_DEBUG, "%s", msg);
1914 zbx_free(msg);
1915 }
1916 }
1917 #elif defined(HAVE_OPENSSL)
1918 /******************************************************************************
1919 * *
1920 * Function: zbx_log_ciphersuites *
1921 * *
1922 * Purpose: write names of enabled OpenSSL ciphersuites into Zabbix log for *
1923 * debugging *
1924 * *
1925 * Parameters: *
1926 * title1 - [IN] name of the calling function *
1927 * title2 - [IN] name of the group of ciphersuites *
1928 * ciphers - [IN] stack of ciphersuites *
1929 * *
1930 ******************************************************************************/
zbx_log_ciphersuites(const char * title1,const char * title2,SSL_CTX * ciphers)1931 static void zbx_log_ciphersuites(const char *title1, const char *title2, SSL_CTX *ciphers)
1932 {
1933 if (SUCCEED == ZBX_CHECK_LOG_LEVEL(LOG_LEVEL_DEBUG))
1934 {
1935 char *msg = NULL;
1936 size_t msg_alloc = 0, msg_offset = 0;
1937 int i, num;
1938 STACK_OF(SSL_CIPHER) *cipher_list;
1939
1940 zbx_snprintf_alloc(&msg, &msg_alloc, &msg_offset, "%s() %s ciphersuites:", title1, title2);
1941
1942 cipher_list = SSL_CTX_get_ciphers(ciphers);
1943 num = sk_SSL_CIPHER_num(cipher_list);
1944
1945 for (i = 0; i < num; i++)
1946 {
1947 zbx_snprintf_alloc(&msg, &msg_alloc, &msg_offset, " %s",
1948 SSL_CIPHER_get_name(sk_SSL_CIPHER_value(cipher_list, i)));
1949 }
1950
1951 zabbix_log(LOG_LEVEL_DEBUG, "%s", msg);
1952 zbx_free(msg);
1953 }
1954 }
1955 #endif
1956
1957 #if defined(HAVE_POLARSSL) || defined(HAVE_GNUTLS)
1958 /******************************************************************************
1959 * *
1960 * Function: zbx_print_rdn_value *
1961 * *
1962 * Purpose: *
1963 * print an RDN (relative distinguished name) value into buffer *
1964 * *
1965 * Parameters: *
1966 * value - [IN] pointer to RDN value *
1967 * len - [IN] number of bytes in the RDN value *
1968 * buf - [OUT] output buffer *
1969 * size - [IN] output buffer size *
1970 * error - [OUT] dynamically allocated memory with error message. *
1971 * Initially '*error' must be NULL. *
1972 * *
1973 * Return value: *
1974 * number of bytes written into 'buf' *
1975 * '*error' is not NULL if an error occurred *
1976 * *
1977 ******************************************************************************/
zbx_print_rdn_value(const unsigned char * value,size_t len,unsigned char * buf,size_t size,char ** error)1978 static size_t zbx_print_rdn_value(const unsigned char *value, size_t len, unsigned char *buf, size_t size,
1979 char **error)
1980 {
1981 const unsigned char *p_in;
1982 unsigned char *p_out, *p_out_end;
1983
1984 p_in = value;
1985 p_out = buf;
1986 p_out_end = buf + size;
1987
1988 while (value + len > p_in)
1989 {
1990 if (0 == (*p_in & 0x80)) /* ASCII */
1991 {
1992 if (0x1f < *p_in && *p_in < 0x7f) /* printable character */
1993 {
1994 if (p_out_end - 1 > p_out)
1995 {
1996 /* According to RFC 4514: */
1997 /* - escape characters '"' (U+0022), '+' U+002B, ',' U+002C, ';' U+003B, */
1998 /* '<' U+003C, '>' U+003E, '\' U+005C anywhere in string. */
1999 /* - escape characters space (' ' U+0020) or number sign ('#' U+0023) at */
2000 /* the beginning of string. */
2001 /* - escape character space (' ' U+0020) at the end of string. */
2002 /* - escape null (U+0000) character anywhere. <--- we do not allow null. */
2003
2004 if ((0x20 == (*p_in & 0x70) && ('"' == *p_in || '+' == *p_in || ',' == *p_in))
2005 || (0x30 == (*p_in & 0x70) && (';' == *p_in || '<' == *p_in ||
2006 '>' == *p_in)) || '\\' == *p_in ||
2007 (' ' == *p_in && (value == p_in || (value + len - 1) == p_in))
2008 || ('#' == *p_in && value == p_in))
2009 {
2010 *p_out++ = '\\';
2011 }
2012 }
2013 else
2014 goto small_buf;
2015
2016 if (p_out_end - 1 > p_out)
2017 *p_out++ = *p_in++;
2018 else
2019 goto small_buf;
2020 }
2021 else if (0 == *p_in)
2022 {
2023 *error = zbx_strdup(*error, "null byte in certificate, could be an attack");
2024 break;
2025 }
2026 else
2027 {
2028 *error = zbx_strdup(*error, "non-printable character in certificate");
2029 break;
2030 }
2031 }
2032 else if (0xc0 == (*p_in & 0xe0)) /* 11000010-11011111 starts a 2-byte sequence */
2033 {
2034 if (p_out_end - 2 > p_out)
2035 {
2036 *p_out++ = *p_in++;
2037 *p_out++ = *p_in++;
2038 }
2039 else
2040 goto small_buf;
2041 }
2042 else if (0xe0 == (*p_in & 0xf0)) /* 11100000-11101111 starts a 3-byte sequence */
2043 {
2044 if (p_out_end - 3 > p_out)
2045 {
2046 *p_out++ = *p_in++;
2047 *p_out++ = *p_in++;
2048 *p_out++ = *p_in++;
2049 }
2050 else
2051 goto small_buf;
2052 }
2053 else if (0xf0 == (*p_in & 0xf8)) /* 11110000-11110100 starts a 4-byte sequence */
2054 {
2055 if (p_out_end - 4 > p_out)
2056 {
2057 *p_out++ = *p_in++;
2058 *p_out++ = *p_in++;
2059 *p_out++ = *p_in++;
2060 *p_out++ = *p_in++;
2061 }
2062 else
2063 goto small_buf;
2064 }
2065 else /* not a valid UTF-8 character */
2066 {
2067 *error = zbx_strdup(*error, "invalid UTF-8 character");
2068 break;
2069 }
2070 }
2071
2072 *p_out = '\0';
2073
2074 return (size_t)(p_out - buf);
2075 small_buf:
2076 *p_out = '\0';
2077 *error = zbx_strdup(*error, "output buffer too small");
2078
2079 return (size_t)(p_out - buf);
2080 }
2081 #endif
2082
2083 #if defined(HAVE_POLARSSL)
2084 /******************************************************************************
2085 * *
2086 * Function: zbx_x509_dn_gets *
2087 * *
2088 * Purpose: *
2089 * Print distinguished name (i.e. issuer, subject) into buffer. Intended *
2090 * to use as an alternative to PolarSSL x509_dn_gets() to meet *
2091 * application needs. *
2092 * *
2093 * Parameters: *
2094 * dn - [IN] pointer to distinguished name *
2095 * buf - [OUT] output buffer *
2096 * size - [IN] output buffer size *
2097 * error - [OUT] dynamically allocated memory with error message *
2098 * *
2099 * Return value: *
2100 * SUCCEED - no errors, FAIL - an error occurred *
2101 * *
2102 * Comments: *
2103 * This function is derived from PolarSSL x509_dn_gets() and heavily *
2104 * modified to print RDNs in reverse order, to print UTF-8 characters and *
2105 * non-printable characters in a different way than original *
2106 * x509_dn_gets() does and to return error messages. *
2107 * Multi-valued RDNs are not supported currently. *
2108 * *
2109 ******************************************************************************/
zbx_x509_dn_gets(const x509_name * dn,char * buf,size_t size,char ** error)2110 static int zbx_x509_dn_gets(const x509_name *dn, char *buf, size_t size, char **error)
2111 {
2112 const x509_name *node, *stop_node = NULL;
2113 const char *short_name = NULL;
2114 char *p, *p_end;
2115
2116 /* We need to traverse a linked list of RDNs and print them out in reverse order (recommended by RFC 4514). */
2117 /* The number of RDNs in DN is expected to be small (typically 4-5, sometimes up to 8). For such a small list */
2118 /* we simply traverse it multiple times for getting elements in reverse order. */
2119
2120 p = buf;
2121 p_end = buf + size;
2122
2123 while (1)
2124 {
2125 node = dn;
2126
2127 while (stop_node != node->next)
2128 node = node->next;
2129
2130 if (NULL != node->oid.p)
2131 {
2132 if (buf != p) /* not the first RDN */
2133 {
2134 if (p_end - 1 == p)
2135 goto small_buf;
2136
2137 p += zbx_strlcpy(p, ",", (size_t)(p_end - p)); /* separator between RDNs */
2138 }
2139
2140 /* write attribute name */
2141
2142 if (0 == oid_get_attr_short_name(&node->oid, &short_name))
2143 {
2144 if (p_end - 1 == p)
2145 goto small_buf;
2146
2147 p += zbx_strlcpy(p, short_name, (size_t)(p_end - p));
2148 }
2149 else /* unknown OID name, write in numerical form */
2150 {
2151 int res;
2152
2153 if (p_end - 1 == p)
2154 goto small_buf;
2155
2156 if (0 < (res = oid_get_numeric_string(p, (size_t)(p_end - p), &node->oid)))
2157 p += (size_t)res;
2158 else
2159 goto small_buf;
2160 }
2161
2162 if (p_end - 1 == p)
2163 goto small_buf;
2164
2165 p += zbx_strlcpy(p, "=", (size_t)(p_end - p));
2166
2167 /* write attribute value */
2168
2169 if (p_end - 1 == p)
2170 goto small_buf;
2171
2172 p += zbx_print_rdn_value(node->val.p, node->val.len, (unsigned char *)p, (size_t)(p_end - p),
2173 error);
2174
2175 if (NULL != *error)
2176 break;
2177 }
2178
2179 if (dn->next != stop_node)
2180 stop_node = node;
2181 else
2182 break;
2183 }
2184
2185 if (NULL == *error)
2186 return SUCCEED;
2187 else
2188 return FAIL;
2189 small_buf:
2190 *error = zbx_strdup(*error, "output buffer too small");
2191
2192 return FAIL;
2193 }
2194 #elif defined(HAVE_GNUTLS)
2195 /******************************************************************************
2196 * *
2197 * Function: zbx_x509_dn_gets *
2198 * *
2199 * Purpose: *
2200 * Print distinguished name (i.e. issuer, subject) into buffer. Intended *
2201 * to use as an alternative to GnuTLS gnutls_x509_crt_get_issuer_dn() and *
2202 * gnutls_x509_crt_get_dn() to meet application needs. *
2203 * *
2204 * Parameters: *
2205 * dn - [IN] pointer to distinguished name *
2206 * buf - [OUT] output buffer *
2207 * size - [IN] output buffer size *
2208 * error - [OUT] dynamically allocated memory with error message *
2209 * *
2210 * Return value: *
2211 * SUCCEED - no errors, FAIL - an error occurred *
2212 * *
2213 * Comments: *
2214 * Multi-valued RDNs are not supported currently (only the first value is *
2215 * printed). *
2216 * *
2217 ******************************************************************************/
zbx_x509_dn_gets(const gnutls_x509_dn_t dn,char * buf,size_t size,char ** error)2218 static int zbx_x509_dn_gets(const gnutls_x509_dn_t dn, char *buf, size_t size, char **error)
2219 {
2220 #define ZBX_AVA_BUF_SIZE 20 /* hopefully no more than 20 RDNs */
2221
2222 int res, i = 0, i_max, ava_dyn_size;
2223 char *p, *p_end;
2224 gnutls_x509_ava_st *ava, *ava_dyn = NULL;
2225 char oid_str[128]; /* size equal to MAX_OID_SIZE, internally defined in GnuTLS */
2226 gnutls_x509_ava_st ava_stat[ZBX_AVA_BUF_SIZE];
2227
2228 /* Find index of the last RDN in distinguished name. Remember pointers to RDNs to minimize calling of */
2229 /* gnutls_x509_dn_get_rdn_ava() as it seems a bit expensive. */
2230
2231 while (1)
2232 {
2233 if (ZBX_AVA_BUF_SIZE > i) /* most common case: small number of RDNs, fits in fixed buffer */
2234 {
2235 ava = &ava_stat[i];
2236 }
2237 else if (NULL == ava_dyn) /* fixed buffer full, copy data to dynamic buffer */
2238 {
2239 ava_dyn_size = 2 * ZBX_AVA_BUF_SIZE;
2240 ava_dyn = zbx_malloc(NULL, (size_t)ava_dyn_size * sizeof(gnutls_x509_ava_st));
2241
2242 memcpy(ava_dyn, ava_stat, ZBX_AVA_BUF_SIZE * sizeof(gnutls_x509_ava_st));
2243 ava = ava_dyn + ZBX_AVA_BUF_SIZE;
2244 }
2245 else if (ava_dyn_size > i) /* fits in dynamic buffer */
2246 {
2247 ava = ava_dyn + i;
2248 }
2249 else /* expand dynamic buffer */
2250 {
2251 ava_dyn_size += ZBX_AVA_BUF_SIZE;
2252 ava_dyn = zbx_realloc(ava_dyn, (size_t)ava_dyn_size * sizeof(gnutls_x509_ava_st));
2253 ava = ava_dyn + i;
2254 }
2255
2256 if (0 == (res = gnutls_x509_dn_get_rdn_ava(dn, i, 0, ava))) /* RDN with index 'i' exists */
2257 {
2258 i++;
2259 }
2260 else if (GNUTLS_E_ASN1_ELEMENT_NOT_FOUND == res)
2261 {
2262 i_max = i;
2263 break;
2264 }
2265 else
2266 {
2267 *error = zbx_dsprintf(*error, "zbx_x509_dn_gets(): gnutls_x509_dn_get_rdn_ava() failed: %d %s",
2268 res, gnutls_strerror(res));
2269 zbx_free(ava_dyn);
2270 return FAIL;
2271 }
2272 }
2273
2274 /* "print" RDNs in reverse order (recommended by RFC 4514) */
2275
2276 if (NULL == ava_dyn)
2277 ava = &ava_stat[0];
2278 else
2279 ava = ava_dyn;
2280
2281 p = buf;
2282 p_end = buf + size;
2283
2284 for (i = i_max - 1, ava += i; i >= 0; i--, ava--)
2285 {
2286 if (sizeof(oid_str) <= ava->oid.size)
2287 {
2288 THIS_SHOULD_NEVER_HAPPEN;
2289 zbx_free(ava_dyn);
2290 return FAIL;
2291 }
2292
2293 memcpy(oid_str, ava->oid.data, ava->oid.size);
2294 oid_str[ava->oid.size] = '\0';
2295
2296 if (buf != p) /* not the first RDN being printed */
2297 {
2298 if (p_end - 1 == p)
2299 goto small_buf;
2300
2301 p += zbx_strlcpy(p, ",", (size_t)(p_end - p)); /* separator between RDNs */
2302 }
2303
2304 /* write attribute name */
2305
2306 if (p_end - 1 == p)
2307 goto small_buf;
2308
2309 p += zbx_strlcpy(p, gnutls_x509_dn_oid_name(oid_str, GNUTLS_X509_DN_OID_RETURN_OID),
2310 (size_t)(p_end - p));
2311
2312 if (p_end - 1 == p)
2313 goto small_buf;
2314
2315 p += zbx_strlcpy(p, "=", (size_t)(p_end - p));
2316
2317 /* write attribute value */
2318
2319 if (p_end - 1 == p)
2320 goto small_buf;
2321
2322 p += zbx_print_rdn_value(ava->value.data, ava->value.size, (unsigned char *)p, (size_t)(p_end - p),
2323 error);
2324
2325 if (NULL != *error)
2326 break;
2327 }
2328
2329 zbx_free(ava_dyn);
2330
2331 if (NULL == *error)
2332 return SUCCEED;
2333 else
2334 return FAIL;
2335 small_buf:
2336 zbx_free(ava_dyn);
2337 *error = zbx_strdup(*error, "output buffer too small");
2338
2339 return FAIL;
2340
2341 #undef ZBX_AVA_BUF_SIZE
2342 }
2343 #elif defined(HAVE_OPENSSL)
2344 /******************************************************************************
2345 * *
2346 * Function: zbx_x509_dn_gets *
2347 * *
2348 * Purpose: *
2349 * Print distinguished name (i.e. issuer, subject) into buffer. Intended *
2350 * to use as an alternative to OpenSSL X509_NAME_oneline() and to meet *
2351 * application needs. *
2352 * *
2353 * Parameters: *
2354 * dn - [IN] pointer to distinguished name *
2355 * buf - [OUT] output buffer *
2356 * size - [IN] output buffer size *
2357 * error - [OUT] dynamically allocated memory with error message *
2358 * *
2359 * Return value: *
2360 * SUCCEED - no errors, FAIL - an error occurred *
2361 * *
2362 * Comments: *
2363 * Examples often use OpenSSL X509_NAME_oneline() to print certificate *
2364 * issuer and subject into memory buffers but it is a legacy function and *
2365 * strongly discouraged in new applications. So, we have to use functions *
2366 * writing into BIOs and then turn results into memory buffers. *
2367 * *
2368 ******************************************************************************/
zbx_x509_dn_gets(X509_NAME * dn,char * buf,size_t size,char ** error)2369 static int zbx_x509_dn_gets(X509_NAME *dn, char *buf, size_t size, char **error)
2370 {
2371 BIO *bio;
2372 const char *data;
2373 size_t len;
2374 int ret = FAIL;
2375
2376 if (NULL == (bio = BIO_new(BIO_s_mem())))
2377 {
2378 *error = zbx_strdup(*error, "cannot create BIO");
2379 goto out;
2380 }
2381
2382 /* XN_FLAG_RFC2253 - RFC 2253 is outdated, it was replaced by RFC 4514 "Lightweight Directory Access Protocol */
2383 /* (LDAP): String Representation of Distinguished Names" */
2384
2385 if (0 > X509_NAME_print_ex(bio, dn, 0, XN_FLAG_RFC2253 & ~ASN1_STRFLGS_ESC_MSB))
2386 {
2387 *error = zbx_strdup(*error, "cannot print distinguished name");
2388 goto out;
2389 }
2390
2391 if (size <= (len = (size_t)BIO_get_mem_data(bio, &data)))
2392 {
2393 *error = zbx_strdup(*error, "output buffer too small");
2394 goto out;
2395 }
2396
2397 zbx_strlcpy(buf, data, len + 1);
2398 ret = SUCCEED;
2399 out:
2400 if (NULL != bio)
2401 {
2402 /* ensure that associated memory buffer will be freed by BIO_vfree() */
2403 (void)BIO_set_close(bio, BIO_CLOSE);
2404 BIO_vfree(bio);
2405 }
2406
2407 return ret;
2408 }
2409 #endif
2410
2411 #if defined(HAVE_GNUTLS)
2412 /******************************************************************************
2413 * *
2414 * Function: zbx_get_peer_cert *
2415 * *
2416 * Purpose: get peer certificate from session *
2417 * *
2418 * Parameters: *
2419 * session - [IN] session context *
2420 * error - [OUT] dynamically allocated memory with error message *
2421 * *
2422 * Return value: *
2423 * pointer to peer certificate - success *
2424 * NULL - an error occurred *
2425 * *
2426 * Comments: *
2427 * In case of success it is a responsibility of caller to deallocate *
2428 * the instance of certificate using gnutls_x509_crt_deinit(). *
2429 * *
2430 ******************************************************************************/
zbx_get_peer_cert(const gnutls_session_t session,char ** error)2431 static gnutls_x509_crt_t zbx_get_peer_cert(const gnutls_session_t session, char **error)
2432 {
2433 const char *__function_name = "zbx_get_peer_cert";
2434
2435 if (GNUTLS_CRT_X509 == gnutls_certificate_type_get(session))
2436 {
2437 int res;
2438 unsigned int cert_list_size = 0;
2439 const gnutls_datum_t *cert_list;
2440 gnutls_x509_crt_t cert;
2441
2442 if (NULL == (cert_list = gnutls_certificate_get_peers(session, &cert_list_size)))
2443 {
2444 *error = zbx_dsprintf(*error, "%s(): gnutls_certificate_get_peers() returned NULL",
2445 __function_name);
2446 return NULL;
2447 }
2448
2449 if (0 == cert_list_size)
2450 {
2451 *error = zbx_dsprintf(*error, "%s(): gnutls_certificate_get_peers() returned 0 certificates",
2452 __function_name);
2453 return NULL;
2454 }
2455
2456 if (GNUTLS_E_SUCCESS != (res = gnutls_x509_crt_init(&cert)))
2457 {
2458 *error = zbx_dsprintf(*error, "%s(): gnutls_x509_crt_init() failed: %d %s", __function_name,
2459 res, gnutls_strerror(res));
2460 return NULL;
2461 }
2462
2463 /* the 1st element of the list is peer certificate */
2464
2465 if (GNUTLS_E_SUCCESS != (res = gnutls_x509_crt_import(cert, &cert_list[0], GNUTLS_X509_FMT_DER)))
2466 {
2467 *error = zbx_dsprintf(*error, "%s(): gnutls_x509_crt_import() failed: %d %s", __function_name,
2468 res, gnutls_strerror(res));
2469 gnutls_x509_crt_deinit(cert);
2470 return NULL;
2471 }
2472
2473 return cert; /* success */
2474 }
2475 else
2476 {
2477 *error = zbx_dsprintf(*error, "%s(): not an X509 certificate", __function_name);
2478 return NULL;
2479 }
2480 }
2481 #endif
2482
2483 /******************************************************************************
2484 * *
2485 * Function: zbx_log_peer_cert *
2486 * *
2487 * Purpose: write peer certificate information into Zabbix log for debugging *
2488 * *
2489 * Parameters: *
2490 * function_name - [IN] caller function name *
2491 * tls_ctx - [IN] TLS context *
2492 * *
2493 ******************************************************************************/
zbx_log_peer_cert(const char * function_name,const zbx_tls_context_t * tls_ctx)2494 static void zbx_log_peer_cert(const char *function_name, const zbx_tls_context_t *tls_ctx)
2495 {
2496 char *error = NULL;
2497 #if defined(HAVE_POLARSSL)
2498 const x509_crt *cert;
2499 char issuer[HOST_TLS_ISSUER_LEN_MAX], subject[HOST_TLS_SUBJECT_LEN_MAX], serial[128];
2500 #elif defined(HAVE_GNUTLS)
2501 gnutls_x509_crt_t cert;
2502 int res;
2503 gnutls_datum_t cert_print;
2504 #elif defined(HAVE_OPENSSL)
2505 X509 *cert;
2506 char issuer[HOST_TLS_ISSUER_LEN_MAX], subject[HOST_TLS_SUBJECT_LEN_MAX];
2507 #endif
2508
2509 if (SUCCEED != ZBX_CHECK_LOG_LEVEL(LOG_LEVEL_DEBUG))
2510 return;
2511 #if defined(HAVE_POLARSSL)
2512 if (NULL == (cert = ssl_get_peer_cert(tls_ctx->ctx)))
2513 {
2514 zabbix_log(LOG_LEVEL_DEBUG, "%s() cannot obtain peer certificate", function_name);
2515 }
2516 else if (SUCCEED != zbx_x509_dn_gets(&cert->issuer, issuer, sizeof(issuer), &error))
2517 {
2518 zabbix_log(LOG_LEVEL_DEBUG, "%s() cannot obtain peer certificate issuer: %s", function_name, error);
2519 }
2520 else if (SUCCEED != zbx_x509_dn_gets(&cert->subject, subject, sizeof(subject), &error))
2521 {
2522 zabbix_log(LOG_LEVEL_DEBUG, "%s() cannot obtain peer certificate subject: %s", function_name, error);
2523 }
2524 else if (0 > x509_serial_gets(serial, sizeof(serial), &cert->serial))
2525 {
2526 zabbix_log(LOG_LEVEL_DEBUG, "%s() cannot obtain peer certificate serial", function_name);
2527 }
2528 else
2529 {
2530 zabbix_log(LOG_LEVEL_DEBUG, "%s() peer certificate issuer:\"%s\" subject:\"%s\" serial:\"%s\"",
2531 function_name, issuer, subject, serial);
2532 }
2533 #elif defined(HAVE_GNUTLS)
2534 if (NULL == (cert = zbx_get_peer_cert(tls_ctx->ctx, &error)))
2535 {
2536 zabbix_log(LOG_LEVEL_DEBUG, "%s(): cannot obtain peer certificate: %s", function_name, error);
2537 }
2538 else if (GNUTLS_E_SUCCESS != (res = gnutls_x509_crt_print(cert, GNUTLS_CRT_PRINT_ONELINE, &cert_print)))
2539 {
2540 zabbix_log(LOG_LEVEL_DEBUG, "%s(): gnutls_x509_crt_print() failed: %d %s", function_name, res,
2541 gnutls_strerror(res));
2542 }
2543 else
2544 {
2545 zabbix_log(LOG_LEVEL_DEBUG, "%s(): peer certificate: %s", function_name, cert_print.data);
2546 gnutls_free(cert_print.data);
2547 }
2548
2549 if (NULL != cert)
2550 gnutls_x509_crt_deinit(cert);
2551 #elif defined(HAVE_OPENSSL)
2552 if (NULL == (cert = SSL_get_peer_certificate(tls_ctx->ctx)))
2553 {
2554 zabbix_log(LOG_LEVEL_DEBUG, "%s() cannot obtain peer certificate", function_name);
2555 }
2556 else if (SUCCEED != zbx_x509_dn_gets(X509_get_issuer_name(cert), issuer, sizeof(issuer), &error))
2557 {
2558 zabbix_log(LOG_LEVEL_DEBUG, "%s() cannot obtain peer certificate issuer: %s", function_name, error);
2559 }
2560 else if (SUCCEED != zbx_x509_dn_gets(X509_get_subject_name(cert), subject, sizeof(subject), &error))
2561 {
2562 zabbix_log(LOG_LEVEL_DEBUG, "%s() cannot obtain peer certificate subject: %s", function_name, error);
2563 }
2564 else
2565 {
2566 zabbix_log(LOG_LEVEL_DEBUG, "%s() peer certificate issuer:\"%s\" subject:\"%s\"",
2567 function_name, issuer, subject);
2568 }
2569
2570 if (NULL != cert)
2571 X509_free(cert);
2572 #endif
2573 zbx_free(error);
2574 }
2575
2576 #if defined(HAVE_GNUTLS)
2577 /******************************************************************************
2578 * *
2579 * Function: zbx_verify_peer_cert *
2580 * *
2581 * Purpose: basic verification of peer certificate *
2582 * *
2583 * Return value: *
2584 * SUCCEED - verification successful *
2585 * FAIL - invalid certificate or an error occurred *
2586 * *
2587 ******************************************************************************/
zbx_verify_peer_cert(const gnutls_session_t session,char ** error)2588 static int zbx_verify_peer_cert(const gnutls_session_t session, char **error)
2589 {
2590 const char *__function_name = "zbx_verify_peer_cert";
2591 int res;
2592 unsigned int status;
2593 gnutls_datum_t status_print;
2594
2595 if (GNUTLS_E_SUCCESS != (res = gnutls_certificate_verify_peers2(session, &status)))
2596 {
2597 *error = zbx_dsprintf(*error, "%s(): gnutls_certificate_verify_peers2() failed: %d %s",
2598 __function_name, res, gnutls_strerror(res));
2599 return FAIL;
2600 }
2601
2602 if (GNUTLS_E_SUCCESS != (res = gnutls_certificate_verification_status_print(status,
2603 gnutls_certificate_type_get(session), &status_print, 0)))
2604 {
2605 *error = zbx_dsprintf(*error, "%s(): gnutls_certificate_verification_status_print() failed: %d"
2606 " %s", __function_name, res, gnutls_strerror(res));
2607 return FAIL;
2608 }
2609
2610 if (0 != status)
2611 *error = zbx_dsprintf(*error, "invalid peer certificate: %s", status_print.data);
2612
2613 gnutls_free(status_print.data);
2614
2615 if (0 == status)
2616 return SUCCEED;
2617 else
2618 return FAIL;
2619 }
2620 #endif
2621
2622 /******************************************************************************
2623 * *
2624 * Function: zbx_verify_issuer_subject *
2625 * *
2626 * Purpose: *
2627 * verify peer certificate issuer and subject of the given TLS context *
2628 * *
2629 * Parameters: *
2630 * tls_ctx - [IN] TLS context to verify *
2631 * issuer - [IN] required issuer (ignore if NULL or empty string) *
2632 * subject - [IN] required subject (ignore if NULL or empty string) *
2633 * error - [OUT] dynamically allocated memory with error message *
2634 * *
2635 * Return value: *
2636 * SUCCEED or FAIL *
2637 * *
2638 ******************************************************************************/
zbx_verify_issuer_subject(const zbx_tls_context_t * tls_ctx,const char * issuer,const char * subject,char ** error)2639 static int zbx_verify_issuer_subject(const zbx_tls_context_t *tls_ctx, const char *issuer, const char *subject,
2640 char **error)
2641 {
2642 char tls_issuer[HOST_TLS_ISSUER_LEN_MAX], tls_subject[HOST_TLS_SUBJECT_LEN_MAX];
2643 int issuer_mismatch = 0, subject_mismatch = 0;
2644 size_t error_alloc = 0, error_offset = 0;
2645 #if defined(HAVE_POLARSSL)
2646 const x509_crt *cert;
2647 #elif defined(HAVE_GNUTLS)
2648 gnutls_x509_crt_t cert;
2649 gnutls_x509_dn_t dn;
2650 int res;
2651 #elif defined(HAVE_OPENSSL)
2652 X509 *cert;
2653 #endif
2654
2655 if ((NULL == issuer || '\0' == *issuer) && (NULL == subject || '\0' == *subject))
2656 return SUCCEED;
2657
2658 tls_issuer[0] = '\0';
2659 tls_subject[0] = '\0';
2660
2661 #if defined(HAVE_POLARSSL)
2662 if (NULL == (cert = ssl_get_peer_cert(tls_ctx->ctx)))
2663 {
2664 *error = zbx_strdup(*error, "cannot obtain peer certificate");
2665 return FAIL;
2666 }
2667
2668 if (NULL != issuer && '\0' != *issuer)
2669 {
2670 if (SUCCEED != zbx_x509_dn_gets(&cert->issuer, tls_issuer, sizeof(tls_issuer), error))
2671 return FAIL;
2672 }
2673
2674 if (NULL != subject && '\0' != *subject)
2675 {
2676 if (SUCCEED != zbx_x509_dn_gets(&cert->subject, tls_subject, sizeof(tls_subject), error))
2677 return FAIL;
2678 }
2679 #elif defined(HAVE_GNUTLS)
2680 if (NULL == (cert = zbx_get_peer_cert(tls_ctx->ctx, error)))
2681 return FAIL;
2682
2683 if (NULL != issuer && '\0' != *issuer)
2684 {
2685 if (0 != (res = gnutls_x509_crt_get_issuer(cert, &dn)))
2686 {
2687 *error = zbx_dsprintf(*error, "gnutls_x509_crt_get_issuer() failed: %d %s", res,
2688 gnutls_strerror(res));
2689 return FAIL;
2690 }
2691
2692 if (SUCCEED != zbx_x509_dn_gets(dn, tls_issuer, sizeof(tls_issuer), error))
2693 return FAIL;
2694 }
2695
2696 if (NULL != subject && '\0' != *subject)
2697 {
2698 if (0 != (res = gnutls_x509_crt_get_subject(cert, &dn)))
2699 {
2700 *error = zbx_dsprintf(*error, "gnutls_x509_crt_get_subject() failed: %d %s", res,
2701 gnutls_strerror(res));
2702 return FAIL;
2703 }
2704
2705 if (SUCCEED != zbx_x509_dn_gets(dn, tls_subject, sizeof(tls_subject), error))
2706 return FAIL;
2707 }
2708
2709 gnutls_x509_crt_deinit(cert);
2710 #elif defined(HAVE_OPENSSL)
2711 if (NULL == (cert = SSL_get_peer_certificate(tls_ctx->ctx)))
2712 {
2713 *error = zbx_strdup(*error, "cannot obtain peer certificate");
2714 return FAIL;
2715 }
2716
2717 if (NULL != issuer && '\0' != *issuer)
2718 {
2719 if (SUCCEED != zbx_x509_dn_gets(X509_get_issuer_name(cert), tls_issuer, sizeof(tls_issuer), error))
2720 return FAIL;
2721 }
2722
2723 if (NULL != subject && '\0' != *subject)
2724 {
2725 if (SUCCEED != zbx_x509_dn_gets(X509_get_subject_name(cert), tls_subject, sizeof(tls_subject), error))
2726 return FAIL;
2727 }
2728
2729 X509_free(cert);
2730 #endif
2731 /* simplified match, not compliant with RFC 4517, 4518 */
2732
2733 if (NULL != issuer && '\0' != *issuer)
2734 issuer_mismatch = strcmp(tls_issuer, issuer);
2735
2736 if (NULL != subject && '\0' != *subject)
2737 subject_mismatch = strcmp(tls_subject, subject);
2738
2739 if (0 == issuer_mismatch && 0 == subject_mismatch)
2740 return SUCCEED;
2741
2742 if (0 != issuer_mismatch)
2743 {
2744 zbx_snprintf_alloc(error, &error_alloc, &error_offset, "issuer: peer: \"%s\", required: \"%s\"",
2745 tls_issuer, issuer);
2746 }
2747
2748 if (0 != subject_mismatch)
2749 {
2750 if (0 != issuer_mismatch)
2751 zbx_strcpy_alloc(error, &error_alloc, &error_offset, ", ");
2752
2753 zbx_snprintf_alloc(error, &error_alloc, &error_offset, "subject: peer: \"%s\", required: \"%s\"",
2754 tls_subject, subject);
2755 }
2756
2757 return FAIL;
2758 }
2759
2760 /******************************************************************************
2761 * *
2762 * Function: zbx_check_server_issuer_subject *
2763 * *
2764 * Purpose: *
2765 * check server certificate issuer and subject (for passive proxies and *
2766 * agent passive checks) *
2767 * *
2768 * Parameters: *
2769 * sock - [IN] certificate to verify *
2770 * error - [OUT] dynamically allocated memory with error message *
2771 * *
2772 * Return value: *
2773 * SUCCEED or FAIL *
2774 * *
2775 ******************************************************************************/
zbx_check_server_issuer_subject(zbx_socket_t * sock,char ** error)2776 int zbx_check_server_issuer_subject(zbx_socket_t *sock, char **error)
2777 {
2778 zbx_tls_conn_attr_t attr;
2779
2780 if (SUCCEED != zbx_tls_get_attr_cert(sock, &attr))
2781 {
2782 THIS_SHOULD_NEVER_HAPPEN;
2783
2784 *error = zbx_dsprintf(*error, "cannot get connection attributes for connection from %s", sock->peer);
2785 return FAIL;
2786 }
2787
2788 /* simplified match, not compliant with RFC 4517, 4518 */
2789 if (NULL != CONFIG_TLS_SERVER_CERT_ISSUER && 0 != strcmp(CONFIG_TLS_SERVER_CERT_ISSUER, attr.issuer))
2790 {
2791 *error = zbx_dsprintf(*error, "certificate issuer does not match for %s", sock->peer);
2792 return FAIL;
2793 }
2794
2795 /* simplified match, not compliant with RFC 4517, 4518 */
2796 if (NULL != CONFIG_TLS_SERVER_CERT_SUBJECT && 0 != strcmp(CONFIG_TLS_SERVER_CERT_SUBJECT, attr.subject))
2797 {
2798 *error = zbx_dsprintf(*error, "certificate subject does not match for %s", sock->peer);
2799 return FAIL;
2800 }
2801
2802 return SUCCEED;
2803 }
2804
2805 /******************************************************************************
2806 * *
2807 * Function: zbx_tls_library_init *
2808 * *
2809 * Purpose: initialize TLS library, log library version *
2810 * *
2811 * Comments: *
2812 * Some crypto libraries require initialization. On Unix the *
2813 * initialization is done separately in each child process which uses *
2814 * crypto libraries. On MS Windows it is done in the first thread. *
2815 * *
2816 * Flag 'init_done' is used to prevent library deinitialzation on exit if *
2817 * it was not yet initialized (can happen if termination signal is *
2818 * received). *
2819 * *
2820 ******************************************************************************/
zbx_tls_library_init(void)2821 static void zbx_tls_library_init(void)
2822 {
2823 #if defined(HAVE_POLARSSL)
2824 zabbix_log(LOG_LEVEL_DEBUG, "mbed TLS library (version %s)", POLARSSL_VERSION_STRING_FULL);
2825 #elif defined(HAVE_GNUTLS)
2826 if (GNUTLS_E_SUCCESS != gnutls_global_init())
2827 {
2828 zabbix_log(LOG_LEVEL_CRIT, "cannot initialize GnuTLS library");
2829 exit(EXIT_FAILURE);
2830 }
2831
2832 init_done = 1;
2833
2834 zabbix_log(LOG_LEVEL_DEBUG, "GnuTLS library (version %s) initialized", gnutls_check_version(NULL));
2835 #elif defined(HAVE_OPENSSL)
2836 #if !defined(LIBRESSL_VERSION_NUMBER) /* LibreSSL does not require initialization */
2837 if (1 != zbx_openssl_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS | OPENSSL_INIT_LOAD_CRYPTO_STRINGS, NULL))
2838 {
2839 zabbix_log(LOG_LEVEL_CRIT, "cannot initialize OpenSSL library");
2840 exit(EXIT_FAILURE);
2841 }
2842 #endif
2843 init_done = 1;
2844
2845 zabbix_log(LOG_LEVEL_DEBUG, "OpenSSL library (version %s) initialized", OpenSSL_version(OPENSSL_VERSION));
2846 #endif
2847 }
2848
2849 /******************************************************************************
2850 * *
2851 * Function: zbx_tls_library_deinit *
2852 * *
2853 * Purpose: deinitialize TLS library *
2854 * *
2855 ******************************************************************************/
zbx_tls_library_deinit(void)2856 void zbx_tls_library_deinit(void)
2857 {
2858 #if defined(HAVE_GNUTLS)
2859 if (1 == init_done)
2860 {
2861 init_done = 0;
2862 gnutls_global_deinit();
2863 }
2864 #elif defined(HAVE_OPENSSL)
2865 if (1 == init_done)
2866 {
2867 init_done = 0;
2868 OPENSSL_cleanup();
2869 }
2870 #endif
2871 }
2872
2873 /******************************************************************************
2874 * *
2875 * Function: zbx_tls_init_parent *
2876 * *
2877 * Purpose: initialize TLS library in a parent process *
2878 * *
2879 ******************************************************************************/
zbx_tls_init_parent(void)2880 void zbx_tls_init_parent(void)
2881 {
2882 #if defined(_WINDOWS)
2883 zbx_tls_library_init(); /* on MS Windows initialize crypto libraries in parent thread */
2884 #endif
2885 }
2886
2887 /******************************************************************************
2888 * *
2889 * Function: zbx_tls_init_child *
2890 * *
2891 * Purpose: read available configuration parameters and initialize TLS *
2892 * library in a child process *
2893 * *
2894 ******************************************************************************/
2895 #if defined(HAVE_POLARSSL)
zbx_tls_init_child(void)2896 void zbx_tls_init_child(void)
2897 {
2898 const char *__function_name = "zbx_tls_init_child";
2899 int res;
2900 unsigned char pers[64]; /* personalization string obtained from SHA-512 in SHA-384 mode */
2901 #ifndef _WINDOWS
2902 sigset_t mask, orig_mask;
2903 #endif
2904 zabbix_log(LOG_LEVEL_DEBUG, "In %s()", __function_name);
2905
2906 #ifndef _WINDOWS
2907 /* Invalid TLS parameters will cause exit. Once one process exits the parent process will send SIGHUP to */
2908 /* child processes which may be on their way to exit on their own - do not interrupt them, block signal */
2909 /* SIGHUP and unblock it when TLS parameters are good and libraries are initialized. */
2910 sigemptyset(&mask);
2911 sigaddset(&mask, SIGTERM);
2912 sigaddset(&mask, SIGHUP);
2913 sigaddset(&mask, SIGUSR2);
2914 sigaddset(&mask, SIGQUIT);
2915 sigprocmask(SIG_BLOCK, &mask, &orig_mask);
2916
2917 zbx_tls_library_init(); /* on Unix initialize crypto libraries in child processes */
2918 #endif
2919 /* 'TLSCAFile' parameter (in zabbix_server.conf, zabbix_proxy.conf, zabbix_agentd.conf). */
2920 if (NULL != CONFIG_TLS_CA_FILE)
2921 {
2922 ca_cert = zbx_malloc(ca_cert, sizeof(x509_crt));
2923 x509_crt_init(ca_cert);
2924
2925 if (0 != (res = x509_crt_parse_file(ca_cert, CONFIG_TLS_CA_FILE)))
2926 {
2927 if (0 > res)
2928 {
2929 zbx_tls_error_msg(res, "", &err_msg);
2930 zabbix_log(LOG_LEVEL_CRIT, "cannot parse CA certificate(s) in file \"%s\": %s",
2931 CONFIG_TLS_CA_FILE, err_msg);
2932 zbx_free(err_msg);
2933 }
2934 else
2935 {
2936 zabbix_log(LOG_LEVEL_CRIT, "cannot parse %d CA certificate(s) in file \"%s\"", res,
2937 CONFIG_TLS_CA_FILE);
2938 }
2939
2940 zbx_tls_free();
2941 exit(EXIT_FAILURE);
2942 }
2943
2944 zabbix_log(LOG_LEVEL_DEBUG, "%s() loaded CA certificate(s) from file \"%s\"", __function_name,
2945 CONFIG_TLS_CA_FILE);
2946 }
2947
2948 /* 'TLSCRLFile' parameter (in zabbix_server.conf, zabbix_proxy.conf, zabbix_agentd.conf). */
2949 /* Load CRL (certificate revocation list) file. */
2950 if (NULL != CONFIG_TLS_CRL_FILE)
2951 {
2952 crl = zbx_malloc(crl, sizeof(x509_crl));
2953 x509_crl_init(crl);
2954
2955 if (0 != (res = x509_crl_parse_file(crl, CONFIG_TLS_CRL_FILE)))
2956 {
2957 zbx_tls_error_msg(res, "", &err_msg);
2958 zabbix_log(LOG_LEVEL_CRIT, "cannot parse CRL file \"%s\": %s", CONFIG_TLS_CRL_FILE, err_msg);
2959 zbx_free(err_msg);
2960
2961 zbx_tls_free();
2962 exit(EXIT_FAILURE);
2963 }
2964
2965 zabbix_log(LOG_LEVEL_DEBUG, "%s() loaded CRL(s) from file \"%s\"", __function_name,
2966 CONFIG_TLS_CRL_FILE);
2967 }
2968
2969 /* 'TLSCertFile' parameter (in zabbix_server.conf, zabbix_proxy.conf, zabbix_agentd.conf). */
2970 /* Load certificate. */
2971 if (NULL != CONFIG_TLS_CERT_FILE)
2972 {
2973 my_cert = zbx_malloc(my_cert, sizeof(x509_crt));
2974 x509_crt_init(my_cert);
2975
2976 if (0 != (res = x509_crt_parse_file(my_cert, CONFIG_TLS_CERT_FILE)))
2977 {
2978 if (0 > res)
2979 {
2980 zbx_tls_error_msg(res, "", &err_msg);
2981 zabbix_log(LOG_LEVEL_CRIT, "cannot parse certificate(s) in file \"%s\": %s",
2982 CONFIG_TLS_CERT_FILE, err_msg);
2983 zbx_free(err_msg);
2984 }
2985 else
2986 {
2987 zabbix_log(LOG_LEVEL_CRIT, "cannot parse %d certificate(s) in file \"%s\"", res,
2988 CONFIG_TLS_CERT_FILE);
2989 }
2990
2991 zbx_tls_free();
2992 exit(EXIT_FAILURE);
2993 }
2994
2995 zabbix_log(LOG_LEVEL_DEBUG, "%s() loaded certificate from file \"%s\"", __function_name,
2996 CONFIG_TLS_CERT_FILE);
2997 }
2998
2999 /* 'TLSKeyFile' parameter (in zabbix_server.conf, zabbix_proxy.conf, zabbix_agentd.conf). */
3000 /* Load private key. */
3001 if (NULL != CONFIG_TLS_KEY_FILE)
3002 {
3003 my_priv_key = zbx_malloc(my_priv_key, sizeof(pk_context));
3004 pk_init(my_priv_key);
3005
3006 /* The 3rd argument of pk_parse_keyfile() is password for decrypting the private key. */
3007 /* Currently the password is not used, it is empty. */
3008 if (0 != (res = pk_parse_keyfile(my_priv_key, CONFIG_TLS_KEY_FILE, "")))
3009 {
3010 zbx_tls_error_msg(res, "", &err_msg);
3011 zabbix_log(LOG_LEVEL_CRIT, "cannot parse the private key in file \"%s\": %s",
3012 CONFIG_TLS_KEY_FILE, err_msg);
3013 zbx_free(err_msg);
3014 zbx_tls_free();
3015 exit(EXIT_FAILURE);
3016 }
3017
3018 zabbix_log(LOG_LEVEL_DEBUG, "%s() loaded " ZBX_FS_SIZE_T "-bit %s private key from file \"%s\"",
3019 __function_name, (zbx_fs_size_t)pk_get_size(my_priv_key), pk_get_name(my_priv_key),
3020 CONFIG_TLS_KEY_FILE);
3021 }
3022
3023 /* 'TLSPSKFile' parameter (in zabbix_proxy.conf, zabbix_agentd.conf). */
3024 /* Load pre-shared key. */
3025 if (NULL != CONFIG_TLS_PSK_FILE)
3026 {
3027 zbx_read_psk_file();
3028 zabbix_log(LOG_LEVEL_DEBUG, "%s() loaded PSK from file \"%s\"", __function_name, CONFIG_TLS_PSK_FILE);
3029 }
3030
3031 /* 'TLSPSKIdentity' parameter (in zabbix_proxy.conf, zabbix_agentd.conf). */
3032 /* Configure identity to be used with the pre-shared key. */
3033 if (NULL != CONFIG_TLS_PSK_IDENTITY)
3034 {
3035 my_psk_identity = CONFIG_TLS_PSK_IDENTITY;
3036 my_psk_identity_len = strlen(my_psk_identity);
3037
3038 zbx_check_psk_identity_len(my_psk_identity_len);
3039
3040 zabbix_log(LOG_LEVEL_DEBUG, "%s() loaded PSK identity \"%s\"", __function_name,
3041 CONFIG_TLS_PSK_IDENTITY);
3042 }
3043
3044 /* Certificate always comes from configuration file. Set up ciphersuites. */
3045 if (NULL != my_cert)
3046 {
3047 zbx_ciphersuites(ZBX_TLS_CIPHERSUITE_CERT, &ciphersuites_cert);
3048 zbx_log_ciphersuites(__function_name, "certificate", ciphersuites_cert);
3049 }
3050
3051 /* PSK can come from configuration file (in proxy, agentd) and later from database (in server, proxy). */
3052 /* Configure ciphersuites just in case they will be used. */
3053 if (NULL != my_psk || 0 != (program_type & (ZBX_PROGRAM_TYPE_SERVER | ZBX_PROGRAM_TYPE_PROXY)))
3054 {
3055 zbx_ciphersuites(ZBX_TLS_CIPHERSUITE_PSK, &ciphersuites_psk);
3056 zbx_log_ciphersuites(__function_name, "PSK", ciphersuites_psk);
3057 }
3058
3059 /* Sometimes we need to be ready for both certificate and PSK whichever comes in. Set up a combined list of */
3060 /* ciphersuites. */
3061 if (NULL != my_cert && (NULL != my_psk ||
3062 0 != (program_type & (ZBX_PROGRAM_TYPE_SERVER | ZBX_PROGRAM_TYPE_PROXY))))
3063 {
3064 zbx_ciphersuites(ZBX_TLS_CIPHERSUITE_ALL, &ciphersuites_all);
3065 zbx_log_ciphersuites(__function_name, "certificate and PSK", ciphersuites_all);
3066 }
3067
3068 entropy = zbx_malloc(entropy, sizeof(entropy_context));
3069 entropy_init(entropy);
3070
3071 zbx_make_personalization_string(pers);
3072
3073 ctr_drbg = zbx_malloc(ctr_drbg, sizeof(ctr_drbg_context));
3074
3075 if (0 != (res = ctr_drbg_init(ctr_drbg, entropy_func, entropy, pers, 48)))
3076 /* PolarSSL sha512_finish() in SHA-384 mode returns an array "unsigned char output[64]" where result */
3077 /* resides in the first 48 bytes and the last 16 bytes are not used */
3078 {
3079 zbx_guaranteed_memset(pers, 0, sizeof(pers));
3080 zbx_tls_error_msg(res, "", &err_msg);
3081 zabbix_log(LOG_LEVEL_CRIT, "cannot initialize random number generator: %s", err_msg);
3082 zbx_free(err_msg);
3083 zbx_tls_free();
3084 exit(EXIT_FAILURE);
3085 }
3086
3087 zbx_guaranteed_memset(pers, 0, sizeof(pers));
3088
3089 #ifndef _WINDOWS
3090 sigprocmask(SIG_SETMASK, &orig_mask, NULL);
3091 #endif
3092 zabbix_log(LOG_LEVEL_DEBUG, "End of %s()", __function_name);
3093 }
3094 #elif defined(HAVE_GNUTLS)
zbx_gnutls_priority_init_or_exit(gnutls_priority_t * ciphersuites,const char * priority_str,const char * err_msg)3095 static void zbx_gnutls_priority_init_or_exit(gnutls_priority_t *ciphersuites, const char *priority_str,
3096 const char *err_msg)
3097 {
3098 const char *err_pos;
3099 int res;
3100
3101 if (GNUTLS_E_SUCCESS != (res = gnutls_priority_init(ciphersuites, priority_str, &err_pos)))
3102 {
3103 zabbix_log(LOG_LEVEL_CRIT, "gnutls_priority_init() for %s failed: %d: %s: error occurred at position:"
3104 " \"%s\"", err_msg, res, gnutls_strerror(res), ZBX_NULL2STR(err_pos));
3105 zbx_tls_free();
3106 exit(EXIT_FAILURE);
3107 }
3108 }
3109
zbx_tls_init_child(void)3110 void zbx_tls_init_child(void)
3111 {
3112 const char *__function_name = "zbx_tls_init_child";
3113 int res;
3114 #ifndef _WINDOWS
3115 sigset_t mask, orig_mask;
3116 #endif
3117 zabbix_log(LOG_LEVEL_DEBUG, "In %s()", __function_name);
3118
3119 #ifndef _WINDOWS
3120 /* Invalid TLS parameters will cause exit. Once one process exits the parent process will send SIGHUP to */
3121 /* child processes which may be on their way to exit on their own - do not interrupt them, block signal */
3122 /* SIGHUP and unblock it when TLS parameters are good and libraries are initialized. */
3123 sigemptyset(&mask);
3124 sigaddset(&mask, SIGTERM);
3125 sigaddset(&mask, SIGHUP);
3126 sigaddset(&mask, SIGUSR2);
3127 sigaddset(&mask, SIGQUIT);
3128 sigprocmask(SIG_BLOCK, &mask, &orig_mask);
3129
3130 zbx_tls_library_init(); /* on Unix initialize crypto libraries in child processes */
3131 #endif
3132 /* need to allocate certificate credentials store? */
3133
3134 if (NULL != CONFIG_TLS_CERT_FILE)
3135 {
3136 if (GNUTLS_E_SUCCESS != (res = gnutls_certificate_allocate_credentials(&my_cert_creds)))
3137 {
3138 zabbix_log(LOG_LEVEL_CRIT, "gnutls_certificate_allocate_credentials() failed: %d: %s", res,
3139 gnutls_strerror(res));
3140 zbx_tls_free();
3141 exit(EXIT_FAILURE);
3142 }
3143 }
3144
3145 /* 'TLSCAFile' parameter (in zabbix_server.conf, zabbix_proxy.conf, zabbix_agentd.conf) */
3146 if (NULL != CONFIG_TLS_CA_FILE)
3147 {
3148 if (0 < (res = gnutls_certificate_set_x509_trust_file(my_cert_creds, CONFIG_TLS_CA_FILE,
3149 GNUTLS_X509_FMT_PEM)))
3150 {
3151 zabbix_log(LOG_LEVEL_DEBUG, "%s() loaded %d CA certificate(s) from file \"%s\"",
3152 __function_name, res, CONFIG_TLS_CA_FILE);
3153 }
3154 else if (0 == res)
3155 {
3156 zabbix_log(LOG_LEVEL_WARNING, "no CA certificate(s) in file \"%s\"", CONFIG_TLS_CA_FILE);
3157 }
3158 else
3159 {
3160 zabbix_log(LOG_LEVEL_CRIT, "cannot parse CA certificate(s) in file \"%s\": %d: %s",
3161 CONFIG_TLS_CA_FILE, res, gnutls_strerror(res));
3162 zbx_tls_free();
3163 exit(EXIT_FAILURE);
3164 }
3165 }
3166
3167 /* 'TLSCRLFile' parameter (in zabbix_server.conf, zabbix_proxy.conf, zabbix_agentd.conf). */
3168 /* Load CRL (certificate revocation list) file. */
3169 if (NULL != CONFIG_TLS_CRL_FILE)
3170 {
3171 if (0 < (res = gnutls_certificate_set_x509_crl_file(my_cert_creds, CONFIG_TLS_CRL_FILE,
3172 GNUTLS_X509_FMT_PEM)))
3173 {
3174 zabbix_log(LOG_LEVEL_DEBUG, "%s() loaded %d CRL(s) from file \"%s\"", __function_name, res,
3175 CONFIG_TLS_CRL_FILE);
3176 }
3177 else if (0 == res)
3178 {
3179 zabbix_log(LOG_LEVEL_WARNING, "no CRL(s) in file \"%s\"", CONFIG_TLS_CRL_FILE);
3180 }
3181 else
3182 {
3183 zabbix_log(LOG_LEVEL_CRIT, "cannot parse CRL file \"%s\": %d: %s", CONFIG_TLS_CRL_FILE, res,
3184 gnutls_strerror(res));
3185 zbx_tls_free();
3186 exit(EXIT_FAILURE);
3187 }
3188 }
3189
3190 /* 'TLSCertFile' and 'TLSKeyFile' parameters (in zabbix_server.conf, zabbix_proxy.conf, zabbix_agentd.conf). */
3191 /* Load certificate and private key. */
3192 if (NULL != CONFIG_TLS_CERT_FILE)
3193 {
3194 if (GNUTLS_E_SUCCESS != (res = gnutls_certificate_set_x509_key_file(my_cert_creds, CONFIG_TLS_CERT_FILE,
3195 CONFIG_TLS_KEY_FILE, GNUTLS_X509_FMT_PEM)))
3196 {
3197 zabbix_log(LOG_LEVEL_CRIT, "cannot load certificate or private key from file \"%s\" or \"%s\":"
3198 " %d: %s", CONFIG_TLS_CERT_FILE, CONFIG_TLS_KEY_FILE, res,
3199 gnutls_strerror(res));
3200 zbx_tls_free();
3201 exit(EXIT_FAILURE);
3202 }
3203 else
3204 {
3205 zabbix_log(LOG_LEVEL_DEBUG, "%s() loaded certificate from file \"%s\"", __function_name,
3206 CONFIG_TLS_CERT_FILE);
3207 zabbix_log(LOG_LEVEL_DEBUG, "%s() loaded private key from file \"%s\"", __function_name,
3208 CONFIG_TLS_KEY_FILE);
3209 }
3210 }
3211
3212 /* 'TLSPSKIdentity' and 'TLSPSKFile' parameters (in zabbix_proxy.conf, zabbix_agentd.conf). */
3213 /* Load pre-shared key and identity to be used with the pre-shared key. */
3214 if (NULL != CONFIG_TLS_PSK_FILE)
3215 {
3216 gnutls_datum_t key;
3217
3218 my_psk_identity = CONFIG_TLS_PSK_IDENTITY;
3219 my_psk_identity_len = strlen(my_psk_identity);
3220
3221 zbx_check_psk_identity_len(my_psk_identity_len);
3222
3223 zbx_read_psk_file();
3224
3225 key.data = (unsigned char *)my_psk;
3226 key.size = (unsigned int)my_psk_len;
3227
3228 /* allocate here only PSK credential stores which do not change (e.g. for proxy communication with */
3229 /* server) */
3230
3231 if (0 != (program_type & (ZBX_PROGRAM_TYPE_PROXY_ACTIVE | ZBX_PROGRAM_TYPE_AGENTD |
3232 ZBX_PROGRAM_TYPE_SENDER | ZBX_PROGRAM_TYPE_GET)))
3233 {
3234 if (GNUTLS_E_SUCCESS != (res = gnutls_psk_allocate_client_credentials(&my_psk_client_creds)))
3235 {
3236 zabbix_log(LOG_LEVEL_CRIT, "gnutls_psk_allocate_client_credentials() failed: %d: %s",
3237 res, gnutls_strerror(res));
3238 zbx_tls_free();
3239 exit(EXIT_FAILURE);
3240 }
3241
3242 /* Simplified. 'my_psk_identity' should have been prepared as required by RFC 4518. */
3243 if (GNUTLS_E_SUCCESS != (res = gnutls_psk_set_client_credentials(my_psk_client_creds,
3244 my_psk_identity, &key, GNUTLS_PSK_KEY_RAW)))
3245 {
3246 zabbix_log(LOG_LEVEL_CRIT, "gnutls_psk_set_client_credentials() failed: %d: %s", res,
3247 gnutls_strerror(res));
3248 zbx_tls_free();
3249 exit(EXIT_FAILURE);
3250 }
3251 }
3252
3253 if (0 != (program_type & (ZBX_PROGRAM_TYPE_PROXY_PASSIVE | ZBX_PROGRAM_TYPE_AGENTD)))
3254 {
3255 if (0 != (res = gnutls_psk_allocate_server_credentials(&my_psk_server_creds)))
3256 {
3257 zabbix_log(LOG_LEVEL_CRIT, "gnutls_psk_allocate_server_credentials() failed: %d: %s",
3258 res, gnutls_strerror(res));
3259 zbx_tls_free();
3260 exit(EXIT_FAILURE);
3261 }
3262
3263 /* Apparently GnuTLS does not provide API for setting up static server credentials (with a */
3264 /* fixed PSK identity and key) for a passive proxy and agentd. The only possibility seems to */
3265 /* be to set up credentials dynamically for each incoming connection using a callback */
3266 /* function. */
3267 gnutls_psk_set_server_credentials_function(my_psk_server_creds, zbx_psk_cb);
3268 }
3269
3270 zabbix_log(LOG_LEVEL_DEBUG, "%s() loaded PSK identity \"%s\"", __function_name,
3271 CONFIG_TLS_PSK_IDENTITY);
3272 zabbix_log(LOG_LEVEL_DEBUG, "%s() loaded PSK from file \"%s\"", __function_name, CONFIG_TLS_PSK_FILE);
3273 }
3274
3275 /* Certificate always comes from configuration file. Set up ciphersuites. */
3276 if (NULL != my_cert_creds)
3277 {
3278 const char *priority_str;
3279
3280 if (NULL == CONFIG_TLS_CIPHER_CERT)
3281 {
3282 /* for GnuTLS 3.1.18 and up */
3283 priority_str = "NONE:+VERS-TLS1.2:+ECDHE-RSA:+RSA:+AES-128-GCM:+AES-128-CBC:+AEAD:+SHA256:"
3284 "+SHA1:+CURVE-ALL:+COMP-NULL:+SIGN-ALL:+CTYPE-X.509";
3285
3286 zbx_gnutls_priority_init_or_exit(&ciphersuites_cert, priority_str,
3287 "\"ciphersuites_cert\" with built-in default value");
3288 }
3289 else
3290 {
3291 priority_str = CONFIG_TLS_CIPHER_CERT;
3292
3293 zbx_gnutls_priority_init_or_exit(&ciphersuites_cert, priority_str,
3294 "\"ciphersuites_cert\" with TLSCipherCert or --tls-cipher parameter");
3295 }
3296
3297 zbx_log_ciphersuites(__function_name, "certificate", ciphersuites_cert);
3298 }
3299
3300 /* PSK can come from configuration file (in proxy, agentd) and later from database (in server, proxy). */
3301 /* Configure ciphersuites just in case they will be used. */
3302 if (NULL != my_psk_client_creds || NULL != my_psk_server_creds ||
3303 0 != (program_type & (ZBX_PROGRAM_TYPE_SERVER | ZBX_PROGRAM_TYPE_PROXY)))
3304 {
3305 const char *priority_str;
3306
3307 if (NULL == CONFIG_TLS_CIPHER_PSK)
3308 {
3309 /* for GnuTLS 3.1.18 and up */
3310 priority_str = "NONE:+VERS-TLS1.2:+ECDHE-PSK:+PSK:+AES-128-GCM:+AES-128-CBC:+AEAD:+SHA256:"
3311 "+SHA1:+CURVE-ALL:+COMP-NULL:+SIGN-ALL";
3312
3313 zbx_gnutls_priority_init_or_exit(&ciphersuites_psk, priority_str,
3314 "\"ciphersuites_psk\" with built-in default value");
3315 }
3316 else
3317 {
3318 priority_str = CONFIG_TLS_CIPHER_PSK;
3319
3320 zbx_gnutls_priority_init_or_exit(&ciphersuites_psk, priority_str,
3321 "\"ciphersuites_psk\" with TLSCipherPSK or --tls-cipher parameter");
3322 }
3323
3324 zbx_log_ciphersuites(__function_name, "PSK", ciphersuites_psk);
3325 }
3326
3327 /* Sometimes we need to be ready for both certificate and PSK whichever comes in. Set up a combined list of */
3328 /* ciphersuites. */
3329 if (NULL != my_cert_creds && (NULL != my_psk_client_creds || NULL != my_psk_server_creds ||
3330 0 != (program_type & (ZBX_PROGRAM_TYPE_SERVER | ZBX_PROGRAM_TYPE_PROXY))))
3331 {
3332 const char *priority_str;
3333
3334 if (NULL == CONFIG_TLS_CIPHER_ALL)
3335 {
3336 /* for GnuTLS 3.1.18 and up */
3337 priority_str = "NONE:+VERS-TLS1.2:+ECDHE-RSA:"
3338 "+RSA:+ECDHE-PSK:+PSK:+AES-128-GCM:+AES-128-CBC:+AEAD:+SHA256:+SHA1:+CURVE-ALL:"
3339 "+COMP-NULL:+SIGN-ALL:+CTYPE-X.509";
3340
3341 zbx_gnutls_priority_init_or_exit(&ciphersuites_all, priority_str,
3342 "\"ciphersuites_all\" with built-in default value");
3343 }
3344 else
3345 {
3346 priority_str = CONFIG_TLS_CIPHER_ALL;
3347
3348 zbx_gnutls_priority_init_or_exit(&ciphersuites_all, priority_str,
3349 "\"ciphersuites_all\" with TLSCipherAll parameter");
3350 }
3351
3352 zbx_log_ciphersuites(__function_name, "certificate and PSK", ciphersuites_all);
3353 }
3354
3355 #ifndef _WINDOWS
3356 sigprocmask(SIG_SETMASK, &orig_mask, NULL);
3357 #endif
3358 zabbix_log(LOG_LEVEL_DEBUG, "End of %s()", __function_name);
3359 }
3360 #elif defined(HAVE_OPENSSL)
zbx_ctx_name(SSL_CTX * param)3361 static const char *zbx_ctx_name(SSL_CTX *param)
3362 {
3363 if (ctx_cert == param)
3364 return "certificate-based encryption";
3365
3366 #if defined(HAVE_OPENSSL_WITH_PSK)
3367 if (ctx_psk == param)
3368 return "PSK-based encryption";
3369
3370 if (ctx_all == param)
3371 return "certificate and PSK-based encryption";
3372 #endif
3373 THIS_SHOULD_NEVER_HAPPEN;
3374 return ZBX_NULL2STR(NULL);
3375 }
3376
zbx_set_ecdhe_parameters(SSL_CTX * ctx)3377 static int zbx_set_ecdhe_parameters(SSL_CTX *ctx)
3378 {
3379 const char *__function_name = "zbx_set_ecdhe_parameters";
3380 const char *msg = "Perfect Forward Secrecy ECDHE ciphersuites will not be available for";
3381 EC_KEY *ecdh;
3382 long res;
3383 int ret = SUCCEED;
3384
3385 /* use curve secp256r1/prime256v1/NIST P-256 */
3386
3387 if (NULL == (ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1)))
3388 {
3389 zabbix_log(LOG_LEVEL_WARNING, "%s() EC_KEY_new_by_curve_name() failed. %s %s",
3390 __function_name, msg, zbx_ctx_name(ctx));
3391 return FAIL;
3392 }
3393
3394 SSL_CTX_set_options(ctx, SSL_OP_SINGLE_ECDH_USE);
3395
3396 if (1 != (res = SSL_CTX_set_tmp_ecdh(ctx, ecdh)))
3397 {
3398 zabbix_log(LOG_LEVEL_WARNING, "%s() SSL_CTX_set_tmp_ecdh() returned %ld. %s %s",
3399 __function_name, res, msg, zbx_ctx_name(ctx));
3400 ret = FAIL;
3401 }
3402
3403 EC_KEY_free(ecdh);
3404
3405 return ret;
3406 }
3407
zbx_tls_init_child(void)3408 void zbx_tls_init_child(void)
3409 {
3410 #define ZBX_CIPHERS_CERT_ECDHE "EECDH+aRSA+AES128:"
3411 #define ZBX_CIPHERS_CERT "RSA+aRSA+AES128"
3412
3413 #if defined(HAVE_OPENSSL_WITH_PSK)
3414 #if OPENSSL_VERSION_NUMBER >= 0x1010100fL /* OpenSSL 1.1.1 or newer */
3415 /* TLS_AES_256_GCM_SHA384 is excluded from client ciphersuite list for PSK based connections. */
3416 /* By default, in TLS 1.3 only *-SHA256 ciphersuites work with PSK. */
3417 # define ZBX_CIPHERS_PSK_TLS13 "TLS_CHACHA20_POLY1305_SHA256:TLS_AES_128_GCM_SHA256"
3418 #endif
3419 #if OPENSSL_VERSION_NUMBER >= 0x1010000fL /* OpenSSL 1.1.0 or newer */
3420 # define ZBX_CIPHERS_PSK_ECDHE "kECDHEPSK+AES128:"
3421 # define ZBX_CIPHERS_PSK "kPSK+AES128"
3422 #else
3423 # define ZBX_CIPHERS_PSK_ECDHE ""
3424 # define ZBX_CIPHERS_PSK "PSK-AES128-CBC-SHA"
3425 #endif
3426 #endif
3427
3428 const char *__function_name = "zbx_tls_init_child";
3429 char *error = NULL;
3430 size_t error_alloc = 0, error_offset = 0;
3431 #ifndef _WINDOWS
3432 sigset_t mask, orig_mask;
3433 #endif
3434 zabbix_log(LOG_LEVEL_DEBUG, "In %s()", __function_name);
3435
3436 #ifndef _WINDOWS
3437 /* Invalid TLS parameters will cause exit. Once one process exits the parent process will send SIGHUP to */
3438 /* child processes which may be on their way to exit on their own - do not interrupt them, block signal */
3439 /* SIGHUP and unblock it when TLS parameters are good and libraries are initialized. */
3440 sigemptyset(&mask);
3441 sigaddset(&mask, SIGTERM);
3442 sigaddset(&mask, SIGHUP);
3443 sigaddset(&mask, SIGUSR2);
3444 sigaddset(&mask, SIGQUIT);
3445 sigprocmask(SIG_BLOCK, &mask, &orig_mask);
3446
3447 zbx_tls_library_init(); /* on Unix initialize crypto libraries in child processes */
3448 #endif
3449 if (1 != RAND_status()) /* protect against not properly seeded PRNG */
3450 {
3451 zabbix_log(LOG_LEVEL_CRIT, "cannot initialize PRNG");
3452 zbx_tls_free();
3453 exit(EXIT_FAILURE);
3454 }
3455
3456 /* set protocol version to TLS 1.2 */
3457
3458 if (0 != (program_type & (ZBX_PROGRAM_TYPE_SENDER | ZBX_PROGRAM_TYPE_GET)))
3459 method = TLS_client_method();
3460 else /* ZBX_PROGRAM_TYPE_SERVER | ZBX_PROGRAM_TYPE_PROXY | ZBX_PROGRAM_TYPE_AGENTD */
3461 method = TLS_method();
3462
3463 /* create context for certificate-only authentication if certificate is configured */
3464 if (NULL != CONFIG_TLS_CERT_FILE)
3465 {
3466 if (NULL == (ctx_cert = SSL_CTX_new(method)))
3467 goto out_method;
3468
3469 if (1 != SSL_CTX_set_min_proto_version(ctx_cert, TLS1_2_VERSION))
3470 goto out_method;
3471 }
3472 #if defined(HAVE_OPENSSL_WITH_PSK)
3473 /* Create context for PSK-only authentication. PSK can come from configuration file (in proxy, agentd) */
3474 /* and later from database (in server, proxy). */
3475 if (NULL != CONFIG_TLS_PSK_FILE || 0 != (program_type & (ZBX_PROGRAM_TYPE_SERVER | ZBX_PROGRAM_TYPE_PROXY)))
3476 {
3477 if (NULL == (ctx_psk = SSL_CTX_new(method)))
3478 goto out_method;
3479
3480 if (1 != SSL_CTX_set_min_proto_version(ctx_psk, TLS1_2_VERSION))
3481 goto out_method;
3482 }
3483
3484 /* Sometimes we need to be ready for both certificate and PSK whichever comes in. Set up a universal context */
3485 /* for certificate and PSK authentication to prepare for both. */
3486 if (NULL != ctx_cert && NULL != ctx_psk)
3487 {
3488 if (NULL == (ctx_all = SSL_CTX_new(method)))
3489 goto out_method;
3490
3491 if (1 != SSL_CTX_set_min_proto_version(ctx_all, TLS1_2_VERSION))
3492 goto out_method;
3493 }
3494 #endif
3495 /* 'TLSCAFile' parameter (in zabbix_server.conf, zabbix_proxy.conf, zabbix_agentd.conf) */
3496 if (NULL != CONFIG_TLS_CA_FILE)
3497 {
3498 #if defined(HAVE_OPENSSL_WITH_PSK)
3499 if (1 != SSL_CTX_load_verify_locations(ctx_cert, CONFIG_TLS_CA_FILE, NULL) ||
3500 (NULL != ctx_all && 1 != SSL_CTX_load_verify_locations(ctx_all, CONFIG_TLS_CA_FILE,
3501 NULL)))
3502 #else
3503 if (1 != SSL_CTX_load_verify_locations(ctx_cert, CONFIG_TLS_CA_FILE, NULL))
3504 #endif
3505 {
3506 zbx_snprintf_alloc(&error, &error_alloc, &error_offset, "cannot load CA certificate(s) from"
3507 " file \"%s\":", CONFIG_TLS_CA_FILE);
3508 goto out;
3509 }
3510
3511 zabbix_log(LOG_LEVEL_DEBUG, "%s() loaded CA certificate(s) from file \"%s\"", __function_name,
3512 CONFIG_TLS_CA_FILE);
3513
3514 /* It is possible to limit the length of certificate chain being verified. For example: */
3515 /* SSL_CTX_set_verify_depth(ctx_cert, 2); */
3516 /* Currently use the default depth 100. */
3517
3518 SSL_CTX_set_verify(ctx_cert, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, NULL);
3519
3520 #if defined(HAVE_OPENSSL_WITH_PSK)
3521 if (NULL != ctx_all)
3522 SSL_CTX_set_verify(ctx_all, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, NULL);
3523 #endif
3524 }
3525
3526 /* 'TLSCRLFile' parameter (in zabbix_server.conf, zabbix_proxy.conf, zabbix_agentd.conf). */
3527 /* Load CRL (certificate revocation list) file. */
3528 if (NULL != CONFIG_TLS_CRL_FILE)
3529 {
3530 X509_STORE *store_cert;
3531 X509_LOOKUP *lookup_cert;
3532 int count_cert;
3533
3534 store_cert = SSL_CTX_get_cert_store(ctx_cert);
3535
3536 if (NULL == (lookup_cert = X509_STORE_add_lookup(store_cert, X509_LOOKUP_file())))
3537 {
3538 zbx_snprintf_alloc(&error, &error_alloc, &error_offset, "X509_STORE_add_lookup() #%d failed"
3539 " when loading CRL(s) from file \"%s\":", 1, CONFIG_TLS_CRL_FILE);
3540 goto out;
3541 }
3542
3543 if (0 >= (count_cert = X509_load_crl_file(lookup_cert, CONFIG_TLS_CRL_FILE, X509_FILETYPE_PEM)))
3544 {
3545 zbx_snprintf_alloc(&error, &error_alloc, &error_offset, "cannot load CRL(s) from file \"%s\":",
3546 CONFIG_TLS_CRL_FILE);
3547 goto out;
3548 }
3549
3550 if (1 != X509_STORE_set_flags(store_cert, X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL))
3551 {
3552 zbx_snprintf_alloc(&error, &error_alloc, &error_offset, "X509_STORE_set_flags() #%d failed when"
3553 " loading CRL(s) from file \"%s\":", 1, CONFIG_TLS_CRL_FILE);
3554 goto out;
3555 }
3556 #if defined(HAVE_OPENSSL_WITH_PSK)
3557 if (NULL != ctx_all)
3558 {
3559 X509_STORE *store_all;
3560 X509_LOOKUP *lookup_all;
3561 int count_all;
3562
3563 store_all = SSL_CTX_get_cert_store(ctx_all);
3564
3565 if (NULL == (lookup_all = X509_STORE_add_lookup(store_all, X509_LOOKUP_file())))
3566 {
3567 zbx_snprintf_alloc(&error, &error_alloc, &error_offset, "X509_STORE_add_lookup() #%d"
3568 " failed when loading CRL(s) from file \"%s\":", 2,
3569 CONFIG_TLS_CRL_FILE);
3570 goto out;
3571 }
3572
3573 if (0 >= (count_all = X509_load_crl_file(lookup_all, CONFIG_TLS_CRL_FILE, X509_FILETYPE_PEM)))
3574 {
3575 zbx_snprintf_alloc(&error, &error_alloc, &error_offset, "cannot load CRL(s) from file"
3576 " \"%s\":", CONFIG_TLS_CRL_FILE);
3577 goto out;
3578 }
3579
3580 if (count_cert != count_all)
3581 {
3582 zbx_snprintf_alloc(&error, &error_alloc, &error_offset, "number of CRL(s) loaded from"
3583 " file \"%s\" does not match: %d and %d", CONFIG_TLS_CRL_FILE,
3584 count_cert, count_all);
3585 goto out1;
3586 }
3587
3588 if (1 != X509_STORE_set_flags(store_all, X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL))
3589 {
3590 zbx_snprintf_alloc(&error, &error_alloc, &error_offset, "X509_STORE_set_flags() #%d"
3591 " failed when loading CRL(s) from file \"%s\":", 2,
3592 CONFIG_TLS_CRL_FILE);
3593 goto out;
3594 }
3595 }
3596 #endif
3597 zabbix_log(LOG_LEVEL_DEBUG, "%s() loaded %d CRL(s) from file \"%s\"", __function_name, count_cert,
3598 CONFIG_TLS_CRL_FILE);
3599 }
3600
3601 /* 'TLSCertFile' parameter (in zabbix_server.conf, zabbix_proxy.conf, zabbix_agentd.conf). */
3602 /* Load certificate. */
3603 if (NULL != CONFIG_TLS_CERT_FILE)
3604 {
3605 #if defined(HAVE_OPENSSL_WITH_PSK)
3606 if (1 != SSL_CTX_use_certificate_chain_file(ctx_cert, CONFIG_TLS_CERT_FILE) || (NULL != ctx_all &&
3607 1 != SSL_CTX_use_certificate_chain_file(ctx_all, CONFIG_TLS_CERT_FILE)))
3608 #else
3609 if (1 != SSL_CTX_use_certificate_chain_file(ctx_cert, CONFIG_TLS_CERT_FILE))
3610 #endif
3611 {
3612 zbx_snprintf_alloc(&error, &error_alloc, &error_offset, "cannot load certificate(s) from file"
3613 " \"%s\":", CONFIG_TLS_CERT_FILE);
3614 goto out;
3615 }
3616
3617 zabbix_log(LOG_LEVEL_DEBUG, "%s() loaded certificate(s) from file \"%s\"", __function_name,
3618 CONFIG_TLS_CERT_FILE);
3619 }
3620
3621 /* 'TLSKeyFile' parameter (in zabbix_server.conf, zabbix_proxy.conf, zabbix_agentd.conf). */
3622 /* Load private key. */
3623 if (NULL != CONFIG_TLS_KEY_FILE)
3624 {
3625 #if defined(HAVE_OPENSSL_WITH_PSK)
3626 if (1 != SSL_CTX_use_PrivateKey_file(ctx_cert, CONFIG_TLS_KEY_FILE, SSL_FILETYPE_PEM) ||
3627 (NULL != ctx_all && 1 != SSL_CTX_use_PrivateKey_file(ctx_all, CONFIG_TLS_KEY_FILE,
3628 SSL_FILETYPE_PEM)))
3629 #else
3630 if (1 != SSL_CTX_use_PrivateKey_file(ctx_cert, CONFIG_TLS_KEY_FILE, SSL_FILETYPE_PEM))
3631 #endif
3632 {
3633 zbx_snprintf_alloc(&error, &error_alloc, &error_offset, "cannot load private key from file"
3634 " \"%s\":", CONFIG_TLS_KEY_FILE);
3635 goto out;
3636 }
3637
3638 zabbix_log(LOG_LEVEL_DEBUG, "%s() loaded private key from file \"%s\"", __function_name,
3639 CONFIG_TLS_KEY_FILE);
3640
3641 if (1 != SSL_CTX_check_private_key(ctx_cert))
3642 {
3643 zbx_snprintf_alloc(&error, &error_alloc, &error_offset, "certificate and private key do not"
3644 " match:");
3645 goto out;
3646 }
3647 }
3648
3649 /* 'TLSPSKIdentity' and 'TLSPSKFile' parameters (in zabbix_proxy.conf, zabbix_agentd.conf). */
3650 /* Load pre-shared key and identity to be used with the pre-shared key. */
3651 if (NULL != CONFIG_TLS_PSK_FILE)
3652 {
3653 my_psk_identity = CONFIG_TLS_PSK_IDENTITY;
3654 my_psk_identity_len = strlen(my_psk_identity);
3655
3656 zbx_check_psk_identity_len(my_psk_identity_len);
3657
3658 zabbix_log(LOG_LEVEL_DEBUG, "%s() loaded PSK identity \"%s\"", __function_name,
3659 CONFIG_TLS_PSK_IDENTITY);
3660
3661 zbx_read_psk_file();
3662
3663 zabbix_log(LOG_LEVEL_DEBUG, "%s() loaded PSK from file \"%s\"", __function_name, CONFIG_TLS_PSK_FILE);
3664 }
3665 #if defined(HAVE_OPENSSL_WITH_PSK)
3666 /* set up PSK global variables for client callback if PSK comes only from configuration file or command line */
3667
3668 if (NULL != ctx_psk && 0 != (program_type & (ZBX_PROGRAM_TYPE_AGENTD | ZBX_PROGRAM_TYPE_SENDER |
3669 ZBX_PROGRAM_TYPE_GET)))
3670 {
3671 psk_identity_for_cb = my_psk_identity;
3672 psk_identity_len_for_cb = my_psk_identity_len;
3673 psk_for_cb = my_psk;
3674 psk_len_for_cb = my_psk_len;
3675 }
3676 #endif
3677 if (NULL != ctx_cert)
3678 {
3679 const char *ciphers;
3680
3681 SSL_CTX_set_info_callback(ctx_cert, zbx_openssl_info_cb);
3682
3683 /* we're using blocking sockets, deal with renegotiations automatically */
3684 SSL_CTX_set_mode(ctx_cert, SSL_MODE_AUTO_RETRY);
3685
3686 /* use server ciphersuite preference, do not use RFC 4507 ticket extension */
3687 SSL_CTX_set_options(ctx_cert, SSL_OP_CIPHER_SERVER_PREFERENCE | SSL_OP_NO_TICKET);
3688
3689 /* do not connect to unpatched servers */
3690 SSL_CTX_clear_options(ctx_cert, SSL_OP_LEGACY_SERVER_CONNECT);
3691
3692 /* disable session caching */
3693 SSL_CTX_set_session_cache_mode(ctx_cert, SSL_SESS_CACHE_OFF);
3694
3695 /* try to enable ECDH ciphersuites */
3696 if (SUCCEED == zbx_set_ecdhe_parameters(ctx_cert))
3697 ciphers = ZBX_CIPHERS_CERT_ECDHE ZBX_CIPHERS_CERT;
3698 else
3699 ciphers = ZBX_CIPHERS_CERT;
3700
3701 /* override TLS 1.3 certificate ciphersuites with user-defined settings */
3702 if (NULL != CONFIG_TLS_CIPHER_CERT13 || NULL != CONFIG_TLS_CIPHER_CMD13)
3703 {
3704 #if OPENSSL_VERSION_NUMBER >= 0x1010100fL && !defined(LIBRESSL_VERSION_NUMBER) /* only OpenSSL 1.1.1 or newer */
3705 const char *override_ciphers = CONFIG_TLS_CIPHER_CERT13; /* can be NULL */
3706
3707 if (NULL != CONFIG_TLS_CIPHER_CMD13 && ZBX_TCP_SEC_TLS_CERT == configured_tls_connect_mode)
3708 override_ciphers = CONFIG_TLS_CIPHER_CMD13;
3709
3710 if (NULL != override_ciphers && 1 != SSL_CTX_set_ciphersuites(ctx_cert, override_ciphers))
3711 {
3712 zbx_snprintf_alloc(&error, &error_alloc, &error_offset, "cannot set list of TLS 1.3"
3713 " certificate ciphersuites from \"TLSCipherCert13\" or"
3714 " \"--tls-cipher13\" parameter:");
3715 goto out;
3716 }
3717 #else
3718 zbx_snprintf_alloc(&error, &error_alloc, &error_offset, "cannot set list of TLS 1.3"
3719 " certificate ciphersuites: compiled with OpenSSL version older than 1.1.1 or"
3720 " with LibreSSL. Consider not using parameters \"TLSCipherCert13\" or"
3721 " \"--tls-cipher13\"");
3722 goto out1;
3723 #endif
3724 }
3725
3726 /* override TLS 1.2 certificate ciphersuites with user-defined settings */
3727 if (NULL != CONFIG_TLS_CIPHER_CERT || NULL != CONFIG_TLS_CIPHER_CMD)
3728 {
3729 const char *override_ciphers = CONFIG_TLS_CIPHER_CERT; /* can be NULL */
3730
3731 if (NULL != CONFIG_TLS_CIPHER_CMD && ZBX_TCP_SEC_TLS_CERT == configured_tls_connect_mode)
3732 override_ciphers = CONFIG_TLS_CIPHER_CMD;
3733
3734 if (NULL != override_ciphers && 1 != SSL_CTX_set_cipher_list(ctx_cert, override_ciphers))
3735 {
3736 zbx_snprintf_alloc(&error, &error_alloc, &error_offset, "cannot set list of TLS 1.2"
3737 " certificate ciphersuites from \"TLSCipherCert\" or \"--tls-cipher\""
3738 " parameter:");
3739 goto out;
3740 }
3741 }
3742 else if (1 != SSL_CTX_set_cipher_list(ctx_cert, ciphers))
3743 {
3744 zbx_snprintf_alloc(&error, &error_alloc, &error_offset, "cannot set list of certificate"
3745 " ciphersuites:");
3746 goto out;
3747 }
3748
3749 zbx_log_ciphersuites(__function_name, "certificate", ctx_cert);
3750 }
3751 #if defined(HAVE_OPENSSL_WITH_PSK)
3752 if (NULL != ctx_psk)
3753 {
3754 const char *ciphers;
3755
3756 SSL_CTX_set_info_callback(ctx_psk, zbx_openssl_info_cb);
3757
3758 if (0 != (program_type & (ZBX_PROGRAM_TYPE_SERVER | ZBX_PROGRAM_TYPE_PROXY | ZBX_PROGRAM_TYPE_AGENTD |
3759 ZBX_PROGRAM_TYPE_SENDER | ZBX_PROGRAM_TYPE_GET)))
3760 {
3761 SSL_CTX_set_psk_client_callback(ctx_psk, zbx_psk_client_cb);
3762 }
3763
3764 if (0 != (program_type & (ZBX_PROGRAM_TYPE_SERVER | ZBX_PROGRAM_TYPE_PROXY | ZBX_PROGRAM_TYPE_AGENTD)))
3765 SSL_CTX_set_psk_server_callback(ctx_psk, zbx_psk_server_cb);
3766
3767 SSL_CTX_set_mode(ctx_psk, SSL_MODE_AUTO_RETRY);
3768 SSL_CTX_set_options(ctx_psk, SSL_OP_CIPHER_SERVER_PREFERENCE | SSL_OP_NO_TICKET);
3769 SSL_CTX_clear_options(ctx_psk, SSL_OP_LEGACY_SERVER_CONNECT);
3770 SSL_CTX_set_session_cache_mode(ctx_psk, SSL_SESS_CACHE_OFF);
3771
3772 if ('\0' != *ZBX_CIPHERS_PSK_ECDHE && SUCCEED == zbx_set_ecdhe_parameters(ctx_psk))
3773 ciphers = ZBX_CIPHERS_PSK_ECDHE ZBX_CIPHERS_PSK;
3774 else
3775 ciphers = ZBX_CIPHERS_PSK;
3776
3777 /* override TLS 1.3 PSK ciphersuites with user-defined settings */
3778 if (NULL != CONFIG_TLS_CIPHER_PSK13 || NULL != CONFIG_TLS_CIPHER_CMD13)
3779 {
3780 #if OPENSSL_VERSION_NUMBER >= 0x1010100fL /* OpenSSL 1.1.1 or newer */
3781 const char *override_ciphers = CONFIG_TLS_CIPHER_PSK13; /* can be NULL */
3782
3783 if (NULL != CONFIG_TLS_CIPHER_CMD13 && ZBX_TCP_SEC_TLS_PSK == configured_tls_connect_mode)
3784 override_ciphers = CONFIG_TLS_CIPHER_CMD13;
3785
3786 if (NULL != override_ciphers && 1 != SSL_CTX_set_ciphersuites(ctx_psk, override_ciphers))
3787 {
3788 zbx_snprintf_alloc(&error, &error_alloc, &error_offset, "cannot set list of TLS 1.3"
3789 " PSK ciphersuites from \"TLSCipherPSK13\" or \"--tls-cipher13\""
3790 " parameter:");
3791 goto out;
3792 }
3793 #else
3794 zbx_snprintf_alloc(&error, &error_alloc, &error_offset, "cannot set list of TLS 1.3"
3795 " PSK ciphersuites: compiled with OpenSSL version older than 1.1.1."
3796 " Consider not using parameters \"TLSCipherPSK13\" or \"--tls-cipher13\"");
3797 goto out1;
3798 #endif
3799 }
3800 #if OPENSSL_VERSION_NUMBER >= 0x1010100fL /* OpenSSL 1.1.1 or newer */
3801 else if (1 != SSL_CTX_set_ciphersuites(ctx_psk, ZBX_CIPHERS_PSK_TLS13))
3802 {
3803 zbx_snprintf_alloc(&error, &error_alloc, &error_offset, "cannot set list of PSK TLS 1.3"
3804 " ciphersuites:");
3805 goto out;
3806 }
3807 #endif
3808 /* override TLS 1.2 PSK ciphersuites with user-defined settings */
3809 if (NULL != CONFIG_TLS_CIPHER_PSK || NULL != CONFIG_TLS_CIPHER_CMD)
3810 {
3811 const char *override_ciphers = CONFIG_TLS_CIPHER_PSK; /* can be NULL */
3812
3813 if (NULL != CONFIG_TLS_CIPHER_CMD && ZBX_TCP_SEC_TLS_PSK == configured_tls_connect_mode)
3814 override_ciphers = CONFIG_TLS_CIPHER_CMD;
3815
3816 if (NULL != override_ciphers && 1 != SSL_CTX_set_cipher_list(ctx_psk, override_ciphers))
3817 {
3818 zbx_snprintf_alloc(&error, &error_alloc, &error_offset, "cannot set list of TLS 1.2"
3819 " PSK ciphersuites from \"TLSCipherPSK\" or \"--tls-cipher\""
3820 " parameter:");
3821 goto out;
3822 }
3823 }
3824 else if (1 != SSL_CTX_set_cipher_list(ctx_psk, ciphers))
3825 {
3826 zbx_snprintf_alloc(&error, &error_alloc, &error_offset, "cannot set list of PSK ciphersuites:");
3827 goto out;
3828 }
3829
3830 zbx_log_ciphersuites(__function_name, "PSK", ctx_psk);
3831 }
3832
3833 if (NULL != ctx_all)
3834 {
3835 const char *ciphers;
3836
3837 SSL_CTX_set_info_callback(ctx_all, zbx_openssl_info_cb);
3838
3839 if (0 != (program_type & (ZBX_PROGRAM_TYPE_SERVER | ZBX_PROGRAM_TYPE_PROXY | ZBX_PROGRAM_TYPE_AGENTD)))
3840 SSL_CTX_set_psk_server_callback(ctx_all, zbx_psk_server_cb);
3841
3842 SSL_CTX_set_mode(ctx_all, SSL_MODE_AUTO_RETRY);
3843 SSL_CTX_set_options(ctx_all, SSL_OP_CIPHER_SERVER_PREFERENCE | SSL_OP_NO_TICKET);
3844 SSL_CTX_clear_options(ctx_all, SSL_OP_LEGACY_SERVER_CONNECT);
3845 SSL_CTX_set_session_cache_mode(ctx_all, SSL_SESS_CACHE_OFF);
3846
3847 if (SUCCEED == zbx_set_ecdhe_parameters(ctx_all))
3848 ciphers = ZBX_CIPHERS_CERT_ECDHE ZBX_CIPHERS_CERT ":" ZBX_CIPHERS_PSK_ECDHE ZBX_CIPHERS_PSK;
3849 else
3850 ciphers = ZBX_CIPHERS_CERT ":" ZBX_CIPHERS_PSK;
3851
3852 /* override TLS 1.3 ciphersuites with user-defined setting */
3853 if (NULL != CONFIG_TLS_CIPHER_ALL13)
3854 {
3855 #if OPENSSL_VERSION_NUMBER >= 0x1010100fL /* OpenSSL 1.1.1 or newer */
3856 if (1 != SSL_CTX_set_ciphersuites(ctx_all, CONFIG_TLS_CIPHER_ALL13))
3857 {
3858 zbx_snprintf_alloc(&error, &error_alloc, &error_offset, "cannot set list of TLS 1.3"
3859 " ciphersuites from \"TLSCipherAll13\" parameter:");
3860 goto out;
3861 }
3862 #else
3863 zbx_snprintf_alloc(&error, &error_alloc, &error_offset, "cannot set list of TLS 1.3"
3864 " ciphersuites: compiled with OpenSSL version older than 1.1.1."
3865 " Consider not using parameter \"TLSCipherAll13\"");
3866 goto out1;
3867 #endif
3868 }
3869
3870 /* override TLS 1.2 ciphersuites with user-defined setting */
3871 if (NULL != CONFIG_TLS_CIPHER_ALL)
3872 {
3873 if (1 != SSL_CTX_set_cipher_list(ctx_all, CONFIG_TLS_CIPHER_ALL))
3874 {
3875 zbx_snprintf_alloc(&error, &error_alloc, &error_offset, "cannot set list of TLS 1.2"
3876 " ciphersuites from \"TLSCipherAll\" parameter:");
3877 goto out;
3878 }
3879 }
3880 else if (1 != SSL_CTX_set_cipher_list(ctx_all, ciphers))
3881 {
3882 zbx_snprintf_alloc(&error, &error_alloc, &error_offset, "cannot set list of all ciphersuites:");
3883 goto out;
3884 }
3885
3886 zbx_log_ciphersuites(__function_name, "certificate and PSK", ctx_all);
3887 }
3888
3889 if (NULL == ctx_psk)
3890 {
3891 /* cannot override TLS 1.3 PSK ciphersuites */
3892 if (NULL != CONFIG_TLS_CIPHER_PSK13)
3893 {
3894 #if OPENSSL_VERSION_NUMBER >= 0x1010100fL /* OpenSSL 1.1.1 or newer */
3895 zbx_snprintf_alloc(&error, &error_alloc, &error_offset, "parameter \"TLSCipherPSK13\" cannot"
3896 " be applied: the list of PSK ciphersuites is not used");
3897 #else
3898 zbx_snprintf_alloc(&error, &error_alloc, &error_offset, "parameter \"TLSCipherPSK13\" cannot"
3899 " be applied: compiled with OpenSSL version older than 1.1.1");
3900 #endif
3901 goto out1;
3902 }
3903
3904 /* cannot override TLS 1.2 PSK ciphersuites */
3905 if (NULL != CONFIG_TLS_CIPHER_PSK)
3906 {
3907 zbx_snprintf_alloc(&error, &error_alloc, &error_offset, "parameter \"TLSCipherPSK\" cannot"
3908 " be applied: the list of PSK ciphersuites is not used");
3909 goto out1;
3910 }
3911 }
3912
3913 if (NULL == ctx_all)
3914 {
3915 /* cannot override TLS 1.3 ciphersuites */
3916 if (NULL != CONFIG_TLS_CIPHER_ALL13)
3917 {
3918 #if OPENSSL_VERSION_NUMBER >= 0x1010100fL /* OpenSSL 1.1.1 or newer */
3919 zbx_snprintf_alloc(&error, &error_alloc, &error_offset, "parameter \"TLSCipherAll13\" cannot"
3920 " be applied: the combined list of certificate and PSK ciphersuites is"
3921 " not used. Most likely parameters \"TLSCipherCert13\" and/or \"TLSCipherPSK13\""
3922 " are sufficient");
3923 #else
3924 zbx_snprintf_alloc(&error, &error_alloc, &error_offset, "parameter \"TLSCipherAll13\" cannot"
3925 " be applied: compiled with OpenSSL version older than 1.1.1");
3926 #endif
3927 goto out1;
3928 }
3929
3930 /* cannot override TLS 1.2 ciphersuites */
3931 if (NULL != CONFIG_TLS_CIPHER_ALL)
3932 {
3933 zbx_snprintf_alloc(&error, &error_alloc, &error_offset, "parameter \"TLSCipherAll\" cannot"
3934 " be applied: the combined list of certificate and PSK ciphersuites is"
3935 " not used. Most likely parameters \"TLSCipherCert\" and/or \"TLSCipherPSK\""
3936 " are sufficient");
3937 goto out1;
3938 }
3939 }
3940 #else /* HAVE_OPENSSL_WITH_PSK is not defined */
3941 /* cannot use TLSCipherPSK13, TLSCipherPSK, TLSCipherAll13 and TLSCipherAll13 parameters */
3942 /* if PSK is not supported by crypto library */
3943 if (NULL != CONFIG_TLS_CIPHER_PSK13 || NULL != CONFIG_TLS_CIPHER_PSK ||
3944 NULL != CONFIG_TLS_CIPHER_ALL13 || NULL != CONFIG_TLS_CIPHER_ALL)
3945 {
3946 zbx_snprintf_alloc(&error, &error_alloc, &error_offset, "at least one of parameters TLSCipherPSK13,"
3947 " TLSCipherPSK, TLSCipherAll13 or TLSCipherAll is defined. These parameters must not"
3948 " be defined because the program is compiled with OpenSSL without PSK support or"
3949 " LibreSSL");
3950 goto out1;
3951 }
3952 #endif /* defined(HAVE_OPENSSL_WITH_PSK) */
3953 #ifndef _WINDOWS
3954 sigprocmask(SIG_SETMASK, &orig_mask, NULL);
3955 #endif
3956 zabbix_log(LOG_LEVEL_DEBUG, "End of %s()", __function_name);
3957
3958 return;
3959
3960 out_method:
3961 zbx_snprintf_alloc(&error, &error_alloc, &error_offset, "cannot initialize TLS method:");
3962 out:
3963 zbx_tls_error_msg(&error, &error_alloc, &error_offset);
3964 out1:
3965 zabbix_log(LOG_LEVEL_CRIT, "%s", error);
3966 zbx_free(error);
3967 zbx_tls_free();
3968 exit(EXIT_FAILURE);
3969
3970 #undef ZBX_CIPHERS_CERT_ECDHE
3971 #undef ZBX_CIPHERS_CERT
3972 #undef ZBX_CIPHERS_PSK_ECDHE
3973 #undef ZBX_CIPHERS_PSK
3974 #undef ZBX_CIPHERS_PSK_TLS13
3975 }
3976 #endif
3977
3978 /******************************************************************************
3979 * *
3980 * Function: zbx_tls_free_on_signal *
3981 * *
3982 * Purpose: TLS cleanup for using in signal handlers *
3983 * *
3984 ******************************************************************************/
zbx_tls_free_on_signal(void)3985 void zbx_tls_free_on_signal(void)
3986 {
3987 if (NULL != my_psk)
3988 zbx_guaranteed_memset(my_psk, 0, my_psk_len);
3989 }
3990
3991 /******************************************************************************
3992 * *
3993 * Function: zbx_tls_free *
3994 * *
3995 * Purpose: release TLS library resources allocated in zbx_tls_init_parent() *
3996 * and zbx_tls_init_child() *
3997 * *
3998 ******************************************************************************/
zbx_tls_free(void)3999 void zbx_tls_free(void)
4000 {
4001 #if defined(HAVE_POLARSSL)
4002 if (NULL != ctr_drbg)
4003 {
4004 ctr_drbg_free(ctr_drbg);
4005 zbx_free(ctr_drbg);
4006 }
4007
4008 if (NULL != entropy)
4009 {
4010 entropy_free(entropy);
4011 zbx_free(entropy);
4012 }
4013
4014 if (NULL != my_psk)
4015 {
4016 zbx_guaranteed_memset(my_psk, 0, my_psk_len);
4017 my_psk_len = 0;
4018 zbx_free(my_psk);
4019 }
4020
4021 if (NULL != my_priv_key)
4022 {
4023 pk_free(my_priv_key);
4024 zbx_free(my_priv_key);
4025 }
4026
4027 if (NULL != my_cert)
4028 {
4029 x509_crt_free(my_cert);
4030 zbx_free(my_cert);
4031 }
4032
4033 if (NULL != crl)
4034 {
4035 x509_crl_free(crl);
4036 zbx_free(crl);
4037 }
4038
4039 if (NULL != ca_cert)
4040 {
4041 x509_crt_free(ca_cert);
4042 zbx_free(ca_cert);
4043 }
4044
4045 zbx_free(ciphersuites_psk);
4046 zbx_free(ciphersuites_cert);
4047 zbx_free(ciphersuites_all);
4048 #elif defined(HAVE_GNUTLS)
4049 if (NULL != my_cert_creds)
4050 {
4051 gnutls_certificate_free_credentials(my_cert_creds);
4052 my_cert_creds = NULL;
4053 }
4054
4055 if (NULL != my_psk_client_creds)
4056 {
4057 gnutls_psk_free_client_credentials(my_psk_client_creds);
4058 my_psk_client_creds = NULL;
4059 }
4060
4061 if (NULL != my_psk_server_creds)
4062 {
4063 gnutls_psk_free_server_credentials(my_psk_server_creds);
4064 my_psk_server_creds = NULL;
4065 }
4066
4067 /* In GnuTLS versions 2.8.x (RHEL 6 uses v.2.8.5 ?) gnutls_priority_init() in case of error does not release */
4068 /* memory allocated for 'ciphersuites_psk' but releasing it by gnutls_priority_deinit() causes crash. In */
4069 /* GnuTLS versions 3.0.x - 3.1.x (RHEL 7 uses v.3.1.18 ?) gnutls_priority_init() in case of error does */
4070 /* release memory allocated for 'ciphersuites_psk' but does not set pointer to NULL. Newer GnuTLS versions */
4071 /* (e.g. 3.3.8) in case of error in gnutls_priority_init() do release memory and set pointer to NULL. */
4072 /* Therefore we cannot reliably release this memory using the pointer. So, we leave the memory to be cleaned */
4073 /* up by OS - we are in the process of exiting and the data is not secret. */
4074
4075 /* do not release 'ciphersuites_cert', 'ciphersuites_psk' and 'ciphersuites_all' here using */
4076 /* gnutls_priority_deinit() */
4077
4078 if (NULL != my_psk)
4079 {
4080 zbx_guaranteed_memset(my_psk, 0, my_psk_len);
4081 my_psk_len = 0;
4082 zbx_free(my_psk);
4083 }
4084
4085 #if !defined(_WINDOWS)
4086 zbx_tls_library_deinit();
4087 #endif
4088 #elif defined(HAVE_OPENSSL)
4089 if (NULL != ctx_cert)
4090 SSL_CTX_free(ctx_cert);
4091
4092 #if defined(HAVE_OPENSSL_WITH_PSK)
4093 if (NULL != ctx_psk)
4094 SSL_CTX_free(ctx_psk);
4095
4096 if (NULL != ctx_all)
4097 SSL_CTX_free(ctx_all);
4098 #endif
4099 if (NULL != my_psk)
4100 {
4101 zbx_guaranteed_memset(my_psk, 0, my_psk_len);
4102 my_psk_len = 0;
4103 zbx_free(my_psk);
4104 }
4105
4106 #if !defined(_WINDOWS)
4107 zbx_tls_library_deinit();
4108 #endif
4109 #endif
4110 }
4111
4112 /******************************************************************************
4113 * *
4114 * Function: zbx_tls_connect *
4115 * *
4116 * Purpose: establish a TLS connection over an established TCP connection *
4117 * *
4118 * Parameters: *
4119 * s - [IN] socket with opened connection *
4120 * error - [OUT] dynamically allocated memory with error message *
4121 * tls_connect - [IN] how to connect. Allowed values: *
4122 * ZBX_TCP_SEC_TLS_CERT, ZBX_TCP_SEC_TLS_PSK. *
4123 * tls_arg1 - [IN] required issuer of peer certificate (may be NULL *
4124 * or empty string if not important) or PSK identity *
4125 * to connect with depending on value of *
4126 * 'tls_connect'. *
4127 * tls_arg2 - [IN] required subject of peer certificate (may be NULL *
4128 * or empty string if not important) or PSK *
4129 * (in hex-string) to connect with depending on value *
4130 * of 'tls_connect'. *
4131 * *
4132 * Return value: *
4133 * SUCCEED - successful TLS handshake with a valid certificate or PSK *
4134 * FAIL - an error occurred *
4135 * *
4136 ******************************************************************************/
4137 #if defined(HAVE_POLARSSL)
zbx_tls_connect(zbx_socket_t * s,unsigned int tls_connect,const char * tls_arg1,const char * tls_arg2,char ** error)4138 int zbx_tls_connect(zbx_socket_t *s, unsigned int tls_connect, const char *tls_arg1, const char *tls_arg2,
4139 char **error)
4140 {
4141 const char *__function_name = "zbx_tls_connect";
4142 int ret = FAIL, res;
4143 #if defined(_WINDOWS)
4144 double sec;
4145 #endif
4146 if (ZBX_TCP_SEC_TLS_CERT == tls_connect)
4147 {
4148 zabbix_log(LOG_LEVEL_DEBUG, "In %s(): issuer:\"%s\" subject:\"%s\"", __function_name,
4149 ZBX_NULL2EMPTY_STR(tls_arg1), ZBX_NULL2EMPTY_STR(tls_arg2));
4150
4151 if (NULL == ciphersuites_cert)
4152 {
4153 *error = zbx_strdup(*error, "cannot connect with TLS and certificate: no valid certificate"
4154 " loaded");
4155 goto out1;
4156 }
4157 }
4158 else if (ZBX_TCP_SEC_TLS_PSK == tls_connect)
4159 {
4160 zabbix_log(LOG_LEVEL_DEBUG, "In %s(): psk_identity:\"%s\"", __function_name,
4161 ZBX_NULL2EMPTY_STR(tls_arg1));
4162
4163 if (NULL == ciphersuites_psk)
4164 {
4165 *error = zbx_strdup(*error, "cannot connect with TLS and PSK: no valid PSK loaded");
4166 goto out1;
4167 }
4168 }
4169 else
4170 {
4171 *error = zbx_strdup(*error, "invalid connection parameters");
4172 THIS_SHOULD_NEVER_HAPPEN;
4173 goto out1;
4174 }
4175
4176 /* set up TLS context */
4177
4178 s->tls_ctx = zbx_malloc(s->tls_ctx, sizeof(zbx_tls_context_t));
4179 s->tls_ctx->ctx = zbx_malloc(NULL, sizeof(ssl_context));
4180
4181 if (0 != (res = ssl_init(s->tls_ctx->ctx)))
4182 {
4183 zbx_tls_error_msg(res, "ssl_init(): ", error);
4184 goto out;
4185 }
4186
4187 ssl_set_endpoint(s->tls_ctx->ctx, SSL_IS_CLIENT);
4188
4189 /* Set RNG callback where to get random numbers from */
4190 ssl_set_rng(s->tls_ctx->ctx, ctr_drbg_random, ctr_drbg);
4191
4192 /* disable using of session tickets (by default it is enabled on client) */
4193 if (0 != (res = ssl_set_session_tickets(s->tls_ctx->ctx, SSL_SESSION_TICKETS_DISABLED)))
4194 {
4195 zbx_tls_error_msg(res, "ssl_set_session_tickets(): ", error);
4196 goto out;
4197 }
4198
4199 if (SUCCEED == ZBX_CHECK_LOG_LEVEL(LOG_LEVEL_TRACE))
4200 {
4201 /* Set our own debug callback function. The 3rd parameter of ssl_set_dbg() we set to NULL. It will be */
4202 /* passed as the 1st parameter to our callback function and will be ignored there. */
4203 ssl_set_dbg(s->tls_ctx->ctx, polarssl_debug_cb, NULL);
4204
4205 /* For Zabbix LOG_LEVEL_TRACE, PolarSSL debug level 3 seems the best. Recompile with 4 (apparently */
4206 /* the highest PolarSSL debug level) to dump also network raw bytes. */
4207 debug_set_threshold(3);
4208 }
4209
4210 /* Set callback functions for receiving and sending data via socket. */
4211 /* Functions provided by PolarSSL work well so far, no need to invent our own. */
4212 ssl_set_bio(s->tls_ctx->ctx, net_recv, &s->socket, net_send, &s->socket);
4213
4214 /* set protocol version to TLS 1.2 */
4215 ssl_set_min_version(s->tls_ctx->ctx, ZBX_TLS_MIN_MAJOR_VER, ZBX_TLS_MIN_MINOR_VER);
4216 ssl_set_max_version(s->tls_ctx->ctx, ZBX_TLS_MAX_MAJOR_VER, ZBX_TLS_MAX_MINOR_VER);
4217
4218 if (ZBX_TCP_SEC_TLS_CERT == tls_connect) /* use certificates */
4219 {
4220 ssl_set_authmode(s->tls_ctx->ctx, SSL_VERIFY_REQUIRED);
4221 ssl_set_ciphersuites(s->tls_ctx->ctx, ciphersuites_cert);
4222
4223 /* set CA certificate and certificate revocation lists */
4224 ssl_set_ca_chain(s->tls_ctx->ctx, ca_cert, crl, NULL);
4225
4226 if (0 != (res = ssl_set_own_cert(s->tls_ctx->ctx, my_cert, my_priv_key)))
4227 {
4228 zbx_tls_error_msg(res, "ssl_set_own_cert(): ", error);
4229 goto out;
4230 }
4231 }
4232 else /* use a pre-shared key */
4233 {
4234 ssl_set_ciphersuites(s->tls_ctx->ctx, ciphersuites_psk);
4235
4236 if (NULL == tls_arg2) /* PSK is not set from DB */
4237 {
4238 /* set up the PSK from a configuration file (always in agentd and a case in active proxy */
4239 /* when it connects to server) */
4240
4241 if (0 != (res = ssl_set_psk(s->tls_ctx->ctx, (const unsigned char *)my_psk, my_psk_len,
4242 (const unsigned char *)my_psk_identity, my_psk_identity_len)))
4243 {
4244 zbx_tls_error_msg(res, "ssl_set_psk(): ", error);
4245 goto out;
4246 }
4247 }
4248 else
4249 {
4250 /* PSK comes from a database (case for a server/proxy when it connects to an agent for */
4251 /* passive checks, for a server when it connects to a passive proxy) */
4252
4253 int psk_len;
4254 char psk_buf[HOST_TLS_PSK_LEN / 2];
4255
4256 if (0 >= (psk_len = zbx_psk_hex2bin((unsigned char *)tls_arg2, (unsigned char *)psk_buf,
4257 sizeof(psk_buf))))
4258 {
4259 *error = zbx_strdup(*error, "invalid PSK");
4260 goto out;
4261 }
4262
4263 if (0 != (res = ssl_set_psk(s->tls_ctx->ctx, (const unsigned char *)psk_buf, (size_t)psk_len,
4264 (const unsigned char *)tls_arg1, strlen(tls_arg1))))
4265 {
4266 zbx_tls_error_msg(res, "ssl_set_psk(): ", error);
4267 goto out;
4268 }
4269 }
4270 }
4271
4272 #if defined(_WINDOWS)
4273 zbx_alarm_flag_clear();
4274 sec = zbx_time();
4275 #endif
4276 while (0 != (res = ssl_handshake(s->tls_ctx->ctx)))
4277 {
4278 #if defined(_WINDOWS)
4279 if (s->timeout < zbx_time() - sec)
4280 zbx_alarm_flag_set();
4281 #endif
4282 if (SUCCEED == zbx_alarm_timed_out())
4283 {
4284 *error = zbx_strdup(*error, "ssl_handshake() timed out");
4285 goto out;
4286 }
4287
4288 if (POLARSSL_ERR_NET_WANT_READ != res && POLARSSL_ERR_NET_WANT_WRITE != res)
4289 {
4290 if (POLARSSL_ERR_X509_CERT_VERIFY_FAILED == res)
4291 {
4292 /* Standard PolarSSL error message might not be very informative in this case. For */
4293 /* example, if certificate validity starts in future, PolarSSL 1.3.9 would produce a */
4294 /* message "X509 - Certificate verification failed, e.g. CRL, CA or signature check */
4295 /* failed" which does not give a precise reason. Here we try to get more detailed */
4296 /* reason why peer certificate was rejected by using some knowledge about PolarSSL */
4297 /* internals. */
4298 zbx_tls_cert_error_msg((unsigned int)s->tls_ctx->ctx->session_negotiate->verify_result,
4299 error);
4300 zbx_tls_close(s);
4301 goto out1;
4302 }
4303
4304 zbx_tls_error_msg(res, "ssl_handshake(): ", error);
4305 goto out;
4306 }
4307 }
4308
4309 if (ZBX_TCP_SEC_TLS_CERT == tls_connect)
4310 {
4311 /* log peer certificate information for debugging */
4312 zbx_log_peer_cert(__function_name, s->tls_ctx);
4313
4314 /* basic verification of peer certificate was done during handshake */
4315
4316 /* if required verify peer certificate Issuer and Subject */
4317 if (SUCCEED != zbx_verify_issuer_subject(s->tls_ctx, tls_arg1, tls_arg2, error))
4318 {
4319 zbx_tls_close(s);
4320 goto out1;
4321 }
4322 }
4323 else /* pre-shared key */
4324 {
4325 /* special print: s->tls_ctx->ctx->psk_identity is not '\0'-terminated */
4326 zabbix_log(LOG_LEVEL_DEBUG, "%s() PSK identity: \"%.*s\"", __function_name,
4327 (int)s->tls_ctx->ctx->psk_identity_len, s->tls_ctx->ctx->psk_identity);
4328 }
4329
4330 s->connection_type = tls_connect;
4331
4332 zabbix_log(LOG_LEVEL_DEBUG, "End of %s():SUCCEED (established %s %s)", __function_name,
4333 ssl_get_version(s->tls_ctx->ctx), ssl_get_ciphersuite(s->tls_ctx->ctx));
4334
4335 return SUCCEED;
4336
4337 out: /* an error occurred */
4338 ssl_free(s->tls_ctx->ctx);
4339 zbx_free(s->tls_ctx->ctx);
4340 zbx_free(s->tls_ctx);
4341 out1:
4342 zabbix_log(LOG_LEVEL_DEBUG, "End of %s():%s error:'%s'", __function_name, zbx_result_string(ret),
4343 ZBX_NULL2EMPTY_STR(*error));
4344 return ret;
4345 }
4346 #elif defined(HAVE_GNUTLS)
zbx_tls_connect(zbx_socket_t * s,unsigned int tls_connect,const char * tls_arg1,const char * tls_arg2,char ** error)4347 int zbx_tls_connect(zbx_socket_t *s, unsigned int tls_connect, const char *tls_arg1, const char *tls_arg2,
4348 char **error)
4349 {
4350 const char *__function_name = "zbx_tls_connect";
4351 int ret = FAIL, res;
4352 #if defined(_WINDOWS)
4353 double sec;
4354 #endif
4355 if (ZBX_TCP_SEC_TLS_CERT == tls_connect)
4356 {
4357 zabbix_log(LOG_LEVEL_DEBUG, "In %s(): issuer:\"%s\" subject:\"%s\"", __function_name,
4358 ZBX_NULL2EMPTY_STR(tls_arg1), ZBX_NULL2EMPTY_STR(tls_arg2));
4359 }
4360 else if (ZBX_TCP_SEC_TLS_PSK == tls_connect)
4361 {
4362 zabbix_log(LOG_LEVEL_DEBUG, "In %s(): psk_identity:\"%s\"", __function_name,
4363 ZBX_NULL2EMPTY_STR(tls_arg1));
4364 }
4365 else
4366 {
4367 *error = zbx_strdup(*error, "invalid connection parameters");
4368 THIS_SHOULD_NEVER_HAPPEN;
4369 goto out1;
4370 }
4371
4372 /* set up TLS context */
4373
4374 s->tls_ctx = zbx_malloc(s->tls_ctx, sizeof(zbx_tls_context_t));
4375 s->tls_ctx->ctx = NULL;
4376 s->tls_ctx->psk_client_creds = NULL;
4377 s->tls_ctx->psk_server_creds = NULL;
4378
4379 if (GNUTLS_E_SUCCESS != (res = gnutls_init(&s->tls_ctx->ctx, GNUTLS_CLIENT | GNUTLS_NO_EXTENSIONS)))
4380 /* GNUTLS_NO_EXTENSIONS is used because we do not currently support extensions (e.g. session */
4381 /* tickets and OCSP) */
4382 {
4383 *error = zbx_dsprintf(*error, "gnutls_init() failed: %d %s", res, gnutls_strerror(res));
4384 goto out;
4385 }
4386
4387 if (ZBX_TCP_SEC_TLS_CERT == tls_connect)
4388 {
4389 if (NULL == ciphersuites_cert)
4390 {
4391 *error = zbx_strdup(*error, "cannot connect with TLS and certificate: no valid certificate"
4392 " loaded");
4393 goto out;
4394 }
4395
4396 if (GNUTLS_E_SUCCESS != (res = gnutls_priority_set(s->tls_ctx->ctx, ciphersuites_cert)))
4397 {
4398 *error = zbx_dsprintf(*error, "gnutls_priority_set() for 'ciphersuites_cert' failed: %d %s",
4399 res, gnutls_strerror(res));
4400 goto out;
4401 }
4402
4403 if (GNUTLS_E_SUCCESS != (res = gnutls_credentials_set(s->tls_ctx->ctx, GNUTLS_CRD_CERTIFICATE,
4404 my_cert_creds)))
4405 {
4406 *error = zbx_dsprintf(*error, "gnutls_credentials_set() for certificate failed: %d %s", res,
4407 gnutls_strerror(res));
4408 goto out;
4409 }
4410 }
4411 else /* use a pre-shared key */
4412 {
4413 if (NULL == ciphersuites_psk)
4414 {
4415 *error = zbx_strdup(*error, "cannot connect with TLS and PSK: no valid PSK loaded");
4416 goto out;
4417 }
4418
4419 if (GNUTLS_E_SUCCESS != (res = gnutls_priority_set(s->tls_ctx->ctx, ciphersuites_psk)))
4420 {
4421 *error = zbx_dsprintf(*error, "gnutls_priority_set() for 'ciphersuites_psk' failed: %d %s", res,
4422 gnutls_strerror(res));
4423 goto out;
4424 }
4425
4426 if (NULL == tls_arg2) /* PSK is not set from DB */
4427 {
4428 /* set up the PSK from a configuration file (always in agentd and a case in active proxy */
4429 /* when it connects to server) */
4430
4431 if (GNUTLS_E_SUCCESS != (res = gnutls_credentials_set(s->tls_ctx->ctx, GNUTLS_CRD_PSK,
4432 my_psk_client_creds)))
4433 {
4434 *error = zbx_dsprintf(*error, "gnutls_credentials_set() for psk failed: %d %s", res,
4435 gnutls_strerror(res));
4436 goto out;
4437 }
4438 }
4439 else
4440 {
4441 /* PSK comes from a database (case for a server/proxy when it connects to an agent for */
4442 /* passive checks, for a server when it connects to a passive proxy) */
4443
4444 gnutls_datum_t key;
4445 int psk_len;
4446 unsigned char psk_buf[HOST_TLS_PSK_LEN / 2];
4447
4448 if (0 >= (psk_len = zbx_psk_hex2bin((unsigned char *)tls_arg2, psk_buf, sizeof(psk_buf))))
4449 {
4450 *error = zbx_strdup(*error, "invalid PSK");
4451 goto out;
4452 }
4453
4454 if (GNUTLS_E_SUCCESS != (res = gnutls_psk_allocate_client_credentials(
4455 &s->tls_ctx->psk_client_creds)))
4456 {
4457 *error = zbx_dsprintf(*error, "gnutls_psk_allocate_client_credentials() failed: %d %s",
4458 res, gnutls_strerror(res));
4459 goto out;
4460 }
4461
4462 key.data = psk_buf;
4463 key.size = (unsigned int)psk_len;
4464
4465 /* Simplified. 'tls_arg1' (PSK identity) should have been prepared as required by RFC 4518. */
4466 if (GNUTLS_E_SUCCESS != (res = gnutls_psk_set_client_credentials(s->tls_ctx->psk_client_creds,
4467 tls_arg1, &key, GNUTLS_PSK_KEY_RAW)))
4468 {
4469 *error = zbx_dsprintf(*error, "gnutls_psk_set_client_credentials() failed: %d %s", res,
4470 gnutls_strerror(res));
4471 goto out;
4472 }
4473
4474 if (GNUTLS_E_SUCCESS != (res = gnutls_credentials_set(s->tls_ctx->ctx, GNUTLS_CRD_PSK,
4475 s->tls_ctx->psk_client_creds)))
4476 {
4477 *error = zbx_dsprintf(*error, "gnutls_credentials_set() for psk failed: %d %s", res,
4478 gnutls_strerror(res));
4479 goto out;
4480 }
4481 }
4482 }
4483
4484 if (SUCCEED == ZBX_CHECK_LOG_LEVEL(LOG_LEVEL_TRACE))
4485 {
4486 /* set our own debug callback function */
4487 gnutls_global_set_log_function(zbx_gnutls_debug_cb);
4488
4489 /* for Zabbix LOG_LEVEL_TRACE, GnuTLS debug level 4 seems the best */
4490 /* (the highest GnuTLS debug level is 9) */
4491 gnutls_global_set_log_level(4);
4492 }
4493 else
4494 gnutls_global_set_log_level(0); /* restore default log level */
4495
4496 /* set our own callback function to log issues into Zabbix log */
4497 gnutls_global_set_audit_log_function(zbx_gnutls_audit_cb);
4498
4499 gnutls_transport_set_int(s->tls_ctx->ctx, ZBX_SOCKET_TO_INT(s->socket));
4500
4501 /* TLS handshake */
4502
4503 #if defined(_WINDOWS)
4504 zbx_alarm_flag_clear();
4505 sec = zbx_time();
4506 #endif
4507 while (GNUTLS_E_SUCCESS != (res = gnutls_handshake(s->tls_ctx->ctx)))
4508 {
4509 #if defined(_WINDOWS)
4510 if (s->timeout < zbx_time() - sec)
4511 zbx_alarm_flag_set();
4512 #endif
4513 if (SUCCEED == zbx_alarm_timed_out())
4514 {
4515 *error = zbx_strdup(*error, "gnutls_handshake() timed out");
4516 goto out;
4517 }
4518
4519 if (GNUTLS_E_INTERRUPTED == res || GNUTLS_E_AGAIN == res)
4520 {
4521 continue;
4522 }
4523 else if (GNUTLS_E_WARNING_ALERT_RECEIVED == res || GNUTLS_E_FATAL_ALERT_RECEIVED == res)
4524 {
4525 const char *msg;
4526 int alert;
4527
4528 /* server sent an alert to us */
4529 alert = gnutls_alert_get(s->tls_ctx->ctx);
4530
4531 if (NULL == (msg = gnutls_alert_get_name(alert)))
4532 msg = "unknown";
4533
4534 if (GNUTLS_E_WARNING_ALERT_RECEIVED == res)
4535 {
4536 zabbix_log(LOG_LEVEL_WARNING, "%s() gnutls_handshake() received a warning alert: %d"
4537 " %s", __function_name, alert, msg);
4538 continue;
4539 }
4540 else /* GNUTLS_E_FATAL_ALERT_RECEIVED */
4541 {
4542 *error = zbx_dsprintf(*error, "%s(): gnutls_handshake() failed with fatal alert: %d %s",
4543 __function_name, alert, msg);
4544 goto out;
4545 }
4546 }
4547 else
4548 {
4549 int level;
4550
4551 /* log "peer has closed connection" case with debug level */
4552 level = (GNUTLS_E_PREMATURE_TERMINATION == res ? LOG_LEVEL_DEBUG : LOG_LEVEL_WARNING);
4553
4554 if (SUCCEED == ZBX_CHECK_LOG_LEVEL(level))
4555 {
4556 zabbix_log(level, "%s() gnutls_handshake() returned: %d %s",
4557 __function_name, res, gnutls_strerror(res));
4558 }
4559
4560 if (0 != gnutls_error_is_fatal(res))
4561 {
4562 *error = zbx_dsprintf(*error, "%s(): gnutls_handshake() failed: %d %s",
4563 __function_name, res, gnutls_strerror(res));
4564 goto out;
4565 }
4566 }
4567 }
4568
4569 if (ZBX_TCP_SEC_TLS_CERT == tls_connect)
4570 {
4571 /* log peer certificate information for debugging */
4572 zbx_log_peer_cert(__function_name, s->tls_ctx);
4573
4574 /* perform basic verification of peer certificate */
4575 if (SUCCEED != zbx_verify_peer_cert(s->tls_ctx->ctx, error))
4576 {
4577 zbx_tls_close(s);
4578 goto out1;
4579 }
4580
4581 /* if required verify peer certificate Issuer and Subject */
4582 if (SUCCEED != zbx_verify_issuer_subject(s->tls_ctx, tls_arg1, tls_arg2, error))
4583 {
4584 zbx_tls_close(s);
4585 goto out1;
4586 }
4587 }
4588
4589 s->connection_type = tls_connect;
4590
4591 zabbix_log(LOG_LEVEL_DEBUG, "End of %s():SUCCEED (established %s %s-%s-%s-" ZBX_FS_SIZE_T ")", __function_name,
4592 gnutls_protocol_get_name(gnutls_protocol_get_version(s->tls_ctx->ctx)),
4593 gnutls_kx_get_name(gnutls_kx_get(s->tls_ctx->ctx)),
4594 gnutls_cipher_get_name(gnutls_cipher_get(s->tls_ctx->ctx)),
4595 gnutls_mac_get_name(gnutls_mac_get(s->tls_ctx->ctx)),
4596 (zbx_fs_size_t)gnutls_mac_get_key_size(gnutls_mac_get(s->tls_ctx->ctx)));
4597
4598 return SUCCEED;
4599
4600 out: /* an error occurred */
4601 if (NULL != s->tls_ctx->ctx)
4602 {
4603 gnutls_credentials_clear(s->tls_ctx->ctx);
4604 gnutls_deinit(s->tls_ctx->ctx);
4605 }
4606
4607 if (NULL != s->tls_ctx->psk_client_creds)
4608 gnutls_psk_free_client_credentials(s->tls_ctx->psk_client_creds);
4609
4610 zbx_free(s->tls_ctx);
4611 out1:
4612 zabbix_log(LOG_LEVEL_DEBUG, "End of %s():%s error:'%s'", __function_name, zbx_result_string(ret),
4613 ZBX_NULL2EMPTY_STR(*error));
4614 return ret;
4615 }
4616 #elif defined(HAVE_OPENSSL)
zbx_tls_connect(zbx_socket_t * s,unsigned int tls_connect,const char * tls_arg1,const char * tls_arg2,char ** error)4617 int zbx_tls_connect(zbx_socket_t *s, unsigned int tls_connect, const char *tls_arg1, const char *tls_arg2,
4618 char **error)
4619 {
4620 const char *__function_name = "zbx_tls_connect";
4621 int ret = FAIL, res;
4622 size_t error_alloc = 0, error_offset = 0;
4623 #if defined(_WINDOWS)
4624 double sec;
4625 #endif
4626 #if defined(HAVE_OPENSSL_WITH_PSK)
4627 char psk_buf[HOST_TLS_PSK_LEN / 2];
4628 #endif
4629
4630 s->tls_ctx = zbx_malloc(s->tls_ctx, sizeof(zbx_tls_context_t));
4631 s->tls_ctx->ctx = NULL;
4632
4633 if (ZBX_TCP_SEC_TLS_CERT == tls_connect)
4634 {
4635 zabbix_log(LOG_LEVEL_DEBUG, "In %s(): issuer:\"%s\" subject:\"%s\"", __function_name,
4636 ZBX_NULL2EMPTY_STR(tls_arg1), ZBX_NULL2EMPTY_STR(tls_arg2));
4637
4638 if (NULL == ctx_cert)
4639 {
4640 *error = zbx_strdup(*error, "cannot connect with TLS and certificate: no valid certificate"
4641 " loaded");
4642 goto out;
4643 }
4644
4645 if (NULL == (s->tls_ctx->ctx = SSL_new(ctx_cert)))
4646 {
4647 zbx_snprintf_alloc(error, &error_alloc, &error_offset, "cannot create connection context:");
4648 zbx_tls_error_msg(error, &error_alloc, &error_offset);
4649 goto out;
4650 }
4651 }
4652 else if (ZBX_TCP_SEC_TLS_PSK == tls_connect)
4653 {
4654 zabbix_log(LOG_LEVEL_DEBUG, "In %s(): psk_identity:\"%s\"", __function_name,
4655 ZBX_NULL2EMPTY_STR(tls_arg1));
4656 #if defined(HAVE_OPENSSL_WITH_PSK)
4657 if (NULL == ctx_psk)
4658 {
4659 *error = zbx_strdup(*error, "cannot connect with TLS and PSK: no valid PSK loaded");
4660 goto out;
4661 }
4662
4663 if (NULL == (s->tls_ctx->ctx = SSL_new(ctx_psk)))
4664 {
4665 zbx_snprintf_alloc(error, &error_alloc, &error_offset, "cannot create connection context:");
4666 zbx_tls_error_msg(error, &error_alloc, &error_offset);
4667 goto out;
4668 }
4669
4670 if (NULL == tls_arg2) /* PSK is not set from DB */
4671 {
4672 /* Set up PSK global variables from a configuration file (always in agentd and a case when */
4673 /* active proxy connects to server). Here we set it only in case of active proxy */
4674 /* because for other programs it has already been set in zbx_tls_init_child(). */
4675
4676 if (0 != (program_type & ZBX_PROGRAM_TYPE_PROXY_ACTIVE))
4677 {
4678 psk_identity_for_cb = my_psk_identity;
4679 psk_identity_len_for_cb = my_psk_identity_len;
4680 psk_for_cb = my_psk;
4681 psk_len_for_cb = my_psk_len;
4682 }
4683 }
4684 else
4685 {
4686 /* PSK comes from a database (case for a server/proxy when it connects to an agent for */
4687 /* passive checks, for a server when it connects to a passive proxy) */
4688
4689 int psk_len;
4690
4691 if (0 >= (psk_len = zbx_psk_hex2bin((unsigned char *)tls_arg2, (unsigned char *)psk_buf,
4692 sizeof(psk_buf))))
4693 {
4694 *error = zbx_strdup(*error, "invalid PSK");
4695 goto out;
4696 }
4697
4698 /* some data reside in stack but it will be available at the time when a PSK client callback */
4699 /* function copies the data into buffers provided by OpenSSL within the callback */
4700 psk_identity_for_cb = tls_arg1; /* string is on stack */
4701 /* NULL check to silence analyzer warning */
4702 psk_identity_len_for_cb = (NULL == tls_arg1 ? 0 : strlen(tls_arg1));
4703 psk_for_cb = psk_buf; /* buffer is on stack */
4704 psk_len_for_cb = (size_t)psk_len;
4705 }
4706 #else
4707 *error = zbx_strdup(*error, "cannot connect with TLS and PSK: support for PSK was not compiled in");
4708 goto out;
4709 #endif
4710 }
4711 else
4712 {
4713 *error = zbx_strdup(*error, "invalid connection parameters");
4714 THIS_SHOULD_NEVER_HAPPEN;
4715 goto out1;
4716 }
4717
4718 /* set our connected TCP socket to TLS context */
4719 if (1 != SSL_set_fd(s->tls_ctx->ctx, s->socket))
4720 {
4721 *error = zbx_strdup(*error, "cannot set socket for TLS context");
4722 goto out;
4723 }
4724
4725 /* TLS handshake */
4726
4727 info_buf[0] = '\0'; /* empty buffer for zbx_openssl_info_cb() messages */
4728 #if defined(_WINDOWS)
4729 zbx_alarm_flag_clear();
4730 sec = zbx_time();
4731 #endif
4732 if (1 != (res = SSL_connect(s->tls_ctx->ctx)))
4733 {
4734 int result_code;
4735
4736 #if defined(_WINDOWS)
4737 if (s->timeout < zbx_time() - sec)
4738 zbx_alarm_flag_set();
4739 #endif
4740 if (SUCCEED == zbx_alarm_timed_out())
4741 {
4742 *error = zbx_strdup(*error, "SSL_connect() timed out");
4743 goto out;
4744 }
4745
4746 if (ZBX_TCP_SEC_TLS_CERT == tls_connect)
4747 {
4748 long verify_result;
4749
4750 /* In case of certificate error SSL_get_verify_result() provides more helpful diagnostics */
4751 /* than other methods. Include it as first but continue with other diagnostics. */
4752 if (X509_V_OK != (verify_result = SSL_get_verify_result(s->tls_ctx->ctx)))
4753 {
4754 zbx_snprintf_alloc(error, &error_alloc, &error_offset, "%s: ",
4755 X509_verify_cert_error_string(verify_result));
4756 }
4757 }
4758
4759 result_code = SSL_get_error(s->tls_ctx->ctx, res);
4760
4761 switch (result_code)
4762 {
4763 case SSL_ERROR_NONE: /* handshake successful */
4764 break;
4765 case SSL_ERROR_ZERO_RETURN:
4766 zbx_snprintf_alloc(error, &error_alloc, &error_offset,
4767 "TLS connection has been closed during handshake");
4768 goto out;
4769 case SSL_ERROR_SYSCALL:
4770 if (0 == ERR_peek_error())
4771 {
4772 if (0 == res)
4773 {
4774 zbx_snprintf_alloc(error, &error_alloc, &error_offset,
4775 "connection closed by peer");
4776 }
4777 else if (-1 == res)
4778 {
4779 zbx_snprintf_alloc(error, &error_alloc, &error_offset, "SSL_connect()"
4780 " I/O error: %s",
4781 strerror_from_system(zbx_socket_last_error()));
4782 }
4783 else
4784 {
4785 /* "man SSL_get_error" describes only res == 0 and res == -1 for */
4786 /* SSL_ERROR_SYSCALL case */
4787 zbx_snprintf_alloc(error, &error_alloc, &error_offset, "SSL_connect()"
4788 " returned undocumented code %d", res);
4789 }
4790 }
4791 else
4792 {
4793 zbx_snprintf_alloc(error, &error_alloc, &error_offset, "SSL_connect() set"
4794 " result code to SSL_ERROR_SYSCALL:");
4795 zbx_tls_error_msg(error, &error_alloc, &error_offset);
4796 zbx_snprintf_alloc(error, &error_alloc, &error_offset, "%s", info_buf);
4797 }
4798 goto out;
4799 case SSL_ERROR_SSL:
4800 zbx_snprintf_alloc(error, &error_alloc, &error_offset, "SSL_connect() set"
4801 " result code to SSL_ERROR_SSL:");
4802 zbx_tls_error_msg(error, &error_alloc, &error_offset);
4803 zbx_snprintf_alloc(error, &error_alloc, &error_offset, "%s", info_buf);
4804 goto out;
4805 default:
4806 zbx_snprintf_alloc(error, &error_alloc, &error_offset, "SSL_connect() set result code"
4807 " to %d", result_code);
4808 zbx_tls_error_msg(error, &error_alloc, &error_offset);
4809 zbx_snprintf_alloc(error, &error_alloc, &error_offset, "%s", info_buf);
4810 goto out;
4811 }
4812 }
4813
4814 if (ZBX_TCP_SEC_TLS_CERT == tls_connect)
4815 {
4816 long verify_result;
4817
4818 /* log peer certificate information for debugging */
4819 zbx_log_peer_cert(__function_name, s->tls_ctx);
4820
4821 /* perform basic verification of peer certificate */
4822 if (X509_V_OK != (verify_result = SSL_get_verify_result(s->tls_ctx->ctx)))
4823 {
4824 zbx_snprintf_alloc(error, &error_alloc, &error_offset, "%s",
4825 X509_verify_cert_error_string(verify_result));
4826 zbx_tls_close(s);
4827 goto out1;
4828 }
4829
4830 /* if required verify peer certificate Issuer and Subject */
4831 if (SUCCEED != zbx_verify_issuer_subject(s->tls_ctx, tls_arg1, tls_arg2, error))
4832 {
4833 zbx_tls_close(s);
4834 goto out1;
4835 }
4836 }
4837
4838 s->connection_type = tls_connect;
4839
4840 zabbix_log(LOG_LEVEL_DEBUG, "End of %s():SUCCEED (established %s %s)", __function_name,
4841 SSL_get_version(s->tls_ctx->ctx), SSL_get_cipher(s->tls_ctx->ctx));
4842
4843 return SUCCEED;
4844
4845 out: /* an error occurred */
4846 if (NULL != s->tls_ctx->ctx)
4847 SSL_free(s->tls_ctx->ctx);
4848
4849 zbx_free(s->tls_ctx);
4850 out1:
4851 zabbix_log(LOG_LEVEL_DEBUG, "End of %s():%s error:'%s'", __function_name, zbx_result_string(ret),
4852 ZBX_NULL2EMPTY_STR(*error));
4853 return ret;
4854 }
4855 #endif
4856
4857 /******************************************************************************
4858 * *
4859 * Function: zbx_tls_accept *
4860 * *
4861 * Purpose: establish a TLS connection over an accepted TCP connection *
4862 * *
4863 * Parameters: *
4864 * s - [IN] socket with opened connection *
4865 * error - [OUT] dynamically allocated memory with error message *
4866 * tls_accept - [IN] type of connection to accept. Can be be either *
4867 * ZBX_TCP_SEC_TLS_CERT or ZBX_TCP_SEC_TLS_PSK, or *
4868 * a bitwise 'OR' of both. *
4869 * *
4870 * Return value: *
4871 * SUCCEED - successful TLS handshake with a valid certificate or PSK *
4872 * FAIL - an error occurred *
4873 * *
4874 ******************************************************************************/
4875 #if defined(HAVE_POLARSSL)
zbx_tls_accept(zbx_socket_t * s,unsigned int tls_accept,char ** error)4876 int zbx_tls_accept(zbx_socket_t *s, unsigned int tls_accept, char **error)
4877 {
4878 const char *__function_name = "zbx_tls_accept";
4879 int ret = FAIL, res;
4880 const ssl_ciphersuite_t *info;
4881 #if defined(_WINDOWS)
4882 double sec;
4883 #endif
4884 zabbix_log(LOG_LEVEL_DEBUG, "In %s()", __function_name);
4885
4886 /* set up TLS context */
4887
4888 s->tls_ctx = zbx_malloc(s->tls_ctx, sizeof(zbx_tls_context_t));
4889 s->tls_ctx->ctx = zbx_malloc(NULL, sizeof(ssl_context));
4890
4891 if (0 != (res = ssl_init(s->tls_ctx->ctx)))
4892 {
4893 zbx_tls_error_msg(res, "ssl_init(): ", error);
4894 goto out;
4895 }
4896
4897 ssl_set_endpoint(s->tls_ctx->ctx, SSL_IS_SERVER);
4898
4899 /* Set RNG callback where to get random numbers from */
4900 ssl_set_rng(s->tls_ctx->ctx, ctr_drbg_random, ctr_drbg);
4901
4902 /* explicitly disable using of session tickets (although by default it is disabled on server) */
4903 if (0 != (res = ssl_set_session_tickets(s->tls_ctx->ctx, SSL_SESSION_TICKETS_DISABLED)))
4904 {
4905 zbx_tls_error_msg(res, "ssl_set_session_tickets(): ", error);
4906 goto out;
4907 }
4908
4909 if (SUCCEED == ZBX_CHECK_LOG_LEVEL(LOG_LEVEL_TRACE))
4910 {
4911 /* Set our own debug callback function. The 3rd parameter of ssl_set_dbg() we set to NULL. It will be */
4912 /* passed as the 1st parameter to our callback function and will be ignored there. */
4913 ssl_set_dbg(s->tls_ctx->ctx, polarssl_debug_cb, NULL);
4914
4915 /* For Zabbix LOG_LEVEL_TRACE, PolarSSL debug level 3 seems the best. Recompile with 4 (apparently */
4916 /* the highest PolarSSL debug level) to dump also network raw bytes. */
4917 debug_set_threshold(3);
4918 }
4919
4920 /* Set callback functions for receiving and sending data via socket. */
4921 /* Functions provided by PolarSSL work well so far, no need to invent our own. */
4922 ssl_set_bio(s->tls_ctx->ctx, net_recv, &s->socket, net_send, &s->socket);
4923
4924 /* set protocol version to TLS 1.2 */
4925 ssl_set_min_version(s->tls_ctx->ctx, ZBX_TLS_MIN_MAJOR_VER, ZBX_TLS_MIN_MINOR_VER);
4926 ssl_set_max_version(s->tls_ctx->ctx, ZBX_TLS_MAX_MAJOR_VER, ZBX_TLS_MAX_MINOR_VER);
4927
4928 /* prepare to accept with certificate */
4929
4930 if (0 != (tls_accept & ZBX_TCP_SEC_TLS_CERT))
4931 {
4932 ssl_set_authmode(s->tls_ctx->ctx, SSL_VERIFY_REQUIRED);
4933
4934 /* set CA certificate and certificate revocation lists */
4935 if (NULL != ca_cert)
4936 ssl_set_ca_chain(s->tls_ctx->ctx, ca_cert, crl, NULL);
4937
4938 if (NULL != my_cert && 0 != (res = ssl_set_own_cert(s->tls_ctx->ctx, my_cert, my_priv_key)))
4939 {
4940 zbx_tls_error_msg(res, "ssl_set_own_cert(): ", error);
4941 goto out;
4942 }
4943 }
4944
4945 /* prepare to accept with pre-shared key */
4946
4947 if (0 != (tls_accept & ZBX_TCP_SEC_TLS_PSK))
4948 {
4949 /* for agentd the only possibility is a PSK from configuration file */
4950 if (0 != (program_type & ZBX_PROGRAM_TYPE_AGENTD) &&
4951 0 != (res = ssl_set_psk(s->tls_ctx->ctx, (const unsigned char *)my_psk, my_psk_len,
4952 (const unsigned char *)my_psk_identity, my_psk_identity_len)))
4953 {
4954 zbx_tls_error_msg(res, "ssl_set_psk(): ", error);
4955 goto out;
4956 }
4957 else if (0 != (program_type & (ZBX_PROGRAM_TYPE_PROXY | ZBX_PROGRAM_TYPE_SERVER)))
4958 {
4959 /* For server or proxy a PSK can come from configuration file or database. */
4960 /* Set up a callback function for finding the requested PSK. */
4961 ssl_set_psk_cb(s->tls_ctx->ctx, zbx_psk_cb, NULL);
4962 }
4963 }
4964
4965 /* set up ciphersuites */
4966
4967 if ((ZBX_TCP_SEC_TLS_CERT | ZBX_TCP_SEC_TLS_PSK) == (tls_accept & (ZBX_TCP_SEC_TLS_CERT | ZBX_TCP_SEC_TLS_PSK)))
4968 {
4969 /* common case in trapper - be ready for all types of incoming connections */
4970 if (NULL != my_cert)
4971 {
4972 /* it can also be a case in agentd listener - when both certificate and PSK is allowed, e.g. */
4973 /* for switching of TLS connections from PSK to using a certificate */
4974 ssl_set_ciphersuites(s->tls_ctx->ctx, ciphersuites_all);
4975 }
4976 else
4977 {
4978 /* assume PSK, although it is not yet known will there be the right PSK available */
4979 ssl_set_ciphersuites(s->tls_ctx->ctx, ciphersuites_psk);
4980 }
4981 }
4982 else if (0 != (tls_accept & ZBX_TCP_SEC_TLS_CERT) && NULL != my_cert)
4983 ssl_set_ciphersuites(s->tls_ctx->ctx, ciphersuites_cert);
4984 else if (0 != (tls_accept & ZBX_TCP_SEC_TLS_PSK))
4985 ssl_set_ciphersuites(s->tls_ctx->ctx, ciphersuites_psk);
4986
4987 /* TLS handshake */
4988
4989 #if defined(_WINDOWS)
4990 zbx_alarm_flag_clear();
4991 sec = zbx_time();
4992 #endif
4993 while (0 != (res = ssl_handshake(s->tls_ctx->ctx)))
4994 {
4995 #if defined(_WINDOWS)
4996 if (s->timeout < zbx_time() - sec)
4997 zbx_alarm_flag_set();
4998 #endif
4999 if (SUCCEED == zbx_alarm_timed_out())
5000 {
5001 *error = zbx_strdup(*error, "ssl_handshake() timed out");
5002 goto out;
5003 }
5004
5005 if (POLARSSL_ERR_NET_WANT_READ != res && POLARSSL_ERR_NET_WANT_WRITE != res)
5006 {
5007 if (POLARSSL_ERR_X509_CERT_VERIFY_FAILED == res)
5008 {
5009 /* Standard PolarSSL error message might not be very informative in this case. For */
5010 /* example, if certificate validity starts in future, PolarSSL 1.3.9 would produce a */
5011 /* message "X509 - Certificate verification failed, e.g. CRL, CA or signature check */
5012 /* failed" which does not give a precise reason. Here we try to get more detailed */
5013 /* reason why peer certificate was rejected by using some knowledge about PolarSSL */
5014 /* internals. */
5015 zbx_tls_cert_error_msg((unsigned int)s->tls_ctx->ctx->session_negotiate->verify_result,
5016 error);
5017 zbx_tls_close(s);
5018 goto out1;
5019 }
5020
5021 zbx_tls_error_msg(res, "ssl_handshake(): ", error);
5022 goto out;
5023 }
5024 }
5025
5026 /* Is this TLS conection using certificate or PSK? */
5027
5028 info = ssl_ciphersuite_from_id(s->tls_ctx->ctx->session->ciphersuite);
5029
5030 if (POLARSSL_KEY_EXCHANGE_PSK == info->key_exchange ||
5031 POLARSSL_KEY_EXCHANGE_DHE_PSK == info->key_exchange ||
5032 POLARSSL_KEY_EXCHANGE_ECDHE_PSK == info->key_exchange ||
5033 POLARSSL_KEY_EXCHANGE_RSA_PSK == info->key_exchange)
5034 {
5035 s->connection_type = ZBX_TCP_SEC_TLS_PSK;
5036
5037 /* special print: s->tls_ctx->ctx->psk_identity is not '\0'-terminated */
5038 zabbix_log(LOG_LEVEL_DEBUG, "%s() PSK identity: \"%.*s\"", __function_name,
5039 (int)s->tls_ctx->ctx->psk_identity_len, s->tls_ctx->ctx->psk_identity);
5040 }
5041 else
5042 {
5043 s->connection_type = ZBX_TCP_SEC_TLS_CERT;
5044
5045 /* log peer certificate information for debugging */
5046 zbx_log_peer_cert(__function_name, s->tls_ctx);
5047
5048 /* basic verification of peer certificate was done during handshake */
5049
5050 /* Issuer and Subject will be verified later, after receiving sender type and host name */
5051 }
5052
5053 zabbix_log(LOG_LEVEL_DEBUG, "End of %s():SUCCEED (established %s %s)", __function_name,
5054 ssl_get_version(s->tls_ctx->ctx), ssl_get_ciphersuite(s->tls_ctx->ctx));
5055
5056 return SUCCEED;
5057
5058 out: /* an error occurred */
5059 ssl_free(s->tls_ctx->ctx);
5060 zbx_free(s->tls_ctx->ctx);
5061 zbx_free(s->tls_ctx);
5062 out1:
5063 zabbix_log(LOG_LEVEL_DEBUG, "End of %s():%s error:'%s'", __function_name, zbx_result_string(ret),
5064 ZBX_NULL2EMPTY_STR(*error));
5065 return ret;
5066 }
5067 #elif defined(HAVE_GNUTLS)
zbx_tls_accept(zbx_socket_t * s,unsigned int tls_accept,char ** error)5068 int zbx_tls_accept(zbx_socket_t *s, unsigned int tls_accept, char **error)
5069 {
5070 const char *__function_name = "zbx_tls_accept";
5071 int ret = FAIL, res;
5072 gnutls_credentials_type_t creds;
5073 #if defined(_WINDOWS)
5074 double sec;
5075 #endif
5076 zabbix_log(LOG_LEVEL_DEBUG, "In %s()", __function_name);
5077
5078 /* set up TLS context */
5079
5080 s->tls_ctx = zbx_malloc(s->tls_ctx, sizeof(zbx_tls_context_t));
5081 s->tls_ctx->ctx = NULL;
5082 s->tls_ctx->psk_client_creds = NULL;
5083 s->tls_ctx->psk_server_creds = NULL;
5084
5085 if (GNUTLS_E_SUCCESS != (res = gnutls_init(&s->tls_ctx->ctx, GNUTLS_SERVER)))
5086 {
5087 *error = zbx_dsprintf(*error, "gnutls_init() failed: %d %s", res, gnutls_strerror(res));
5088 goto out;
5089 }
5090
5091 /* prepare to accept with certificate */
5092
5093 if (0 != (tls_accept & ZBX_TCP_SEC_TLS_CERT))
5094 {
5095 if (NULL != my_cert_creds && GNUTLS_E_SUCCESS != (res = gnutls_credentials_set(s->tls_ctx->ctx,
5096 GNUTLS_CRD_CERTIFICATE, my_cert_creds)))
5097 {
5098 *error = zbx_dsprintf(*error, "gnutls_credentials_set() for certificate failed: %d %s", res,
5099 gnutls_strerror(res));
5100 goto out;
5101 }
5102
5103 /* client certificate is mandatory unless pre-shared key is used */
5104 gnutls_certificate_server_set_request(s->tls_ctx->ctx, GNUTLS_CERT_REQUIRE);
5105 }
5106
5107 /* prepare to accept with pre-shared key */
5108
5109 if (0 != (tls_accept & ZBX_TCP_SEC_TLS_PSK))
5110 {
5111 /* for agentd the only possibility is a PSK from configuration file */
5112 if (0 != (program_type & ZBX_PROGRAM_TYPE_AGENTD) &&
5113 GNUTLS_E_SUCCESS != (res = gnutls_credentials_set(s->tls_ctx->ctx, GNUTLS_CRD_PSK,
5114 my_psk_server_creds)))
5115 {
5116 *error = zbx_dsprintf(*error, "gnutls_credentials_set() for my_psk_server_creds failed: %d %s",
5117 res, gnutls_strerror(res));
5118 goto out;
5119 }
5120 else if (0 != (program_type & (ZBX_PROGRAM_TYPE_PROXY | ZBX_PROGRAM_TYPE_SERVER)))
5121 {
5122 /* For server or proxy a PSK can come from configuration file or database. */
5123 /* Set up a callback function for finding the requested PSK. */
5124 if (GNUTLS_E_SUCCESS != (res = gnutls_psk_allocate_server_credentials(
5125 &s->tls_ctx->psk_server_creds)))
5126 {
5127 *error = zbx_dsprintf(*error, "gnutls_psk_allocate_server_credentials() for"
5128 " psk_server_creds failed: %d %s", res, gnutls_strerror(res));
5129 goto out;
5130 }
5131
5132 gnutls_psk_set_server_credentials_function(s->tls_ctx->psk_server_creds, zbx_psk_cb);
5133
5134 if (GNUTLS_E_SUCCESS != (res = gnutls_credentials_set(s->tls_ctx->ctx, GNUTLS_CRD_PSK,
5135 s->tls_ctx->psk_server_creds)))
5136 {
5137 *error = zbx_dsprintf(*error, "gnutls_credentials_set() for psk_server_creds failed"
5138 ": %d %s", res, gnutls_strerror(res));
5139 goto out;
5140 }
5141 }
5142 }
5143
5144 /* set up ciphersuites */
5145
5146 if ((ZBX_TCP_SEC_TLS_CERT | ZBX_TCP_SEC_TLS_PSK) == (tls_accept & (ZBX_TCP_SEC_TLS_CERT | ZBX_TCP_SEC_TLS_PSK)))
5147 {
5148 /* common case in trapper - be ready for all types of incoming connections */
5149 if (NULL != my_cert_creds)
5150 {
5151 /* it can also be a case in agentd listener - when both certificate and PSK is allowed, e.g. */
5152 /* for switching of TLS connections from PSK to using a certificate */
5153 if (GNUTLS_E_SUCCESS != (res = gnutls_priority_set(s->tls_ctx->ctx, ciphersuites_all)))
5154 {
5155 *error = zbx_dsprintf(*error, "gnutls_priority_set() for 'ciphersuites_all' failed: %d"
5156 " %s", res, gnutls_strerror(res));
5157 goto out;
5158 }
5159 }
5160 else
5161 {
5162 /* assume PSK, although it is not yet known will there be the right PSK available */
5163 if (GNUTLS_E_SUCCESS != (res = gnutls_priority_set(s->tls_ctx->ctx, ciphersuites_psk)))
5164 {
5165 *error = zbx_dsprintf(*error, "gnutls_priority_set() for 'ciphersuites_psk' failed: %d"
5166 " %s", res, gnutls_strerror(res));
5167 goto out;
5168 }
5169 }
5170 }
5171 else if (0 != (tls_accept & ZBX_TCP_SEC_TLS_CERT) && NULL != my_cert_creds)
5172 {
5173 if (GNUTLS_E_SUCCESS != (res = gnutls_priority_set(s->tls_ctx->ctx, ciphersuites_cert)))
5174 {
5175 *error = zbx_dsprintf(*error, "gnutls_priority_set() for 'ciphersuites_cert' failed: %d %s",
5176 res, gnutls_strerror(res));
5177 goto out;
5178 }
5179 }
5180 else if (0 != (tls_accept & ZBX_TCP_SEC_TLS_PSK))
5181 {
5182 if (GNUTLS_E_SUCCESS != (res = gnutls_priority_set(s->tls_ctx->ctx, ciphersuites_psk)))
5183 {
5184 *error = zbx_dsprintf(*error, "gnutls_priority_set() for 'ciphersuites_psk' failed: %d %s", res,
5185 gnutls_strerror(res));
5186 goto out;
5187 }
5188 }
5189
5190 if (SUCCEED == ZBX_CHECK_LOG_LEVEL(LOG_LEVEL_TRACE))
5191 {
5192 /* set our own debug callback function */
5193 gnutls_global_set_log_function(zbx_gnutls_debug_cb);
5194
5195 /* for Zabbix LOG_LEVEL_TRACE, GnuTLS debug level 4 seems the best */
5196 /* (the highest GnuTLS debug level is 9) */
5197 gnutls_global_set_log_level(4);
5198 }
5199 else
5200 gnutls_global_set_log_level(0); /* restore default log level */
5201
5202 /* set our own callback function to log issues into Zabbix log */
5203 gnutls_global_set_audit_log_function(zbx_gnutls_audit_cb);
5204
5205 gnutls_transport_set_int(s->tls_ctx->ctx, ZBX_SOCKET_TO_INT(s->socket));
5206
5207 /* TLS handshake */
5208
5209 #if defined(_WINDOWS)
5210 zbx_alarm_flag_clear();
5211 sec = zbx_time();
5212 #endif
5213 while (GNUTLS_E_SUCCESS != (res = gnutls_handshake(s->tls_ctx->ctx)))
5214 {
5215 #if defined(_WINDOWS)
5216 if (s->timeout < zbx_time() - sec)
5217 zbx_alarm_flag_set();
5218 #endif
5219 if (SUCCEED == zbx_alarm_timed_out())
5220 {
5221 *error = zbx_strdup(*error, "gnutls_handshake() timed out");
5222 goto out;
5223 }
5224
5225 if (GNUTLS_E_INTERRUPTED == res || GNUTLS_E_AGAIN == res)
5226 {
5227 continue;
5228 }
5229 else if (GNUTLS_E_WARNING_ALERT_RECEIVED == res || GNUTLS_E_FATAL_ALERT_RECEIVED == res ||
5230 GNUTLS_E_GOT_APPLICATION_DATA == res)
5231 {
5232 const char *msg;
5233 int alert;
5234
5235 /* client sent an alert to us */
5236 alert = gnutls_alert_get(s->tls_ctx->ctx);
5237
5238 if (NULL == (msg = gnutls_alert_get_name(alert)))
5239 msg = "unknown";
5240
5241 if (GNUTLS_E_WARNING_ALERT_RECEIVED == res)
5242 {
5243 zabbix_log(LOG_LEVEL_WARNING, "%s() gnutls_handshake() received a warning alert: %d"
5244 " %s", __function_name, alert, msg);
5245 continue;
5246 }
5247 else if (GNUTLS_E_GOT_APPLICATION_DATA == res)
5248 /* if rehandshake request deal with it as with error */
5249 {
5250 *error = zbx_dsprintf(*error, "%s(): gnutls_handshake() returned"
5251 " GNUTLS_E_GOT_APPLICATION_DATA", __function_name);
5252 goto out;
5253 }
5254 else /* GNUTLS_E_FATAL_ALERT_RECEIVED */
5255 {
5256 *error = zbx_dsprintf(*error, "%s(): gnutls_handshake() failed with fatal alert: %d %s",
5257 __function_name, alert, msg);
5258 goto out;
5259 }
5260 }
5261 else
5262 {
5263 zabbix_log(LOG_LEVEL_WARNING, "%s() gnutls_handshake() returned: %d %s",
5264 __function_name, res, gnutls_strerror(res));
5265
5266 if (0 != gnutls_error_is_fatal(res))
5267 {
5268 *error = zbx_dsprintf(*error, "%s(): gnutls_handshake() failed: %d %s",
5269 __function_name, res, gnutls_strerror(res));
5270 goto out;
5271 }
5272 }
5273 }
5274
5275 /* Is this TLS conection using certificate or PSK? */
5276
5277 if (GNUTLS_CRD_CERTIFICATE == (creds = gnutls_auth_get_type(s->tls_ctx->ctx)))
5278 {
5279 s->connection_type = ZBX_TCP_SEC_TLS_CERT;
5280
5281 /* log peer certificate information for debugging */
5282 zbx_log_peer_cert(__function_name, s->tls_ctx);
5283
5284 /* perform basic verification of peer certificate */
5285 if (SUCCEED != zbx_verify_peer_cert(s->tls_ctx->ctx, error))
5286 {
5287 zbx_tls_close(s);
5288 goto out1;
5289 }
5290
5291 /* Issuer and Subject will be verified later, after receiving sender type and host name */
5292 }
5293 else if (GNUTLS_CRD_PSK == creds)
5294 {
5295 s->connection_type = ZBX_TCP_SEC_TLS_PSK;
5296
5297 if (SUCCEED == ZBX_CHECK_LOG_LEVEL(LOG_LEVEL_DEBUG))
5298 {
5299 const char *psk_identity;
5300
5301 if (NULL != (psk_identity = gnutls_psk_server_get_username(s->tls_ctx->ctx)))
5302 {
5303 zabbix_log(LOG_LEVEL_DEBUG, "%s() PSK identity: \"%s\"", __function_name,
5304 psk_identity);
5305 }
5306 }
5307 }
5308 else
5309 {
5310 THIS_SHOULD_NEVER_HAPPEN;
5311 zbx_tls_close(s);
5312 return FAIL;
5313 }
5314
5315 zabbix_log(LOG_LEVEL_DEBUG, "End of %s():SUCCEED (established %s %s-%s-%s-" ZBX_FS_SIZE_T ")", __function_name,
5316 gnutls_protocol_get_name(gnutls_protocol_get_version(s->tls_ctx->ctx)),
5317 gnutls_kx_get_name(gnutls_kx_get(s->tls_ctx->ctx)),
5318 gnutls_cipher_get_name(gnutls_cipher_get(s->tls_ctx->ctx)),
5319 gnutls_mac_get_name(gnutls_mac_get(s->tls_ctx->ctx)),
5320 (zbx_fs_size_t)gnutls_mac_get_key_size(gnutls_mac_get(s->tls_ctx->ctx)));
5321
5322 return SUCCEED;
5323
5324 out: /* an error occurred */
5325 if (NULL != s->tls_ctx->ctx)
5326 {
5327 gnutls_credentials_clear(s->tls_ctx->ctx);
5328 gnutls_deinit(s->tls_ctx->ctx);
5329 }
5330
5331 if (NULL != s->tls_ctx->psk_server_creds)
5332 gnutls_psk_free_server_credentials(s->tls_ctx->psk_server_creds);
5333
5334 zbx_free(s->tls_ctx);
5335 out1:
5336 zabbix_log(LOG_LEVEL_DEBUG, "End of %s():%s error:'%s'", __function_name, zbx_result_string(ret),
5337 ZBX_NULL2EMPTY_STR(*error));
5338 return ret;
5339 }
5340 #elif defined(HAVE_OPENSSL)
zbx_tls_accept(zbx_socket_t * s,unsigned int tls_accept,char ** error)5341 int zbx_tls_accept(zbx_socket_t *s, unsigned int tls_accept, char **error)
5342 {
5343 const char *__function_name = "zbx_tls_accept";
5344 const char *cipher_name;
5345 int ret = FAIL, res;
5346 size_t error_alloc = 0, error_offset = 0;
5347 long verify_result;
5348 #if defined(_WINDOWS)
5349 double sec;
5350 #endif
5351 #if OPENSSL_VERSION_NUMBER >= 0x1010100fL /* OpenSSL 1.1.1 or newer, or LibreSSL */
5352 const unsigned char session_id_context[] = {'Z', 'b', 'x'};
5353 #endif
5354 zabbix_log(LOG_LEVEL_DEBUG, "In %s()", __function_name);
5355
5356 s->tls_ctx = zbx_malloc(s->tls_ctx, sizeof(zbx_tls_context_t));
5357 s->tls_ctx->ctx = NULL;
5358
5359 #if defined(HAVE_OPENSSL_WITH_PSK)
5360 incoming_connection_has_psk = 0; /* assume certificate-based connection by default */
5361 #endif
5362 if ((ZBX_TCP_SEC_TLS_CERT | ZBX_TCP_SEC_TLS_PSK) == (tls_accept & (ZBX_TCP_SEC_TLS_CERT | ZBX_TCP_SEC_TLS_PSK)))
5363 {
5364 #if defined(HAVE_OPENSSL_WITH_PSK)
5365 /* common case in trapper - be ready for all types of incoming connections but possible also in */
5366 /* agentd listener */
5367
5368 if (NULL != ctx_all)
5369 {
5370 if (NULL == (s->tls_ctx->ctx = SSL_new(ctx_all)))
5371 {
5372 zbx_snprintf_alloc(error, &error_alloc, &error_offset, "cannot create context to accept"
5373 " connection:");
5374 zbx_tls_error_msg(error, &error_alloc, &error_offset);
5375 goto out;
5376 }
5377 }
5378 #else
5379 if (0 != (program_type & (ZBX_PROGRAM_TYPE_PROXY | ZBX_PROGRAM_TYPE_SERVER)))
5380 {
5381 /* server or proxy running with OpenSSL or LibreSSL without PSK support */
5382 if (NULL != ctx_cert)
5383 {
5384 if (NULL == (s->tls_ctx->ctx = SSL_new(ctx_cert)))
5385 {
5386 zbx_snprintf_alloc(error, &error_alloc, &error_offset, "cannot create context"
5387 " to accept connection:");
5388 zbx_tls_error_msg(error, &error_alloc, &error_offset);
5389 goto out;
5390 }
5391 }
5392 else
5393 {
5394 *error = zbx_strdup(*error, "not ready for certificate-based incoming connection:"
5395 " certificate not loaded. PSK support not compiled in.");
5396 goto out;
5397 }
5398 }
5399 #endif
5400 else if (0 != (program_type & ZBX_PROGRAM_TYPE_AGENTD))
5401 {
5402 THIS_SHOULD_NEVER_HAPPEN;
5403 goto out;
5404 }
5405 #if defined(HAVE_OPENSSL_WITH_PSK)
5406 else if (NULL != ctx_psk)
5407 {
5408 /* Server or proxy with no certificate configured. PSK is always assumed to be configured on */
5409 /* server or proxy because PSK can come from database. */
5410
5411 if (NULL == (s->tls_ctx->ctx = SSL_new(ctx_psk)))
5412 {
5413 zbx_snprintf_alloc(error, &error_alloc, &error_offset, "cannot create context to accept"
5414 " connection:");
5415 zbx_tls_error_msg(error, &error_alloc, &error_offset);
5416 goto out;
5417 }
5418 }
5419 else
5420 {
5421 THIS_SHOULD_NEVER_HAPPEN;
5422 goto out;
5423 }
5424 #endif
5425 }
5426 else if (0 != (tls_accept & ZBX_TCP_SEC_TLS_CERT))
5427 {
5428 if (NULL != ctx_cert)
5429 {
5430 if (NULL == (s->tls_ctx->ctx = SSL_new(ctx_cert)))
5431 {
5432 zbx_snprintf_alloc(error, &error_alloc, &error_offset, "cannot create context to accept"
5433 " connection:");
5434 zbx_tls_error_msg(error, &error_alloc, &error_offset);
5435 goto out;
5436 }
5437 }
5438 else
5439 {
5440 *error = zbx_strdup(*error, "not ready for certificate-based incoming connection: certificate"
5441 " not loaded");
5442 goto out;
5443 }
5444 }
5445 else /* PSK */
5446 {
5447 #if defined(HAVE_OPENSSL_WITH_PSK)
5448 if (NULL != ctx_psk)
5449 {
5450 if (NULL == (s->tls_ctx->ctx = SSL_new(ctx_psk)))
5451 {
5452 zbx_snprintf_alloc(error, &error_alloc, &error_offset, "cannot create context to accept"
5453 " connection:");
5454 zbx_tls_error_msg(error, &error_alloc, &error_offset);
5455 goto out;
5456 }
5457 }
5458 else
5459 {
5460 *error = zbx_strdup(*error, "not ready for PSK-based incoming connection: PSK not loaded");
5461 goto out;
5462 }
5463 #else
5464 *error = zbx_strdup(*error, "support for PSK was not compiled in");
5465 goto out;
5466 #endif
5467 }
5468
5469 #if OPENSSL_VERSION_NUMBER >= 0x1010100fL /* OpenSSL 1.1.1 or newer, or LibreSSL */
5470 if (1 != SSL_set_session_id_context(s->tls_ctx->ctx, session_id_context, sizeof(session_id_context)))
5471 {
5472 *error = zbx_strdup(*error, "cannot set session_id_context");
5473 goto out;
5474 }
5475 #endif
5476 if (1 != SSL_set_fd(s->tls_ctx->ctx, s->socket))
5477 {
5478 *error = zbx_strdup(*error, "cannot set socket for TLS context");
5479 goto out;
5480 }
5481
5482 /* TLS handshake */
5483
5484 info_buf[0] = '\0'; /* empty buffer for zbx_openssl_info_cb() messages */
5485 #if defined(_WINDOWS)
5486 zbx_alarm_flag_clear();
5487 sec = zbx_time();
5488 #endif
5489 if (1 != (res = SSL_accept(s->tls_ctx->ctx)))
5490 {
5491 int result_code;
5492
5493 #if defined(_WINDOWS)
5494 if (s->timeout < zbx_time() - sec)
5495 zbx_alarm_flag_set();
5496 #endif
5497 if (SUCCEED == zbx_alarm_timed_out())
5498 {
5499 *error = zbx_strdup(*error, "SSL_accept() timed out");
5500 goto out;
5501 }
5502
5503 /* In case of certificate error SSL_get_verify_result() provides more helpful diagnostics */
5504 /* than other methods. Include it as first but continue with other diagnostics. Should be */
5505 /* harmless in case of PSK. */
5506
5507 if (X509_V_OK != (verify_result = SSL_get_verify_result(s->tls_ctx->ctx)))
5508 {
5509 zbx_snprintf_alloc(error, &error_alloc, &error_offset, "%s: ",
5510 X509_verify_cert_error_string(verify_result));
5511 }
5512
5513 result_code = SSL_get_error(s->tls_ctx->ctx, res);
5514
5515 if (0 == res)
5516 {
5517 zbx_snprintf_alloc(error, &error_alloc, &error_offset, "TLS connection has been closed during"
5518 " handshake:");
5519 }
5520 else
5521 {
5522 zbx_snprintf_alloc(error, &error_alloc, &error_offset, "TLS handshake set result code to %d:",
5523 result_code);
5524 }
5525
5526 zbx_tls_error_msg(error, &error_alloc, &error_offset);
5527 zbx_snprintf_alloc(error, &error_alloc, &error_offset, "%s", info_buf);
5528 goto out;
5529 }
5530
5531 /* Is this TLS conection using certificate or PSK? */
5532
5533 cipher_name = SSL_get_cipher(s->tls_ctx->ctx);
5534
5535 #if defined(HAVE_OPENSSL_WITH_PSK)
5536 if (1 == incoming_connection_has_psk)
5537 {
5538 s->connection_type = ZBX_TCP_SEC_TLS_PSK;
5539 }
5540 else if (0 != strncmp("(NONE)", cipher_name, ZBX_CONST_STRLEN("(NONE)")))
5541 #endif
5542 {
5543 s->connection_type = ZBX_TCP_SEC_TLS_CERT;
5544
5545 /* log peer certificate information for debugging */
5546 zbx_log_peer_cert(__function_name, s->tls_ctx);
5547
5548 /* perform basic verification of peer certificate */
5549 if (X509_V_OK != (verify_result = SSL_get_verify_result(s->tls_ctx->ctx)))
5550 {
5551 zbx_snprintf_alloc(error, &error_alloc, &error_offset, "%s",
5552 X509_verify_cert_error_string(verify_result));
5553 zbx_tls_close(s);
5554 goto out1;
5555 }
5556
5557 /* Issuer and Subject will be verified later, after receiving sender type and host name */
5558 }
5559 #if defined(HAVE_OPENSSL_WITH_PSK)
5560 else
5561 {
5562 THIS_SHOULD_NEVER_HAPPEN;
5563 zbx_tls_close(s);
5564 return FAIL;
5565 }
5566 #endif
5567 zabbix_log(LOG_LEVEL_DEBUG, "End of %s():SUCCEED (established %s %s)", __function_name,
5568 SSL_get_version(s->tls_ctx->ctx), cipher_name);
5569
5570 return SUCCEED;
5571
5572 out: /* an error occurred */
5573 if (NULL != s->tls_ctx->ctx)
5574 SSL_free(s->tls_ctx->ctx);
5575
5576 zbx_free(s->tls_ctx);
5577 out1:
5578 zabbix_log(LOG_LEVEL_DEBUG, "End of %s():%s error:'%s'", __function_name, zbx_result_string(ret),
5579 ZBX_NULL2EMPTY_STR(*error));
5580 return ret;
5581 }
5582 #endif
5583
5584 #if defined(HAVE_POLARSSL)
5585 # define ZBX_TLS_WRITE(ctx, buf, len) ssl_write(ctx, (const unsigned char *)(buf), len)
5586 # define ZBX_TLS_READ(ctx, buf, len) ssl_read(ctx, (unsigned char *)(buf), len)
5587 # define ZBX_TLS_WRITE_FUNC_NAME "ssl_write"
5588 # define ZBX_TLS_READ_FUNC_NAME "ssl_read"
5589 # define ZBX_TLS_WANT_WRITE(res) (POLARSSL_ERR_NET_WANT_WRITE == (res) ? SUCCEED : FAIL)
5590 # define ZBX_TLS_WANT_READ(res) (POLARSSL_ERR_NET_WANT_READ == (res) ? SUCCEED : FAIL)
5591 #elif defined(HAVE_GNUTLS)
5592 # define ZBX_TLS_WRITE(ctx, buf, len) gnutls_record_send(ctx, buf, len)
5593 # define ZBX_TLS_READ(ctx, buf, len) gnutls_record_recv(ctx, buf, len)
5594 # define ZBX_TLS_WRITE_FUNC_NAME "gnutls_record_send"
5595 # define ZBX_TLS_READ_FUNC_NAME "gnutls_record_recv"
5596 # define ZBX_TLS_WANT_WRITE(res) (GNUTLS_E_INTERRUPTED == (res) || GNUTLS_E_AGAIN == (res) ? SUCCEED : FAIL)
5597 # define ZBX_TLS_WANT_READ(res) (GNUTLS_E_INTERRUPTED == (res) || GNUTLS_E_AGAIN == (res) ? SUCCEED : FAIL)
5598 #elif defined(HAVE_OPENSSL)
5599 # define ZBX_TLS_WRITE(ctx, buf, len) SSL_write(ctx, buf, (int)(len))
5600 # define ZBX_TLS_READ(ctx, buf, len) SSL_read(ctx, buf, (int)(len))
5601 # define ZBX_TLS_WRITE_FUNC_NAME "SSL_write"
5602 # define ZBX_TLS_READ_FUNC_NAME "SSL_read"
5603 # define ZBX_TLS_WANT_WRITE(res) FAIL
5604 # define ZBX_TLS_WANT_READ(res) FAIL
5605 /* SSL_ERROR_WANT_READ or SSL_ERROR_WANT_WRITE should not be returned here because we set */
5606 /* SSL_MODE_AUTO_RETRY flag in zbx_tls_init_child() */
5607 #endif
5608
zbx_tls_write(zbx_socket_t * s,const char * buf,size_t len,char ** error)5609 ssize_t zbx_tls_write(zbx_socket_t *s, const char *buf, size_t len, char **error)
5610 {
5611 #if defined(_WINDOWS)
5612 double sec;
5613 #endif
5614 #if defined(HAVE_POLARSSL)
5615 int res;
5616 #elif defined(HAVE_GNUTLS)
5617 ssize_t res;
5618 #elif defined(HAVE_OPENSSL)
5619 int res;
5620 #endif
5621
5622 #if defined(_WINDOWS)
5623 zbx_alarm_flag_clear();
5624 sec = zbx_time();
5625 #endif
5626 #if defined(HAVE_OPENSSL)
5627 info_buf[0] = '\0'; /* empty buffer for zbx_openssl_info_cb() messages */
5628 #endif
5629 do
5630 {
5631 res = ZBX_TLS_WRITE(s->tls_ctx->ctx, buf, len);
5632 #if defined(_WINDOWS)
5633 if (s->timeout < zbx_time() - sec)
5634 zbx_alarm_flag_set();
5635 #endif
5636 if (SUCCEED == zbx_alarm_timed_out())
5637 {
5638 *error = zbx_strdup(*error, ZBX_TLS_WRITE_FUNC_NAME "() timed out");
5639 return ZBX_PROTO_ERROR;
5640 }
5641 }
5642 while (SUCCEED == ZBX_TLS_WANT_WRITE(res));
5643
5644 #if defined(HAVE_POLARSSL)
5645 if (0 > res)
5646 {
5647 char err[128]; /* 128 bytes are enough for PolarSSL error messages */
5648
5649 polarssl_strerror(res, err, sizeof(err));
5650 *error = zbx_dsprintf(*error, "ssl_write() failed: %s", err);
5651
5652 return ZBX_PROTO_ERROR;
5653 }
5654 #elif defined(HAVE_GNUTLS)
5655 if (0 > res)
5656 {
5657 *error = zbx_dsprintf(*error, "gnutls_record_send() failed: " ZBX_FS_SSIZE_T " %s",
5658 (zbx_fs_ssize_t)res, gnutls_strerror(res));
5659
5660 return ZBX_PROTO_ERROR;
5661 }
5662 #elif defined(HAVE_OPENSSL)
5663 if (0 >= res)
5664 {
5665 int result_code;
5666
5667 result_code = SSL_get_error(s->tls_ctx->ctx, res);
5668
5669 if (0 == res && SSL_ERROR_ZERO_RETURN == result_code)
5670 {
5671 *error = zbx_strdup(*error, "connection closed during write");
5672 }
5673 else
5674 {
5675 char *err = NULL;
5676 size_t error_alloc = 0, error_offset = 0;
5677
5678 zbx_snprintf_alloc(&err, &error_alloc, &error_offset, "TLS write set result code to"
5679 " %d:", result_code);
5680 zbx_tls_error_msg(&err, &error_alloc, &error_offset);
5681 *error = zbx_dsprintf(*error, "%s%s", err, info_buf);
5682 zbx_free(err);
5683 }
5684
5685 return ZBX_PROTO_ERROR;
5686 }
5687 #endif
5688
5689 return (ssize_t)res;
5690 }
5691
zbx_tls_read(zbx_socket_t * s,char * buf,size_t len,char ** error)5692 ssize_t zbx_tls_read(zbx_socket_t *s, char *buf, size_t len, char **error)
5693 {
5694 #if defined(_WINDOWS)
5695 double sec;
5696 #endif
5697 #if defined(HAVE_POLARSSL)
5698 int res;
5699 #elif defined(HAVE_GNUTLS)
5700 ssize_t res;
5701 #elif defined(HAVE_OPENSSL)
5702 int res;
5703 #endif
5704
5705 #if defined(_WINDOWS)
5706 zbx_alarm_flag_clear();
5707 sec = zbx_time();
5708 #endif
5709 #if defined(HAVE_OPENSSL)
5710 info_buf[0] = '\0'; /* empty buffer for zbx_openssl_info_cb() messages */
5711 #endif
5712 do
5713 {
5714 res = ZBX_TLS_READ(s->tls_ctx->ctx, buf, len);
5715 #if defined(_WINDOWS)
5716 if (s->timeout < zbx_time() - sec)
5717 zbx_alarm_flag_set();
5718 #endif
5719 if (SUCCEED == zbx_alarm_timed_out())
5720 {
5721 *error = zbx_strdup(*error, ZBX_TLS_READ_FUNC_NAME "() timed out");
5722 return ZBX_PROTO_ERROR;
5723 }
5724 }
5725 while (SUCCEED == ZBX_TLS_WANT_READ(res));
5726
5727 #if defined(HAVE_POLARSSL)
5728 if (0 > res)
5729 {
5730 char err[128]; /* 128 bytes are enough for PolarSSL error messages */
5731
5732 polarssl_strerror(res, err, sizeof(err));
5733 *error = zbx_dsprintf(*error, "ssl_read() failed: %s", err);
5734
5735 return ZBX_PROTO_ERROR;
5736 }
5737 #elif defined(HAVE_GNUTLS)
5738 if (0 > res)
5739 {
5740 /* in case of rehandshake a GNUTLS_E_REHANDSHAKE will be returned, deal with it as with error */
5741 *error = zbx_dsprintf(*error, "gnutls_record_recv() failed: " ZBX_FS_SSIZE_T " %s",
5742 (zbx_fs_ssize_t)res, gnutls_strerror(res));
5743
5744 return ZBX_PROTO_ERROR;
5745 }
5746 #elif defined(HAVE_OPENSSL)
5747 if (0 >= res)
5748 {
5749 int result_code;
5750
5751 result_code = SSL_get_error(s->tls_ctx->ctx, res);
5752
5753 if (0 == res && SSL_ERROR_ZERO_RETURN == result_code)
5754 {
5755 *error = zbx_strdup(*error, "connection closed during read");
5756 }
5757 else
5758 {
5759 char *err = NULL;
5760 size_t error_alloc = 0, error_offset = 0;
5761
5762 zbx_snprintf_alloc(&err, &error_alloc, &error_offset, "TLS read set result code to"
5763 " %d:", result_code);
5764 zbx_tls_error_msg(&err, &error_alloc, &error_offset);
5765 *error = zbx_dsprintf(*error, "%s%s", err, info_buf);
5766 zbx_free(err);
5767 }
5768
5769 return ZBX_PROTO_ERROR;
5770 }
5771 #endif
5772
5773 return (ssize_t)res;
5774 }
5775
5776 /******************************************************************************
5777 * *
5778 * Function: zbx_tls_close *
5779 * *
5780 * Purpose: close a TLS connection before closing a TCP socket *
5781 * *
5782 ******************************************************************************/
zbx_tls_close(zbx_socket_t * s)5783 void zbx_tls_close(zbx_socket_t *s)
5784 {
5785 int res;
5786
5787 if (NULL == s->tls_ctx)
5788 return;
5789 #if defined(HAVE_POLARSSL)
5790 if (NULL != s->tls_ctx->ctx)
5791 {
5792 #if defined(_WINDOWS)
5793 double sec;
5794
5795 zbx_alarm_flag_clear();
5796 sec = zbx_time();
5797 #endif
5798 while (0 > (res = ssl_close_notify(s->tls_ctx->ctx)))
5799 {
5800 #if defined(_WINDOWS)
5801 if (s->timeout < zbx_time() - sec)
5802 zbx_alarm_flag_set();
5803 #endif
5804 if (SUCCEED == zbx_alarm_timed_out())
5805 break;
5806
5807 if (POLARSSL_ERR_NET_WANT_READ != res && POLARSSL_ERR_NET_WANT_WRITE != res)
5808 {
5809 zabbix_log(LOG_LEVEL_WARNING, "ssl_close_notify() with %s returned error code: %d",
5810 s->peer, res);
5811 break;
5812 }
5813 }
5814
5815 ssl_free(s->tls_ctx->ctx);
5816 zbx_free(s->tls_ctx->ctx);
5817 }
5818 #elif defined(HAVE_GNUTLS)
5819 if (NULL != s->tls_ctx->ctx)
5820 {
5821 #if defined(_WINDOWS)
5822 double sec;
5823
5824 zbx_alarm_flag_clear();
5825 sec = zbx_time();
5826 #endif
5827 /* shutdown TLS connection */
5828 while (GNUTLS_E_SUCCESS != (res = gnutls_bye(s->tls_ctx->ctx, GNUTLS_SHUT_WR)))
5829 {
5830 #if defined(_WINDOWS)
5831 if (s->timeout < zbx_time() - sec)
5832 zbx_alarm_flag_set();
5833 #endif
5834 if (SUCCEED == zbx_alarm_timed_out())
5835 break;
5836
5837 if (GNUTLS_E_INTERRUPTED == res || GNUTLS_E_AGAIN == res)
5838 continue;
5839
5840 zabbix_log(LOG_LEVEL_WARNING, "gnutls_bye() with %s returned error code: %d %s",
5841 s->peer, res, gnutls_strerror(res));
5842
5843 if (0 != gnutls_error_is_fatal(res))
5844 break;
5845 }
5846
5847 gnutls_credentials_clear(s->tls_ctx->ctx);
5848 gnutls_deinit(s->tls_ctx->ctx);
5849 }
5850
5851 if (NULL != s->tls_ctx->psk_client_creds)
5852 gnutls_psk_free_client_credentials(s->tls_ctx->psk_client_creds);
5853
5854 if (NULL != s->tls_ctx->psk_server_creds)
5855 gnutls_psk_free_server_credentials(s->tls_ctx->psk_server_creds);
5856 #elif defined(HAVE_OPENSSL)
5857 if (NULL != s->tls_ctx->ctx)
5858 {
5859 info_buf[0] = '\0'; /* empty buffer for zbx_openssl_info_cb() messages */
5860
5861 /* After TLS shutdown the TCP conection will be closed. So, there is no need to do a bidirectional */
5862 /* TLS shutdown - unidirectional shutdown is ok. */
5863 if (0 > (res = SSL_shutdown(s->tls_ctx->ctx)))
5864 {
5865 int result_code;
5866 char *error = NULL;
5867 size_t error_alloc = 0, error_offset = 0;
5868
5869 result_code = SSL_get_error(s->tls_ctx->ctx, res);
5870 zbx_tls_error_msg(&error, &error_alloc, &error_offset);
5871 zabbix_log(LOG_LEVEL_WARNING, "SSL_shutdown() with %s set result code to %d:%s%s",
5872 s->peer, result_code, ZBX_NULL2EMPTY_STR(error), info_buf);
5873 zbx_free(error);
5874 }
5875
5876 SSL_free(s->tls_ctx->ctx);
5877 }
5878 #endif
5879 zbx_free(s->tls_ctx);
5880 }
5881
5882 /******************************************************************************
5883 * *
5884 * Function: zbx_tls_get_attr_cert *
5885 * *
5886 * Purpose: get certificate attributes from the context of established *
5887 * connection *
5888 * *
5889 ******************************************************************************/
zbx_tls_get_attr_cert(const zbx_socket_t * s,zbx_tls_conn_attr_t * attr)5890 int zbx_tls_get_attr_cert(const zbx_socket_t *s, zbx_tls_conn_attr_t *attr)
5891 {
5892 char *error = NULL;
5893 #if defined(HAVE_POLARSSL)
5894 const x509_crt *peer_cert;
5895 #elif defined(HAVE_GNUTLS)
5896 gnutls_x509_crt_t peer_cert;
5897 gnutls_x509_dn_t dn;
5898 int res;
5899 #elif defined(HAVE_OPENSSL)
5900 X509 *peer_cert;
5901 #endif
5902
5903 #if defined(HAVE_POLARSSL)
5904 if (NULL == (peer_cert = ssl_get_peer_cert(s->tls_ctx->ctx)))
5905 {
5906 zabbix_log(LOG_LEVEL_WARNING, "no peer certificate, ssl_get_peer_cert() returned NULL");
5907 return FAIL;
5908 }
5909
5910 if (SUCCEED != zbx_x509_dn_gets(&peer_cert->issuer, attr->issuer, sizeof(attr->issuer), &error))
5911 {
5912 zabbix_log(LOG_LEVEL_WARNING, "error while getting issuer name: \"%s\"", error);
5913 zbx_free(error);
5914 return FAIL;
5915 }
5916
5917 if (SUCCEED != zbx_x509_dn_gets(&peer_cert->subject, attr->subject, sizeof(attr->subject), &error))
5918 {
5919 zabbix_log(LOG_LEVEL_WARNING, "error while getting subject name: \"%s\"", error);
5920 zbx_free(error);
5921 return FAIL;
5922 }
5923 #elif defined(HAVE_GNUTLS)
5924 /* here is some inefficiency - we do not know will it be required to verify peer certificate issuer */
5925 /* and subject - but we prepare for it */
5926 if (NULL == (peer_cert = zbx_get_peer_cert(s->tls_ctx->ctx, &error)))
5927 {
5928 zabbix_log(LOG_LEVEL_WARNING, "cannot get peer certificate: %s", error);
5929 zbx_free(error);
5930 return FAIL;
5931 }
5932
5933 if (0 != (res = gnutls_x509_crt_get_issuer(peer_cert, &dn)))
5934 {
5935 zabbix_log(LOG_LEVEL_WARNING, "gnutls_x509_crt_get_issuer() failed: %d %s", res,
5936 gnutls_strerror(res));
5937 gnutls_x509_crt_deinit(peer_cert);
5938 return FAIL;
5939 }
5940
5941 if (SUCCEED != zbx_x509_dn_gets(dn, attr->issuer, sizeof(attr->issuer), &error))
5942 {
5943 zabbix_log(LOG_LEVEL_WARNING, "zbx_x509_dn_gets() failed: %s", error);
5944 zbx_free(error);
5945 gnutls_x509_crt_deinit(peer_cert);
5946 return FAIL;
5947 }
5948
5949 if (0 != (res = gnutls_x509_crt_get_subject(peer_cert, &dn)))
5950 {
5951 zabbix_log(LOG_LEVEL_WARNING, "gnutls_x509_crt_get_subject() failed: %d %s", res,
5952 gnutls_strerror(res));
5953 gnutls_x509_crt_deinit(peer_cert);
5954 return FAIL;
5955 }
5956
5957 if (SUCCEED != zbx_x509_dn_gets(dn, attr->subject, sizeof(attr->subject), &error))
5958 {
5959 zabbix_log(LOG_LEVEL_WARNING, "zbx_x509_dn_gets() failed: %s", error);
5960 zbx_free(error);
5961 gnutls_x509_crt_deinit(peer_cert);
5962 return FAIL;
5963 }
5964
5965 gnutls_x509_crt_deinit(peer_cert);
5966 #elif defined(HAVE_OPENSSL)
5967 if (NULL == (peer_cert = SSL_get_peer_certificate(s->tls_ctx->ctx)))
5968 {
5969 zabbix_log(LOG_LEVEL_WARNING, "no peer certificate, SSL_get_peer_certificate() returned NULL");
5970 return FAIL;
5971 }
5972
5973 if (SUCCEED != zbx_x509_dn_gets(X509_get_issuer_name(peer_cert), attr->issuer, sizeof(attr->issuer), &error))
5974 {
5975 zabbix_log(LOG_LEVEL_WARNING, "error while getting issuer name: \"%s\"", error);
5976 zbx_free(error);
5977 X509_free(peer_cert);
5978 return FAIL;
5979 }
5980
5981 if (SUCCEED != zbx_x509_dn_gets(X509_get_subject_name(peer_cert), attr->subject, sizeof(attr->subject), &error))
5982 {
5983 zabbix_log(LOG_LEVEL_WARNING, "error while getting subject name: \"%s\"", error);
5984 zbx_free(error);
5985 X509_free(peer_cert);
5986 return FAIL;
5987 }
5988
5989 X509_free(peer_cert);
5990 #endif
5991
5992 return SUCCEED;
5993 }
5994
5995 /******************************************************************************
5996 * *
5997 * Function: zbx_tls_get_attr_psk *
5998 * *
5999 * Purpose: get PSK attributes from the context of established connection *
6000 * *
6001 * Comments: *
6002 * This function can be used only on server-side of TLS connection. *
6003 * GnuTLS makes it asymmetric - see documentation for *
6004 * gnutls_psk_server_get_username() and gnutls_psk_client_get_hint() *
6005 * (the latter function is not used in Zabbix). *
6006 * Implementation for OpenSSL is server-side only, too. *
6007 * *
6008 ******************************************************************************/
6009 #if defined(HAVE_POLARSSL)
zbx_tls_get_attr_psk(const zbx_socket_t * s,zbx_tls_conn_attr_t * attr)6010 int zbx_tls_get_attr_psk(const zbx_socket_t *s, zbx_tls_conn_attr_t *attr)
6011 {
6012 attr->psk_identity = (char *)s->tls_ctx->ctx->psk_identity;
6013 attr->psk_identity_len = s->tls_ctx->ctx->psk_identity_len;
6014 return SUCCEED;
6015 }
6016 #elif defined(HAVE_GNUTLS)
zbx_tls_get_attr_psk(const zbx_socket_t * s,zbx_tls_conn_attr_t * attr)6017 int zbx_tls_get_attr_psk(const zbx_socket_t *s, zbx_tls_conn_attr_t *attr)
6018 {
6019 if (NULL == (attr->psk_identity = gnutls_psk_server_get_username(s->tls_ctx->ctx)))
6020 return FAIL;
6021
6022 attr->psk_identity_len = strlen(attr->psk_identity);
6023 return SUCCEED;
6024 }
6025 #elif defined(HAVE_OPENSSL) && defined(HAVE_OPENSSL_WITH_PSK)
zbx_tls_get_attr_psk(const zbx_socket_t * s,zbx_tls_conn_attr_t * attr)6026 int zbx_tls_get_attr_psk(const zbx_socket_t *s, zbx_tls_conn_attr_t *attr)
6027 {
6028 ZBX_UNUSED(s);
6029
6030 /* SSL_get_psk_identity() is not used here. It works with TLS 1.2, */
6031 /* but returns NULL with TLS 1.3 in OpenSSL 1.1.1 */
6032 if ('\0' == incoming_connection_psk_id[0])
6033 return FAIL;
6034
6035 attr->psk_identity = incoming_connection_psk_id;
6036 attr->psk_identity_len = strlen(attr->psk_identity);
6037 return SUCCEED;
6038 }
6039 #endif
6040
6041 #if defined(_WINDOWS)
6042 /******************************************************************************
6043 * *
6044 * Function: zbx_tls_pass_vars *
6045 * *
6046 * Purpose: pass some TLS variables from one thread to other *
6047 * *
6048 * Comments: used in Zabbix sender on MS Windows *
6049 * *
6050 ******************************************************************************/
zbx_tls_pass_vars(ZBX_THREAD_SENDVAL_TLS_ARGS * args)6051 void zbx_tls_pass_vars(ZBX_THREAD_SENDVAL_TLS_ARGS *args)
6052 {
6053 #if defined(HAVE_POLARSSL)
6054 args->my_psk = my_psk;
6055 args->my_psk_len = my_psk_len;
6056 args->my_psk_identity = my_psk_identity;
6057 args->my_psk_identity_len = my_psk_identity_len;
6058 args->ca_cert = ca_cert;
6059 args->crl = crl;
6060 args->my_cert = my_cert;
6061 args->my_priv_key = my_priv_key;
6062 args->entropy = entropy;
6063 args->ctr_drbg = ctr_drbg;
6064 args->ciphersuites_cert = ciphersuites_cert;
6065 args->ciphersuites_psk = ciphersuites_psk;
6066 #elif defined(HAVE_GNUTLS)
6067 args->my_cert_creds = my_cert_creds;
6068 args->my_psk_client_creds = my_psk_client_creds;
6069 args->ciphersuites_cert = ciphersuites_cert;
6070 args->ciphersuites_psk = ciphersuites_psk;
6071 #elif defined(HAVE_OPENSSL)
6072 args->ctx_cert = ctx_cert;
6073 #if defined(HAVE_OPENSSL_WITH_PSK)
6074 args->ctx_psk = ctx_psk;
6075 args->psk_identity_for_cb = psk_identity_for_cb;
6076 args->psk_identity_len_for_cb = psk_identity_len_for_cb;
6077 args->psk_for_cb = psk_for_cb;
6078 args->psk_len_for_cb = psk_len_for_cb;
6079 #endif
6080 #endif /* defined(HAVE_OPENSSL) */
6081 }
6082
6083 /******************************************************************************
6084 * *
6085 * Function: zbx_tls_take_vars *
6086 * *
6087 * Purpose: pass some TLS variables from one thread to other *
6088 * *
6089 * Comments: used in Zabbix sender on MS Windows *
6090 * *
6091 ******************************************************************************/
zbx_tls_take_vars(ZBX_THREAD_SENDVAL_TLS_ARGS * args)6092 void zbx_tls_take_vars(ZBX_THREAD_SENDVAL_TLS_ARGS *args)
6093 {
6094 #if defined(HAVE_POLARSSL)
6095 my_psk = args->my_psk;
6096 my_psk_len = args->my_psk_len;
6097 my_psk_identity = args->my_psk_identity;
6098 my_psk_identity_len = args->my_psk_identity_len;
6099 ca_cert = args->ca_cert;
6100 crl = args->crl;
6101 my_cert = args->my_cert;
6102 my_priv_key = args->my_priv_key;
6103 entropy = args->entropy;
6104 ctr_drbg = args->ctr_drbg;
6105 ciphersuites_cert = args->ciphersuites_cert;
6106 ciphersuites_psk = args->ciphersuites_psk;
6107 #elif defined(HAVE_GNUTLS)
6108 my_cert_creds = args->my_cert_creds;
6109 my_psk_client_creds = args->my_psk_client_creds;
6110 ciphersuites_cert = args->ciphersuites_cert;
6111 ciphersuites_psk = args->ciphersuites_psk;
6112 #elif defined(HAVE_OPENSSL)
6113 ctx_cert = args->ctx_cert;
6114 #if defined(HAVE_OPENSSL_WITH_PSK)
6115 ctx_psk = args->ctx_psk;
6116 psk_identity_for_cb = args->psk_identity_for_cb;
6117 psk_identity_len_for_cb = args->psk_identity_len_for_cb;
6118 psk_for_cb = args->psk_for_cb;
6119 psk_len_for_cb = args->psk_len_for_cb;
6120 #endif
6121 #endif /* defined(HAVE_OPENSSL) */
6122 }
6123 #endif
6124
6125 #endif
6126