Debian Codegraph @

runtime/nsd_gtls.c

raw
1 /* nsd_gtls.c
2 *
3 * An implementation of the nsd interface for GnuTLS.
4 *
5 * Copyright (C) 2007-2025 Rainer Gerhards and Adiscon GmbH.
6 *
7 * This file is part of the rsyslog runtime library.
8 *
9 * The rsyslog runtime library is free software: you can redistribute it and/or modify
10 * it under the terms of the GNU Lesser General Public License as published by
11 * the Free Software Foundation, either version 3 of the License, or
12 * (at your option) any later version.
13 *
14 * The rsyslog runtime library is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU Lesser General Public License for more details.
18 *
19 * You should have received a copy of the GNU Lesser General Public License
20 * along with the rsyslog runtime library. If not, see <http://www.gnu.org/licenses/>.
21 *
22 * A copy of the GPL can be found in the file "COPYING" in this distribution.
23 * A copy of the LGPL can be found in the file "COPYING.LESSER" in this distribution.
24 */
25 #include "config.h"
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <assert.h>
29 #include <string.h>
30 #include <gnutls/gnutls.h>
31 #include <gnutls/x509.h>
32 #if GNUTLS_VERSION_NUMBER <= 0x020b00
33 #include <gcrypt.h>
34 #endif
35 #include <errno.h>
36 #include <sys/stat.h>
37 #include <unistd.h>
38 #include <fcntl.h>
39 #include <pthread.h>
40 #include <arpa/inet.h>
41
42 #include "rsyslog.h"
43 #include "syslogd-types.h"
44 #include "module-template.h"
45 #include "cfsysline.h"
46 #include "obj.h"
47 #include "stringbuf.h"
48 #include "errmsg.h"
49 #include "net.h"
50 #include "datetime.h"
51 #include "netstrm.h"
52 #include "netstrms.h"
53 #include "nsd_ptcp.h"
54 #include "nsd_gtls.h"
55 #include "unicode-helper.h"
56 #include "rsconf.h"
57
58 #if GNUTLS_VERSION_NUMBER <= 0x020b00
59 GCRY_THREAD_OPTION_PTHREAD_IMPL;
60 #endif
61 MODULE_TYPE_LIB
62 MODULE_TYPE_KEEP;
63
64 /* static data */
65 DEFobjStaticHelpers;
66 DEFobjCurrIf(glbl) DEFobjCurrIf(net) DEFobjCurrIf(datetime) DEFobjCurrIf(nsd_ptcp)
67
68
69 /* Static Helper variables for certless communication */
70 static gnutls_anon_client_credentials_t anoncred; /**< client anon credentials */
71 static gnutls_anon_server_credentials_t anoncredSrv; /**< server anon credentials */
72 static int dhBits = 2048; /**< number of bits for Diffie-Hellman key */
73 static int dhMinBits = 512; /**< minimum number of bits for Diffie-Hellman key */
74
75 static pthread_mutex_t mutGtlsStrerror;
76 /*< a mutex protecting the potentially non-reentrant gtlStrerror() function */
77
78 static gnutls_dh_params_t dh_params; /**< server DH parameters for anon mode */
79
80 /* Module-level bitfield for warnings that have been logged (shared across all instances)
81 * NOTE: Intentionally NOT thread-safe. Occasional duplicate warnings (1-2) are acceptable
82 * vs. thousands without this mechanism. Atomic ops/locks are overkill for startup warnings.
83 */
84 static unsigned loggedWarnings = 0;
85
86 /* bitfield for warnings that have been logged */
87 enum {
88 GTLS_LOGGED_WARN_CERT_MISSING = 1 << 0,
89 GTLS_LOGGED_WARN_KEY_MISSING = 1 << 1,
90 GTLS_LOGGED_WARN_CA_MISSING = 1 << 2
91 };
92
93 /* a macro to abort if GnuTLS error is not acceptable. We split this off from
94 * CHKgnutls() to avoid some Coverity report in cases where we know GnuTLS
95 * failed. Note: gnuRet must already be set accordingly!
96 */
97 #define ABORTgnutls \
98 { \
99 uchar *pErr = gtlsStrerror(gnuRet); \
100 LogError(0, RS_RET_GNUTLS_ERR, "unexpected GnuTLS error %d in %s:%d: %s\n", gnuRet, __FILE__, __LINE__, pErr); \
101 free(pErr); \
102 ABORT_FINALIZE(RS_RET_GNUTLS_ERR); \
103 }
104 /* a macro to check GnuTLS calls against unexpected errors */
105 #define CHKgnutls(x) \
106 { \
107 gnuRet = (x); \
108 if (gnuRet == GNUTLS_E_FILE_ERROR) { \
109 LogError(0, RS_RET_GNUTLS_ERR, \
110 "error reading file - a common cause is that the " \
111 "file does not exist"); \
112 ABORT_FINALIZE(RS_RET_GNUTLS_ERR); \
113 } else if (gnuRet != 0) { \
114 ABORTgnutls; \
115 } \
116 }
117
118
119 /* ------------------------------ GnuTLS specifics ------------------------------ */
120 static rsRetVal doRetry(nsd_gtls_t *pNsd) {
121 DEFiRet;
122 int gnuRet;
123
124 dbgprintf("doRetry: GnuTLS requested retry of operation %d - executing\n", pNsd->rtryCall);
125
126 /* We follow a common scheme here: first, we do the systen call and
127 * then we check the result. So far, the result is checked after the
128 * switch, because the result check is the same for all calls. Note that
129 * this may change once we deal with the read and write calls (but
130 * probably this becomes an issue only when we begin to work on TLS
131 * for relp). -- rgerhards, 2008-04-30
132 */
133 switch (pNsd->rtryCall) {
134 case gtlsRtry_handshake:
135 gnuRet = gnutls_handshake(pNsd->sess);
136 if (gnuRet == GNUTLS_E_AGAIN || gnuRet == GNUTLS_E_INTERRUPTED) {
137 dbgprintf(
138 "doRetry: GnuTLS handshake retry did not finish - "
139 "setting to retry (this is OK and can happen)\n");
140 FINALIZE;
141 } else if (gnuRet == 0) {
142 pNsd->rtryCall = gtlsRtry_None; /* we are done */
143 /* we got a handshake, now check authorization */
144 CHKiRet(gtlsChkPeerAuth(pNsd));
145 } else {
146 uchar *pGnuErr = gtlsStrerror(gnuRet);
147 uchar *fromHostIP = NULL;
148 int remotePort;
149 uchar remotePortStr[8];
150 nsd_ptcp.GetRemoteHName(pNsd->pTcp, &fromHostIP);
151 nsd_ptcp.GetRemotePort(pNsd->pTcp, &remotePort);
152 nsd_ptcp.FmtRemotePortStr(remotePort, remotePortStr, sizeof(remotePortStr));
153 LogError(0, RS_RET_TLS_HANDSHAKE_ERR,
154 "nsd_gtls:TLS session terminated with remote client '%s:%s': "
155 " GnuTLS handshake retry returned error: %s",
156 fromHostIP, remotePortStr, pGnuErr);
157 free(fromHostIP);
158 free(pGnuErr);
159 ABORT_FINALIZE(RS_RET_TLS_HANDSHAKE_ERR);
160 }
161 break;
162 case gtlsRtry_recv:
163 case gtlsRtry_None:
164 default:
165 assert(0); /* this shall not happen! */
166 dbgprintf("ERROR: pNsd->rtryCall %d invalid in nsd_gtls.c:%d\n", pNsd->rtryCall, __LINE__);
167 gnuRet = 0; /* if it happens, we have at least a defined behaviour... ;) */
168 break;
169 }
170
171 if (gnuRet == 0) {
172 pNsd->rtryCall = gtlsRtry_None; /* we are done */
173 } else if (gnuRet != GNUTLS_E_AGAIN && gnuRet != GNUTLS_E_INTERRUPTED) {
174 uchar *pErr = gtlsStrerror(gnuRet);
175 LogError(0, RS_RET_GNUTLS_ERR, "unexpected GnuTLS error %d in %s:%d: %s\n", gnuRet, __FILE__, __LINE__, pErr);
176 free(pErr);
177 pNsd->rtryCall = gtlsRtry_None; /* we are also done... ;) */
178 ABORT_FINALIZE(RS_RET_GNUTLS_ERR);
179 }
180 /* if we are interrupted once again (else case), we do not need to
181 * change our status because we are already setup for retries.
182 */
183
184 finalize_it:
185 if (iRet != RS_RET_OK && iRet != RS_RET_CLOSED && iRet != RS_RET_RETRY) pNsd->bAbortConn = 1; /* request abort */
186 RETiRet;
187 }
188
189 /* This defines a log function to be provided to GnuTLS. It hopefully
190 * helps us track down hard to find problems.
191 * rgerhards, 2008-06-20
192 */
193 static void logFunction(int level, const char *msg) {
194 dbgprintf("GnuTLS log msg, level %d: %s\n", level, msg);
195 }
196
197 /* read in the whole content of a file. The caller is responsible for
198 * freeing the buffer. To prevent DOS, this function can NOT read
199 * files larger than 1MB (which still is *very* large).
200 * rgerhards, 2008-05-26
201 */
202 static rsRetVal readFile(const uchar *const pszFile, gnutls_datum_t *const pBuf) {
203 int fd;
204 struct stat stat_st;
205 DEFiRet;
206
207 assert(pszFile != NULL);
208 assert(pBuf != NULL);
209
210 pBuf->data = NULL;
211
212 if ((fd = open((char *)pszFile, O_RDONLY)) == -1) {
213 LogError(errno, RS_RET_FILE_NOT_FOUND, "can not read file '%s'", pszFile);
214 ABORT_FINALIZE(RS_RET_FILE_NOT_FOUND);
215 }
216
217 if (fstat(fd, &stat_st) == -1) {
218 LogError(errno, RS_RET_FILE_NO_STAT, "can not stat file '%s'", pszFile);
219 ABORT_FINALIZE(RS_RET_FILE_NO_STAT);
220 }
221
222 /* 1MB limit */
223 if (stat_st.st_size > 1024 * 1024) {
224 LogError(0, RS_RET_FILE_TOO_LARGE, "file '%s' too large, max 1MB", pszFile);
225 ABORT_FINALIZE(RS_RET_FILE_TOO_LARGE);
226 }
227
228 CHKmalloc(pBuf->data = malloc(stat_st.st_size));
229 pBuf->size = stat_st.st_size;
230 if (read(fd, pBuf->data, stat_st.st_size) != stat_st.st_size) {
231 LogError(0, RS_RET_IO_ERROR, "error or incomplete read of file '%s'", pszFile);
232 ABORT_FINALIZE(RS_RET_IO_ERROR);
233 }
234
235 finalize_it:
236 if (fd != -1) close(fd);
237 if (iRet != RS_RET_OK) {
238 if (pBuf->data != NULL) {
239 free(pBuf->data);
240 pBuf->data = NULL;
241 pBuf->size = 0;
242 }
243 }
244 RETiRet;
245 }
246
247
248 /* Load the certificate and the private key into our own store. We need to do
249 * this in the client case, to support fingerprint authentication. In that case,
250 * we may be presented no matching root certificate, but we must provide ours.
251 * The only way to do that is via the cert callback interface, but for it we
252 * need to load certificates into our private store.
253 * rgerhards, 2008-05-26
254 */
255 static rsRetVal gtlsLoadOurCertKey(nsd_gtls_t *pThis) {
256 DEFiRet;
257 int gnuRet;
258 gnutls_datum_t data = {NULL, 0};
259 const uchar *keyFile;
260 const uchar *certFile;
261
262 ISOBJ_TYPE_assert(pThis, nsd_gtls);
263
264 certFile = (pThis->pszCertFile == NULL) ? glbl.GetDfltNetstrmDrvrCertFile(runConf) : pThis->pszCertFile;
265 keyFile = (pThis->pszKeyFile == NULL) ? glbl.GetDfltNetstrmDrvrKeyFile(runConf) : pThis->pszKeyFile;
266
267 if (certFile == NULL || keyFile == NULL) {
268 /* in this case, we can not set our certificate. If we are
269 * a client and the server is running in "anon" auth mode, this
270 * may be well acceptable. In other cases, we will see some
271 * more error messages down the road. -- rgerhards, 2008-07-02
272 */
273 dbgprintf("gtlsLoadOurCertKey our certificate is not set, file name values are cert: '%s', key: '%s'\n",
274 certFile, keyFile);
275 ABORT_FINALIZE(RS_RET_CERTLESS);
276 }
277
278 /* try load certificate */
279 CHKiRet(readFile(certFile, &data));
280 pThis->nOurCerts = sizeof(pThis->pOurCerts) / sizeof(gnutls_x509_crt_t);
281 gnuRet = gnutls_x509_crt_list_import(pThis->pOurCerts, &pThis->nOurCerts, &data, GNUTLS_X509_FMT_PEM,
282 GNUTLS_X509_CRT_LIST_IMPORT_FAIL_IF_EXCEED);
283 if (gnuRet < 0) {
284 ABORTgnutls;
285 }
286 pThis->bOurCertIsInit = 1;
287 free(data.data);
288 data.data = NULL;
289
290 /* try load private key */
291 CHKiRet(readFile(keyFile, &data));
292 CHKgnutls(gnutls_x509_privkey_init(&pThis->ourKey));
293 pThis->bOurKeyIsInit = 1;
294 CHKgnutls(gnutls_x509_privkey_import(pThis->ourKey, &data, GNUTLS_X509_FMT_PEM));
295 free(data.data);
296
297
298 finalize_it:
299 if (iRet == RS_RET_CERTLESS) {
300 dbgprintf("gtlsLoadOurCertKey certless exit\n");
301 pThis->bOurCertIsInit = 0;
302 pThis->bOurKeyIsInit = 0;
303 } else if (iRet != RS_RET_OK) {
304 dbgprintf("gtlsLoadOurCertKey error exit\n");
305 if (data.data != NULL) free(data.data);
306 if (pThis->bOurCertIsInit) {
307 for (unsigned i = 0; i < pThis->nOurCerts; ++i) {
308 gnutls_x509_crt_deinit(pThis->pOurCerts[i]);
309 }
310 pThis->bOurCertIsInit = 0;
311 }
312 if (pThis->bOurKeyIsInit) {
313 gnutls_x509_privkey_deinit(pThis->ourKey);
314 pThis->bOurKeyIsInit = 0;
315 }
316 } else {
317 dbgprintf("gtlsLoadOurCertKey Successfully Loaded cert '%s' and key: '%s'\n", certFile, keyFile);
318 }
319 RETiRet;
320 }
321
322
323 /* This callback must be associated with a session by calling
324 * gnutls_certificate_client_set_retrieve_function(session, cert_callback),
325 * before a handshake. We will always return the configured certificate,
326 * even if it does not match the peer's trusted CAs. This is necessary
327 * to use self-signed certs in fingerprint mode. And, yes, this usage
328 * of the callback is quite a hack. But it seems the only way to
329 * obey to the IETF -transport-tls I-D.
330 * Note: GnuTLS requires the function to return 0 on success and
331 * -1 on failure.
332 * rgerhards, 2008-05-27
333 */
334 static int gtlsClientCertCallback(gnutls_session_t session,
335 __attribute__((unused)) const gnutls_datum_t *req_ca_rdn,
336 int __attribute__((unused)) nreqs,
337 __attribute__((unused)) const gnutls_pk_algorithm_t *sign_algos,
338 int __attribute__((unused)) sign_algos_length,
339 #if HAVE_GNUTLS_CERTIFICATE_SET_RETRIEVE_FUNCTION
340 gnutls_retr2_st *st
341 #else
342 gnutls_retr_st *st
343 #endif
344 ) {
345 nsd_gtls_t *pThis;
346
347 pThis = (nsd_gtls_t *)gnutls_session_get_ptr(session);
348
349 #if HAVE_GNUTLS_CERTIFICATE_SET_RETRIEVE_FUNCTION
350 st->cert_type = GNUTLS_CRT_X509;
351 #else
352 st->type = GNUTLS_CRT_X509;
353 #endif
354 st->ncerts = pThis->nOurCerts;
355 st->cert.x509 = pThis->pOurCerts;
356 st->key.x509 = pThis->ourKey;
357 st->deinit_all = 0;
358
359 return 0;
360 }
361
362
363 /* This function extracts some information about this session's peer
364 * certificate. Works for X.509 certificates only. Adds all
365 * of the info to a cstr_t, which is handed over to the caller.
366 * Caller must destruct it when no longer needed.
367 * rgerhards, 2008-05-21
368 */
369 static rsRetVal gtlsGetCertInfo(nsd_gtls_t *const pThis, cstr_t **ppStr) {
370 uchar szBufA[1024];
371 uchar *szBuf = szBufA;
372 size_t szBufLen = sizeof(szBufA), tmp;
373 unsigned int algo, bits;
374 time_t expiration_time, activation_time;
375 const gnutls_datum_t *cert_list;
376 unsigned cert_list_size = 0;
377 gnutls_x509_crt_t cert;
378 cstr_t *pStr = NULL;
379 int gnuRet;
380 DEFiRet;
381 unsigned iAltName;
382
383 assert(ppStr != NULL);
384 ISOBJ_TYPE_assert(pThis, nsd_gtls);
385
386 if (gnutls_certificate_type_get(pThis->sess) != GNUTLS_CRT_X509) return RS_RET_TLS_CERT_ERR;
387
388 cert_list = gnutls_certificate_get_peers(pThis->sess, &cert_list_size);
389 CHKiRet(rsCStrConstructFromszStrf(&pStr, "peer provided %d certificate(s). ", cert_list_size));
390
391 if (cert_list_size > 0) {
392 /* we only print information about the first certificate */
393 CHKgnutls(gnutls_x509_crt_init(&cert));
394 CHKgnutls(gnutls_x509_crt_import(cert, &cert_list[0], GNUTLS_X509_FMT_DER));
395
396 expiration_time = gnutls_x509_crt_get_expiration_time(cert);
397 activation_time = gnutls_x509_crt_get_activation_time(cert);
398 ctime_r(&activation_time, (char *)szBuf);
399 szBuf[ustrlen(szBuf) - 1] = '\0'; /* strip linefeed */
400 CHKiRet(rsCStrAppendStrf(pStr,
401 "Certificate 1 info: "
402 "certificate valid from %s ",
403 szBuf));
404 ctime_r(&expiration_time, (char *)szBuf);
405 szBuf[ustrlen(szBuf) - 1] = '\0'; /* strip linefeed */
406 CHKiRet(rsCStrAppendStrf(pStr, "to %s; ", szBuf));
407
408 /* Extract some of the public key algorithm's parameters */
409 algo = gnutls_x509_crt_get_pk_algorithm(cert, &bits);
410 CHKiRet(rsCStrAppendStrf(pStr, "Certificate public key: %s; ", gnutls_pk_algorithm_get_name(algo)));
411
412 /* names */
413 tmp = szBufLen;
414 if (gnutls_x509_crt_get_dn(cert, (char *)szBuf, &tmp) == GNUTLS_E_SHORT_MEMORY_BUFFER) {
415 szBufLen = tmp;
416 szBuf = malloc(tmp);
417 gnutls_x509_crt_get_dn(cert, (char *)szBuf, &tmp);
418 }
419 CHKiRet(rsCStrAppendStrf(pStr, "DN: %s; ", szBuf));
420
421 tmp = szBufLen;
422 if (gnutls_x509_crt_get_issuer_dn(cert, (char *)szBuf, &tmp) == GNUTLS_E_SHORT_MEMORY_BUFFER) {
423 szBufLen = tmp;
424 szBuf = realloc((szBuf == szBufA) ? NULL : szBuf, tmp);
425 gnutls_x509_crt_get_issuer_dn(cert, (char *)szBuf, &tmp);
426 }
427 CHKiRet(rsCStrAppendStrf(pStr, "Issuer DN: %s; ", szBuf));
428
429 /* dNSName alt name */
430 iAltName = 0;
431 while (1) { /* loop broken below */
432 tmp = szBufLen;
433 gnuRet = gnutls_x509_crt_get_subject_alt_name(cert, iAltName, szBuf, &tmp, NULL);
434 if (gnuRet == GNUTLS_E_SHORT_MEMORY_BUFFER) {
435 szBufLen = tmp;
436 szBuf = realloc((szBuf == szBufA) ? NULL : szBuf, tmp);
437 continue;
438 } else if (gnuRet < 0)
439 break;
440 else if (gnuRet == GNUTLS_SAN_DNSNAME) {
441 /* we found it! */
442 CHKiRet(rsCStrAppendStrf(pStr, "SAN:DNSname: %s; ", szBuf));
443 /* do NOT break, because there may be multiple dNSName's! */
444 } else if (gnuRet == GNUTLS_SAN_IPADDRESS) {
445 char ipAddress[INET6_ADDRSTRLEN];
446 /* we found it! */
447 inet_ntop(((tmp == sizeof(struct in6_addr)) ? AF_INET6 : AF_INET), szBuf, ipAddress, sizeof(ipAddress));
448 CHKiRet(rsCStrAppendStrf(pStr, "SAN:IPaddress: %s; ", ipAddress));
449 /* do NOT break, because there may be multiple ipAddr's! */
450 }
451 ++iAltName;
452 }
453
454 gnutls_x509_crt_deinit(cert);
455 }
456
457 cstrFinalize(pStr);
458 *ppStr = pStr;
459
460 finalize_it:
461 if (iRet != RS_RET_OK) {
462 if (pStr != NULL) rsCStrDestruct(&pStr);
463 }
464 if (szBuf != szBufA) free(szBuf);
465
466 RETiRet;
467 }
468
469
470 #if 0 /* we may need this in the future - code needs to be looked at then! */
471 /* This function will print some details of the
472 * given pThis->sess.
473 */
474 static rsRetVal
475 print_info(nsd_gtls_t *pThis)
476 {
477 const char *tmp;
478 gnutls_credentials_type cred;
479 gnutls_kx_algorithm kx;
480 DEFiRet;
481
482 ISOBJ_TYPE_assert(pThis, nsd_gtls);
483 /* print the key exchange's algorithm name
484 */
485 kx = gnutls_kx_get(pThis->sess);
486 tmp = gnutls_kx_get_name(kx);
487 dbgprintf("- Key Exchange: %s\n", tmp);
488
489 /* Check the authentication type used and switch
490 * to the appropriate.
491 */
492 cred = gnutls_auth_get_type(pThis->sess);
493 switch (cred) {
494 case GNUTLS_CRD_ANON: /* anonymous authentication */
495 dbgprintf("- Anonymous DH using prime of %d bits\n",
496 gnutls_dh_get_prime_bits(pThis->sess));
497 break;
498 case GNUTLS_CRD_CERTIFICATE: /* certificate authentication */
499 /* Check if we have been using ephemeral Diffie Hellman.
500 */
501 if (kx == GNUTLS_KX_DHE_RSA || kx == GNUTLS_KX_DHE_DSS) {
502 dbgprintf("\n- Ephemeral DH using prime of %d bits\n",
503 gnutls_dh_get_prime_bits(pThis->sess));
504 }
505
506 /* if the certificate list is available, then
507 * print some information about it.
508 */
509 gtlsPrintCert(pThis);
510 break;
511 case GNUTLS_CRD_SRP: /* certificate authentication */
512 dbgprintf("GNUTLS_CRD_SRP/IA");
513 break;
514 case GNUTLS_CRD_PSK: /* certificate authentication */
515 dbgprintf("GNUTLS_CRD_PSK");
516 break;
517 case GNUTLS_CRD_IA: /* certificate authentication */
518 dbgprintf("GNUTLS_CRD_IA");
519 break;
520 } /* switch */
521
522 /* print the protocol's name (ie TLS 1.0) */
523 tmp = gnutls_protocol_get_name(gnutls_protocol_get_version(pThis->sess));
524 dbgprintf("- Protocol: %s\n", tmp);
525
526 /* print the certificate type of the peer.
527 * ie X.509
528 */
529 tmp = gnutls_certificate_type_get_name(
530 gnutls_certificate_type_get(pThis->sess));
531
532 dbgprintf("- Certificate Type: %s\n", tmp);
533
534 /* print the compression algorithm (if any)
535 */
536 tmp = gnutls_compression_get_name( gnutls_compression_get(pThis->sess));
537 dbgprintf("- Compression: %s\n", tmp);
538
539 /* print the name of the cipher used.
540 * ie 3DES.
541 */
542 tmp = gnutls_cipher_get_name(gnutls_cipher_get(pThis->sess));
543 dbgprintf("- Cipher: %s\n", tmp);
544
545 /* Print the MAC algorithms name.
546 * ie SHA1
547 */
548 tmp = gnutls_mac_get_name(gnutls_mac_get(pThis->sess));
549 dbgprintf("- MAC: %s\n", tmp);
550
551 RETiRet;
552 }
553 #endif
554
555
556 /* Convert a fingerprint to printable data. The conversion is carried out
557 * according IETF I-D syslog-transport-tls-12. The fingerprint string is
558 * returned in a new cstr object. It is the caller's responsibility to
559 * destruct that object.
560 * rgerhards, 2008-05-08
561 */
562 static rsRetVal GenFingerprintStr(uchar *pFingerprint, size_t sizeFingerprint, cstr_t **ppStr, const char *prefix) {
563 cstr_t *pStr = NULL;
564 uchar buf[4];
565 size_t i;
566 DEFiRet;
567
568 CHKiRet(rsCStrConstruct(&pStr));
569 CHKiRet(rsCStrAppendStrWithLen(pStr, (uchar *)prefix, strlen(prefix)));
570 for (i = 0; i < sizeFingerprint; ++i) {
571 snprintf((char *)buf, sizeof(buf), ":%2.2X", pFingerprint[i]);
572 CHKiRet(rsCStrAppendStrWithLen(pStr, buf, 3));
573 }
574 cstrFinalize(pStr);
575
576 *ppStr = pStr;
577
578 finalize_it:
579 if (iRet != RS_RET_OK) {
580 if (pStr != NULL) rsCStrDestruct(&pStr);
581 }
582 RETiRet;
583 }
584
585
586 /* a thread-safe variant of gnutls_strerror
587 * The caller must free the returned string.
588 * rgerhards, 2008-04-30
589 */
590 uchar *gtlsStrerror(int error) {
591 uchar *pErr;
592
593 pthread_mutex_lock(&mutGtlsStrerror);
594 pErr = (uchar *)strdup(gnutls_strerror(error));
595 pthread_mutex_unlock(&mutGtlsStrerror);
596
597 return pErr;
598 }
599
600
601 /* try to receive a record from the remote peer. This works with
602 * our own abstraction and handles local buffering and EAGAIN.
603 * See details on local buffering in Rcv() header-comment.
604 * This function MUST only be called when the local buffer is
605 * empty. Calling it otherwise will cause losss of current buffer
606 * data.
607 * rgerhards, 2008-06-24
608 */
609 rsRetVal gtlsRecordRecv(nsd_gtls_t *const pThis, unsigned int *nextIODirection) {
610 ssize_t lenRcvd;
611 DEFiRet;
612
613 ISOBJ_TYPE_assert(pThis, nsd_gtls);
614 DBGPRINTF("gtlsRecordRecv: start (Pending Data: %zd | Wanted Direction: %s)\n",
615 gnutls_record_check_pending(pThis->sess),
616 (gnutls_record_get_direction(pThis->sess) == gtlsDir_READ ? "READ" : "WRITE"));
617 lenRcvd = gnutls_record_recv(pThis->sess, pThis->pszRcvBuf, NSD_GTLS_MAX_RCVBUF);
618 if (lenRcvd >= 0) {
619 DBGPRINTF("gtlsRecordRecv: gnutls_record_recv received %zd bytes\n", lenRcvd);
620 pThis->lenRcvBuf = lenRcvd;
621 pThis->ptrRcvBuf = 0;
622
623 /* Check for additional data in SSL buffer */
624 size_t stBytesLeft = gnutls_record_check_pending(pThis->sess);
625 if (stBytesLeft > 0) {
626 DBGPRINTF("gtlsRecordRecv: %zd Bytes pending after gnutls_record_recv, expand buffer.\n", stBytesLeft);
627 /* realloc buffer size and preserve char content */
628 char *const newbuf = realloc(pThis->pszRcvBuf, NSD_GTLS_MAX_RCVBUF + stBytesLeft);
629 CHKmalloc(newbuf);
630 pThis->pszRcvBuf = newbuf;
631
632 /* 2nd read will read missing bytes from the current SSL Packet */
633 lenRcvd = gnutls_record_recv(pThis->sess, pThis->pszRcvBuf + NSD_GTLS_MAX_RCVBUF, stBytesLeft);
634 if (lenRcvd > 0) {
635 DBGPRINTF("gtlsRecordRecv: 2nd SSL_read received %zd bytes\n", (NSD_GTLS_MAX_RCVBUF + lenRcvd));
636 pThis->lenRcvBuf = NSD_GTLS_MAX_RCVBUF + lenRcvd;
637 } else {
638 if (lenRcvd == GNUTLS_E_AGAIN || lenRcvd == GNUTLS_E_INTERRUPTED) {
639 goto sslerragain; /* Go to ERR AGAIN handling */
640 } else {
641 /* Do all other error handling */
642 int gnuRet = lenRcvd;
643 ABORTgnutls;
644 }
645 }
646 }
647 } else if (lenRcvd == GNUTLS_E_AGAIN || lenRcvd == GNUTLS_E_INTERRUPTED) {
648 sslerragain:
649 /* Check if the underlaying file descriptor needs to read or write data!*/
650 pThis->rtryCall = gtlsRtry_recv; /* _recv refers to the gnutls call, not socket layer! */
651 dbgprintf("GnuTLS receive requires a retry, this most probably is OK and no error condition\n");
652 *nextIODirection = (gnutls_record_get_direction(pThis->sess) == 0) ? NSDSEL_RD : NSDSEL_WR;
653 ABORT_FINALIZE(RS_RET_RETRY);
654 } else {
655 int gnuRet = lenRcvd;
656 ABORTgnutls;
657 }
658
659 finalize_it:
660 dbgprintf("gtlsRecordRecv return. nsd %p, iRet %d, lenRcvd %d, lenRcvBuf %d, ptrRcvBuf %d\n", pThis, iRet,
661 (int)lenRcvd, pThis->lenRcvBuf, pThis->ptrRcvBuf);
662 RETiRet;
663 }
664
665
666 /* add our own certificate to the certificate set, so that the peer
667 * can identify us. Please note that we try to use mutual authentication,
668 * so we always add a cert, even if we are in the client role (later,
669 * this may be controlled by a config setting).
670 * rgerhards, 2008-05-15
671 */
672 static rsRetVal gtlsAddOurCert(nsd_gtls_t *const pThis) {
673 int gnuRet = 0;
674 const uchar *keyFile;
675 const uchar *certFile;
676 uchar *pGnuErr; /* for GnuTLS error reporting */
677 DEFiRet;
678
679 certFile = (pThis->pszCertFile == NULL) ? glbl.GetDfltNetstrmDrvrCertFile(runConf) : pThis->pszCertFile;
680 keyFile = (pThis->pszKeyFile == NULL) ? glbl.GetDfltNetstrmDrvrKeyFile(runConf) : pThis->pszKeyFile;
681 dbgprintf("GTLS certificate file: '%s'\n", certFile);
682 dbgprintf("GTLS key file: '%s'\n", keyFile);
683
684 if (certFile == NULL && !(loggedWarnings & GTLS_LOGGED_WARN_CERT_MISSING)) {
685 LogError(0, RS_RET_CERT_MISSING, "warning: certificate file is not set");
686 loggedWarnings |= GTLS_LOGGED_WARN_CERT_MISSING;
687 }
688 if (keyFile == NULL && !(loggedWarnings & GTLS_LOGGED_WARN_KEY_MISSING)) {
689 LogError(0, RS_RET_CERTKEY_MISSING, "warning: key file is not set");
690 loggedWarnings |= GTLS_LOGGED_WARN_KEY_MISSING;
691 }
692
693 /* set certificate in gnutls */
694 if (certFile != NULL && keyFile != NULL) {
695 CHKgnutls(
696 gnutls_certificate_set_x509_key_file(pThis->xcred, (char *)certFile, (char *)keyFile, GNUTLS_X509_FMT_PEM));
697 }
698
699 finalize_it:
700 if (iRet != RS_RET_OK && iRet != RS_RET_CERT_MISSING && iRet != RS_RET_CERTKEY_MISSING) {
701 pGnuErr = gtlsStrerror(gnuRet);
702 errno = 0;
703 LogError(0, iRet,
704 "error adding our certificate. GnuTLS error %d, message: '%s', "
705 "key: '%s', cert: '%s'",
706 gnuRet, pGnuErr, keyFile, certFile);
707 free(pGnuErr);
708 }
709 RETiRet;
710 }
711
712 /*
713 * removecomment ifdef out if needed
714 */
715 #ifdef false
716
717 static void print_cipher_suite_list(const char *priorities) {
718 size_t i;
719 int ret;
720 unsigned int idx;
721 const char *name;
722 const char *err;
723 unsigned char id[2];
724 gnutls_protocol_t version;
725 gnutls_priority_t pcache;
726
727 if (priorities != NULL) {
728 printf("print_cipher_suite_list: Cipher suites for %s\n", priorities);
729
730 ret = gnutls_priority_init(&pcache, priorities, &err);
731 if (ret < 0) {
732 fprintf(stderr, "print_cipher_suite_list: Syntax error at: %s\n", err);
733 exit(1);
734 }
735
736 for (i = 0;; i++) {
737 ret = gnutls_priority_get_cipher_suite_index(pcache, i, &idx);
738 if (ret == GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE) break;
739 if (ret == GNUTLS_E_UNKNOWN_CIPHER_SUITE) continue;
740
741 name = gnutls_cipher_suite_info(idx, id, NULL, NULL, NULL, &version);
742
743 if (name != NULL)
744 dbgprintf("print_cipher_suite_list: %-50s\t0x%02x, 0x%02x\t%s\n", name, (unsigned char)id[0],
745 (unsigned char)id[1], gnutls_protocol_get_name(version));
746 }
747
748 return;
749 }
750 }
751 #endif
752
753 /* initialize GnuTLS credential structure (certs etc) */
754 static rsRetVal gtlsInitCred(nsd_gtls_t *const pThis) {
755 int gnuRet;
756 const uchar *cafile, *crlfile;
757 DEFiRet;
758
759 /* X509 stuff */
760 if (pThis->xcred == NULL) {
761 /* Allocate only ONCE */
762 CHKgnutls(gnutls_certificate_allocate_credentials(&pThis->xcred));
763 }
764
765 /* sets the trusted cas file */
766 cafile = (pThis->pszCAFile == NULL) ? glbl.GetDfltNetstrmDrvrCAF(runConf) : pThis->pszCAFile;
767 if (cafile == NULL && !(loggedWarnings & GTLS_LOGGED_WARN_CA_MISSING)) {
768 LogError(0, RS_RET_CA_CERT_MISSING, "Warning: CA certificate is not set");
769 loggedWarnings |= GTLS_LOGGED_WARN_CA_MISSING;
770 }
771 if (cafile != NULL) {
772 dbgprintf("GTLS CA file: '%s'\n", cafile);
773 gnuRet = gnutls_certificate_set_x509_trust_file(pThis->xcred, (char *)cafile, GNUTLS_X509_FMT_PEM);
774 if (gnuRet == GNUTLS_E_FILE_ERROR) {
775 LogError(0, RS_RET_GNUTLS_ERR,
776 "error reading certificate file '%s' - a common cause is that the "
777 "file does not exist",
778 cafile);
779 ABORT_FINALIZE(RS_RET_GNUTLS_ERR);
780 } else if (gnuRet < 0) {
781 /* TODO; a more generic error-tracking function (this one based on CHKgnutls()) */
782 uchar *pErr = gtlsStrerror(gnuRet);
783 LogError(0, RS_RET_GNUTLS_ERR, "unexpected GnuTLS error reading CA certificate file %d in %s:%d: %s\n",
784 gnuRet, __FILE__, __LINE__, pErr);
785 free(pErr);
786 ABORT_FINALIZE(RS_RET_GNUTLS_ERR);
787 }
788 }
789
790 crlfile = (pThis->pszCRLFile == NULL) ? glbl.GetDfltNetstrmDrvrCRLF(runConf) : pThis->pszCRLFile;
791 if (crlfile == NULL) {
792 dbgprintf("Certificate revocation list (CRL) file not set.");
793 } else {
794 gnutls_datum_t crlData;
795 gnutls_x509_crl_t crl;
796
797 dbgprintf("GTLS CRL file: '%s'\n", crlfile);
798
799 gnuRet = gnutls_load_file((char *)crlfile, &crlData);
800 if (gnuRet < 0) {
801 LogError(0, RS_RET_GNUTLS_ERR,
802 "error reading Certificate revocation list (CRL) '%s' - a common cause is that the "
803 "file does not exist",
804 crlfile);
805 ABORT_FINALIZE(RS_RET_GNUTLS_ERR);
806 }
807
808 gnuRet = gnutls_x509_crl_init(&crl);
809 if (gnuRet < 0) {
810 gnutls_free(crlData.data);
811 uchar *pErr = gtlsStrerror(gnuRet);
812 LogError(0, RS_RET_GNUTLS_ERR, "error initializing CRL object: %s", pErr);
813 free(pErr);
814 ABORT_FINALIZE(RS_RET_GNUTLS_ERR);
815 }
816
817 gnuRet = gnutls_x509_crl_import(crl, &crlData, GNUTLS_X509_FMT_PEM);
818 if (gnuRet < 0) {
819 gnutls_x509_crl_deinit(crl);
820 gnutls_free(crlData.data);
821 uchar *pErr = gtlsStrerror(gnuRet);
822 LogError(0, RS_RET_GNUTLS_ERR, "error parsing Certificate revocation list (CRL) '%s': %s", crlfile, pErr);
823 free(pErr);
824 ABORT_FINALIZE(RS_RET_GNUTLS_ERR);
825 }
826
827 /* Check CRL validity period. GnuTLS does not do this automatically. */
828 time_t now = time(NULL);
829 time_t thisUpdate = gnutls_x509_crl_get_this_update(crl);
830 time_t nextUpdate = gnutls_x509_crl_get_next_update(crl);
831 gnutls_x509_crl_deinit(crl);
832 pThis->crlNextUpdate = nextUpdate;
833
834 dbgprintf("GTLS CRL '%s': thisUpdate=%lld, nextUpdate=%lld, now=%lld\n", crlfile, (long long)thisUpdate,
835 (long long)nextUpdate, (long long)now);
836
837 if (thisUpdate > 0 && now < thisUpdate) {
838 gnutls_free(crlData.data);
839 LogError(0, RS_RET_CRL_INVALID, "CRL '%s' is not yet valid (thisUpdate is in the future)", crlfile);
840 ABORT_FINALIZE(RS_RET_CRL_INVALID);
841 }
842 if (nextUpdate > 0 && now > nextUpdate) {
843 gnutls_free(crlData.data);
844 LogError(0, RS_RET_CRL_INVALID, "CRL '%s' has expired", crlfile);
845 ABORT_FINALIZE(RS_RET_CRL_INVALID);
846 }
847 dbgprintf("GTLS CRL '%s' validity check passed\n", crlfile);
848
849 /* Load CRL into credentials (using already-loaded data) */
850 gnuRet = gnutls_certificate_set_x509_crl_mem(pThis->xcred, &crlData, GNUTLS_X509_FMT_PEM);
851 gnutls_free(crlData.data);
852 if (gnuRet < 0) {
853 uchar *pErr = gtlsStrerror(gnuRet);
854 LogError(0, RS_RET_GNUTLS_ERR,
855 "unexpected GnuTLS error loading Certificate revocation list (CRL) %d in %s:%d: %s\n", gnuRet,
856 __FILE__, __LINE__, pErr);
857 free(pErr);
858 ABORT_FINALIZE(RS_RET_GNUTLS_ERR);
859 }
860 }
861
862 finalize_it:
863 RETiRet;
864 }
865
866
867 /* globally initialize GnuTLS */
868 static rsRetVal gtlsGlblInit(void) {
869 int gnuRet;
870 DEFiRet;
871
872 dbgprintf("gtlsGlblInit: Running Version: '%#010x'\n", GNUTLS_VERSION_NUMBER);
873
874 /* gcry_control must be called first, so that the thread system is correctly set up */
875 #if GNUTLS_VERSION_NUMBER <= 0x020b00
876 gcry_control(GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
877 #endif
878 CHKgnutls(gnutls_global_init());
879
880 if (GetGnuTLSLoglevel(runConf) > 0) {
881 gnutls_global_set_log_function(logFunction);
882 gnutls_global_set_log_level(GetGnuTLSLoglevel(runConf));
883 /* 0 (no) to 9 (most), 10 everything */
884 }
885
886 /* Init Anon cipher helpers */
887 CHKgnutls(gnutls_dh_params_init(&dh_params));
888 CHKgnutls(gnutls_dh_params_generate2(dh_params, dhBits));
889
890 /* Allocate ANON Client Cred */
891 CHKgnutls(gnutls_anon_allocate_client_credentials(&anoncred));
892
893 /* Allocate ANON Server Cred */
894 CHKgnutls(gnutls_anon_allocate_server_credentials(&anoncredSrv));
895 gnutls_anon_set_server_dh_params(anoncredSrv, dh_params);
896
897 finalize_it:
898 RETiRet;
899 }
900
901 static rsRetVal gtlsInitSession(nsd_gtls_t *pThis) {
902 DEFiRet;
903 int gnuRet = 0;
904 gnutls_session_t session;
905
906 gnutls_init(&session, GNUTLS_SERVER);
907 pThis->bHaveSess = 1;
908 pThis->bIsInitiator = 0;
909 pThis->sess = session;
910
911 /* Moved CertKey Loading to top */
912 #if HAVE_GNUTLS_CERTIFICATE_SET_RETRIEVE_FUNCTION
913 /* store a pointer to ourselfs (needed by callback) */
914 gnutls_session_set_ptr(pThis->sess, (void *)pThis);
915 iRet = gtlsLoadOurCertKey(pThis); /* first load .pem files */
916 if (iRet == RS_RET_OK) {
917 dbgprintf("gtlsInitSession: enable certificate checking (VerifyDepth=%d)\n", pThis->DrvrVerifyDepth);
918 gnutls_certificate_set_retrieve_function(pThis->xcred, gtlsClientCertCallback);
919 if (pThis->DrvrVerifyDepth != 0) {
920 gnutls_certificate_set_verify_limits(pThis->xcred, 8200, pThis->DrvrVerifyDepth);
921 }
922 } else if (iRet == RS_RET_CERTLESS) {
923 dbgprintf("gtlsInitSession: certificates not configured, not loaded.\n");
924 } else {
925 ABORT_FINALIZE(iRet); /* we have an error case! */
926 }
927 #endif
928
929 /* avoid calling all the priority functions, since the defaults are adequate. */
930 CHKgnutls(gnutls_credentials_set(pThis->sess, GNUTLS_CRD_CERTIFICATE, pThis->xcred));
931
932 /* check for anon authmode */
933 if (pThis->authMode == GTLS_AUTH_CERTANON) {
934 dbgprintf("gtlsInitSession: anon authmode, gnutls_credentials_set GNUTLS_CRD_ANON\n");
935 CHKgnutls(gnutls_credentials_set(pThis->sess, GNUTLS_CRD_ANON, anoncredSrv));
936 gnutls_dh_set_prime_bits(pThis->sess, dhMinBits);
937 }
938
939 /* request client certificate if any. */
940 gnutls_certificate_server_set_request(pThis->sess, GNUTLS_CERT_REQUEST);
941
942
943 finalize_it:
944 if (iRet != RS_RET_OK && iRet != RS_RET_CERTLESS) {
945 LogError(0, iRet, "gtlsInitSession failed to INIT Session %d", gnuRet);
946 }
947
948 RETiRet;
949 }
950
951
952 /* Obtain the CN from the DN field and hand it back to the caller
953 * (which is responsible for destructing it). We try to follow
954 * RFC2253 as far as it makes sense for our use-case. This function
955 * is considered a compromise providing good-enough correctness while
956 * limiting code size and complexity. If a problem occurs, we may enhance
957 * this function. A (pointer to a) certificate must be caller-provided.
958 * If no CN is contained in the cert, no string is returned
959 * (*ppstrCN remains NULL). *ppstrCN MUST be NULL on entry!
960 * rgerhards, 2008-05-22
961 */
962 static rsRetVal gtlsGetCN(gnutls_x509_crt_t *pCert, cstr_t **ppstrCN) {
963 DEFiRet;
964 int gnuRet;
965 int i;
966 int bFound;
967 cstr_t *pstrCN = NULL;
968 size_t size;
969 /* big var the last, so we hope to have all we usually neeed within one mem cache line */
970 uchar szDN[1024]; /* this should really be large enough for any non-malicious case... */
971
972 assert(pCert != NULL);
973 assert(ppstrCN != NULL);
974 assert(*ppstrCN == NULL);
975
976 size = sizeof(szDN);
977 CHKgnutls(gnutls_x509_crt_get_dn(*pCert, (char *)szDN, &size));
978
979 /* now search for the CN part */
980 i = 0;
981 bFound = 0;
982 while (!bFound && szDN[i] != '\0') {
983 /* note that we do not overrun our string due to boolean shortcut
984 * operations. If we have '\0', the if does not match and evaluation
985 * stops. Order of checks is obviously important!
986 */
987 if (szDN[i] == 'C' && szDN[i + 1] == 'N' && szDN[i + 2] == '=') {
988 bFound = 1;
989 i += 2;
990 }
991 i++;
992 }
993
994 if (!bFound) {
995 FINALIZE; /* we are done */
996 }
997
998 /* we found a common name, now extract it */
999 CHKiRet(cstrConstruct(&pstrCN));
1000 while (szDN[i] != '\0' && szDN[i] != ',') {
1001 if (szDN[i] == '\\') {
1002 /* hex escapes are not implemented */
1003 ++i; /* escape char processed */
1004 if (szDN[i] == '\0') ABORT_FINALIZE(RS_RET_CERT_INVALID_DN);
1005 CHKiRet(cstrAppendChar(pstrCN, szDN[i]));
1006 } else {
1007 CHKiRet(cstrAppendChar(pstrCN, szDN[i]));
1008 }
1009 ++i; /* char processed */
1010 }
1011 cstrFinalize(pstrCN);
1012
1013 /* we got it - we ignore the rest of the DN string (if any). So we may
1014 * not detect if it contains more than one CN
1015 */
1016
1017 *ppstrCN = pstrCN;
1018
1019 finalize_it:
1020 if (iRet != RS_RET_OK) {
1021 if (pstrCN != NULL) cstrDestruct(&pstrCN);
1022 }
1023
1024 RETiRet;
1025 }
1026
1027
1028 /* Check the peer's ID in fingerprint auth mode.
1029 * rgerhards, 2008-05-22
1030 */
1031 static rsRetVal gtlsChkPeerFingerprint(nsd_gtls_t *pThis, gnutls_x509_crt_t *pCert) {
1032 uchar fingerprint[20];
1033 uchar fingerprintSha256[32];
1034 size_t size;
1035 size_t sizeSha256;
1036 cstr_t *pstrFingerprint = NULL;
1037 cstr_t *pstrFingerprintSha256 = NULL;
1038 int bFoundPositiveMatch;
1039 permittedPeers_t *pPeer;
1040 int gnuRet;
1041 DEFiRet;
1042
1043 ISOBJ_TYPE_assert(pThis, nsd_gtls);
1044
1045 /* obtain the SHA1 fingerprint */
1046 size = sizeof(fingerprint);
1047 sizeSha256 = sizeof(fingerprintSha256);
1048 CHKgnutls(gnutls_x509_crt_get_fingerprint(*pCert, GNUTLS_DIG_SHA1, fingerprint, &size));
1049 CHKgnutls(gnutls_x509_crt_get_fingerprint(*pCert, GNUTLS_DIG_SHA256, fingerprintSha256, &sizeSha256));
1050 CHKiRet(GenFingerprintStr(fingerprint, size, &pstrFingerprint, "SHA1"));
1051 CHKiRet(GenFingerprintStr(fingerprintSha256, sizeSha256, &pstrFingerprintSha256, "SHA256"));
1052 dbgprintf("peer's certificate SHA1 fingerprint: %s\n", cstrGetSzStrNoNULL(pstrFingerprint));
1053 dbgprintf("peer's certificate SHA256 fingerprint: %s\n", cstrGetSzStrNoNULL(pstrFingerprintSha256));
1054
1055
1056 /* now search through the permitted peers to see if we can find a permitted one */
1057 bFoundPositiveMatch = 0;
1058 pPeer = pThis->pPermPeers;
1059 while (pPeer != NULL && !bFoundPositiveMatch) {
1060 if (!rsCStrSzStrCmp(pstrFingerprint, pPeer->pszID, strlen((char *)pPeer->pszID))) {
1061 dbgprintf("gtlsChkPeerFingerprint: peer's certificate SHA1 MATCH found: %s\n", pPeer->pszID);
1062 bFoundPositiveMatch = 1;
1063 } else if (!rsCStrSzStrCmp(pstrFingerprintSha256, pPeer->pszID, strlen((char *)pPeer->pszID))) {
1064 dbgprintf("gtlsChkPeerFingerprint: peer's certificate SHA256 MATCH found: %s\n", pPeer->pszID);
1065 bFoundPositiveMatch = 1;
1066 } else {
1067 pPeer = pPeer->pNext;
1068 }
1069 }
1070
1071 if (!bFoundPositiveMatch) {
1072 dbgprintf("invalid peer fingerprint, not permitted to talk to it\n");
1073 if (pThis->bReportAuthErr == 1) {
1074 errno = 0;
1075 LogError(0, RS_RET_INVALID_FINGERPRINT,
1076 "error: peer fingerprint '%s' unknown - we are "
1077 "not permitted to talk to it",
1078 cstrGetSzStrNoNULL(pstrFingerprint));
1079 pThis->bReportAuthErr = 0;
1080 }
1081 ABORT_FINALIZE(RS_RET_INVALID_FINGERPRINT);
1082 }
1083
1084 finalize_it:
1085 if (pstrFingerprint != NULL) cstrDestruct(&pstrFingerprint);
1086 if (pstrFingerprintSha256 != NULL) cstrDestruct(&pstrFingerprintSha256);
1087 RETiRet;
1088 }
1089
1090
1091 /* Perform a match on ONE peer name obtained from the certificate. This name
1092 * is checked against the set of configured credentials. *pbFoundPositiveMatch is
1093 * set to 1 if the ID matches. *pbFoundPositiveMatch must have been initialized
1094 * to 0 by the caller (this is a performance enhancement as we expect to be
1095 * called multiple times).
1096 * TODO: implemet wildcards?
1097 * rgerhards, 2008-05-26
1098 */
1099 static rsRetVal gtlsChkOnePeerName(nsd_gtls_t *pThis, uchar *pszPeerID, int *pbFoundPositiveMatch) {
1100 permittedPeers_t *pPeer;
1101 DEFiRet;
1102
1103 ISOBJ_TYPE_assert(pThis, nsd_gtls);
1104 assert(pszPeerID != NULL);
1105 assert(pbFoundPositiveMatch != NULL);
1106
1107 if (pThis->pPermPeers) { /* do we have configured peer IDs? */
1108 pPeer = pThis->pPermPeers;
1109 while (pPeer != NULL) {
1110 CHKiRet(net.PermittedPeerWildcardMatch(pPeer, pszPeerID, pbFoundPositiveMatch));
1111 if (*pbFoundPositiveMatch) break;
1112 pPeer = pPeer->pNext;
1113 }
1114 } else {
1115 /* we do not have configured peer IDs, so we use defaults */
1116 if (pThis->pszConnectHost && !strcmp((char *)pszPeerID, (char *)pThis->pszConnectHost)) {
1117 *pbFoundPositiveMatch = 1;
1118 }
1119 }
1120
1121 finalize_it:
1122 RETiRet;
1123 }
1124
1125
1126 /* Check the peer's ID in name auth mode.
1127 * rgerhards, 2008-05-22
1128 */
1129 static rsRetVal gtlsChkPeerName(nsd_gtls_t *pThis, gnutls_x509_crt_t *pCert) {
1130 uchar lnBuf[256];
1131 char szAltName[1024]; /* this is sufficient for the DNSNAME and IPADDRESS... */
1132 int iAltName;
1133 size_t szAltNameLen;
1134 int bFoundPositiveMatch;
1135 int bHaveSAN = 0;
1136 cstr_t *pStr = NULL;
1137 cstr_t *pstrCN = NULL;
1138 int gnuRet;
1139 DEFiRet;
1140
1141 ISOBJ_TYPE_assert(pThis, nsd_gtls);
1142
1143 bFoundPositiveMatch = 0;
1144 CHKiRet(rsCStrConstruct(&pStr));
1145
1146 /* first search through the dNSName subject alt names */
1147 iAltName = 0;
1148 while (!bFoundPositiveMatch) { /* loop broken below */
1149 szAltNameLen = sizeof(szAltName);
1150 gnuRet = gnutls_x509_crt_get_subject_alt_name(*pCert, iAltName, szAltName, &szAltNameLen, NULL);
1151 if (gnuRet < 0)
1152 break;
1153 else if (gnuRet == GNUTLS_SAN_DNSNAME) {
1154 bHaveSAN = 1;
1155 dbgprintf("subject alt dnsName: '%s'\n", szAltName);
1156 snprintf((char *)lnBuf, sizeof(lnBuf), "DNSname: %s; ", szAltName);
1157 CHKiRet(rsCStrAppendStr(pStr, lnBuf));
1158 CHKiRet(gtlsChkOnePeerName(pThis, (uchar *)szAltName, &bFoundPositiveMatch));
1159 /* do NOT break, because there may be multiple dNSName's! */
1160 } else if (gnuRet == GNUTLS_SAN_IPADDRESS) {
1161 bHaveSAN = 1;
1162 char ipAddress[INET6_ADDRSTRLEN];
1163 inet_ntop(((szAltNameLen == sizeof(struct in6_addr)) ? AF_INET6 : AF_INET), szAltName, ipAddress,
1164 INET6_ADDRSTRLEN);
1165 dbgprintf("subject alt ipAddr: '%s'\n", ipAddress);
1166 snprintf((char *)lnBuf, sizeof(lnBuf), "IPaddress: %s; ", ipAddress);
1167 CHKiRet(rsCStrAppendStr(pStr, lnBuf));
1168 CHKiRet(gtlsChkOnePeerName(pThis, (uchar *)ipAddress, &bFoundPositiveMatch));
1169 /* do NOT break, because there may be multiple ipAddr's! */
1170 }
1171 ++iAltName;
1172 }
1173
1174 /* Check also CN only if not configured per stricter RFC 6125 or no SAN present*/
1175 if (!bFoundPositiveMatch && (!pThis->bSANpriority || !bHaveSAN)) {
1176 CHKiRet(gtlsGetCN(pCert, &pstrCN));
1177 if (pstrCN != NULL) { /* NULL if there was no CN present */
1178 dbgprintf("gtls now checking auth for CN '%s'\n", cstrGetSzStrNoNULL(pstrCN));
1179 snprintf((char *)lnBuf, sizeof(lnBuf), "CN: %s; ", cstrGetSzStrNoNULL(pstrCN));
1180 CHKiRet(rsCStrAppendStr(pStr, lnBuf));
1181 CHKiRet(gtlsChkOnePeerName(pThis, cstrGetSzStrNoNULL(pstrCN), &bFoundPositiveMatch));
1182 }
1183 }
1184
1185 if (!bFoundPositiveMatch) {
1186 dbgprintf("invalid peer name, not permitted to talk to it\n");
1187 if (pThis->bReportAuthErr == 1) {
1188 cstrFinalize(pStr);
1189 errno = 0;
1190 LogError(0, RS_RET_INVALID_FINGERPRINT,
1191 "error: peer name not authorized - "
1192 "not permitted to talk to it. Names: %s",
1193 cstrGetSzStrNoNULL(pStr));
1194 pThis->bReportAuthErr = 0;
1195 }
1196 ABORT_FINALIZE(RS_RET_INVALID_FINGERPRINT);
1197 }
1198
1199 finalize_it:
1200 if (pStr != NULL) rsCStrDestruct(&pStr);
1201 if (pstrCN != NULL) rsCStrDestruct(&pstrCN);
1202 RETiRet;
1203 }
1204
1205
1206 /* check the ID of the remote peer - used for both fingerprint and
1207 * name authentication. This is common code. Will call into specific
1208 * drivers once the certificate has been obtained.
1209 * rgerhards, 2008-05-08
1210 */
1211 static rsRetVal gtlsChkPeerID(nsd_gtls_t *pThis) {
1212 const gnutls_datum_t *cert_list;
1213 unsigned int list_size = 0;
1214 gnutls_x509_crt_t cert;
1215 int bMustDeinitCert = 0;
1216 int gnuRet;
1217 DEFiRet;
1218
1219 ISOBJ_TYPE_assert(pThis, nsd_gtls);
1220
1221 /* This function only works for X.509 certificates. */
1222 if (gnutls_certificate_type_get(pThis->sess) != GNUTLS_CRT_X509) return RS_RET_TLS_CERT_ERR;
1223
1224 cert_list = gnutls_certificate_get_peers(pThis->sess, &list_size);
1225
1226 if (list_size < 1) {
1227 if (pThis->bReportAuthErr == 1) {
1228 uchar *fromHost = NULL;
1229 errno = 0;
1230 pThis->bReportAuthErr = 0;
1231 nsd_ptcp.GetRemoteHName((nsd_t *)pThis->pTcp, &fromHost);
1232 LogError(0, RS_RET_TLS_NO_CERT,
1233 "error: peer %s did not provide a certificate, "
1234 "not permitted to talk to it",
1235 fromHost);
1236 free(fromHost);
1237 }
1238 ABORT_FINALIZE(RS_RET_TLS_NO_CERT);
1239 }
1240
1241 /* If we reach this point, we have at least one valid certificate.
1242 * We always use only the first certificate. As of GnuTLS documentation, the
1243 * first certificate always contains the remote peer's own certificate. All other
1244 * certificates are issuer's certificates (up the chain). We are only interested
1245 * in the first certificate, which is our peer. -- rgerhards, 2008-05-08
1246 */
1247 CHKgnutls(gnutls_x509_crt_init(&cert));
1248 bMustDeinitCert = 1; /* indicate cert is initialized and must be freed on exit */
1249 CHKgnutls(gnutls_x509_crt_import(cert, &cert_list[0], GNUTLS_X509_FMT_DER));
1250
1251 /* Now we see which actual authentication code we must call. */
1252 if (pThis->authMode == GTLS_AUTH_CERTFINGERPRINT) {
1253 CHKiRet(gtlsChkPeerFingerprint(pThis, &cert));
1254 } else {
1255 assert(pThis->authMode == GTLS_AUTH_CERTNAME);
1256 CHKiRet(gtlsChkPeerName(pThis, &cert));
1257 }
1258
1259 finalize_it:
1260 if (bMustDeinitCert) gnutls_x509_crt_deinit(cert);
1261
1262 RETiRet;
1263 }
1264
1265
1266 /* Verify the validity of the remote peer's certificate.
1267 * rgerhards, 2008-05-21
1268 */
1269 static rsRetVal gtlsChkPeerCertValidity(nsd_gtls_t *pThis) {
1270 DEFiRet;
1271 const char *pszErrCause;
1272 int gnuRet;
1273 cstr_t *pStr = NULL;
1274 unsigned stateCert;
1275 const gnutls_datum_t *cert_list;
1276 unsigned cert_list_size = 0;
1277 gnutls_x509_crt_t cert;
1278 unsigned i;
1279 time_t ttCert;
1280 time_t ttNow;
1281 sbool bAbort = RSFALSE;
1282 int iAbortCode = RS_RET_OK;
1283
1284 ISOBJ_TYPE_assert(pThis, nsd_gtls);
1285
1286 /* check if we have at least one cert */
1287 cert_list = gnutls_certificate_get_peers(pThis->sess, &cert_list_size);
1288 if (cert_list_size < 1) {
1289 errno = 0;
1290 uchar *fromHost = NULL;
1291 nsd_ptcp.GetRemoteHName((nsd_t *)pThis->pTcp, &fromHost);
1292 LogError(0, RS_RET_TLS_NO_CERT, "peer %s did not provide a certificate, not permitted to talk to it", fromHost);
1293 free(fromHost);
1294 ABORT_FINALIZE(RS_RET_TLS_NO_CERT);
1295 }
1296 #ifdef EXTENDED_CERT_CHECK_AVAILABLE
1297 if (pThis->dataTypeCheck == GTLS_NONE) {
1298 #endif
1299 CHKgnutls(gnutls_certificate_verify_peers2(pThis->sess, &stateCert));
1300 #ifdef EXTENDED_CERT_CHECK_AVAILABLE
1301 } else { /* we have configured data to check in addition to cert */
1302 gnutls_typed_vdata_st data;
1303 data.type = GNUTLS_DT_KEY_PURPOSE_OID;
1304 if (pThis->bIsInitiator) { /* client mode */
1305 data.data = (uchar *)GNUTLS_KP_TLS_WWW_SERVER;
1306 } else { /* server mode */
1307 data.data = (uchar *)GNUTLS_KP_TLS_WWW_CLIENT;
1308 }
1309 data.size = ustrlen(data.data);
1310 CHKgnutls(gnutls_certificate_verify_peers(pThis->sess, &data, 1, &stateCert));
1311 }
1312 #endif
1313
1314 if (stateCert & GNUTLS_CERT_INVALID) {
1315 /* Default abort code */
1316 iAbortCode = RS_RET_CERT_INVALID;
1317
1318 /* provide error details if we have them */
1319 if (stateCert & GNUTLS_CERT_EXPIRED) {
1320 dbgprintf("GnuTLS returned GNUTLS_CERT_EXPIRED, handling mode %d ...\n", pThis->permitExpiredCerts);
1321 /* Handle expired certs */
1322 if (pThis->permitExpiredCerts == GTLS_EXPIRED_DENY) {
1323 bAbort = RSTRUE;
1324 iAbortCode = RS_RET_CERT_EXPIRED;
1325 } else if (pThis->permitExpiredCerts == GTLS_EXPIRED_WARN) {
1326 LogMsg(0, RS_RET_NO_ERRCODE, LOG_WARNING,
1327 "Warning, certificate expired but expired certs are permitted");
1328 } else {
1329 dbgprintf("GnuTLS returned GNUTLS_CERT_EXPIRED, but expired certs are permitted.\n");
1330 }
1331 pszErrCause = "certificate expired";
1332 } else if (stateCert & GNUTLS_CERT_SIGNER_NOT_FOUND) {
1333 pszErrCause = "signer not found";
1334 bAbort = RSTRUE;
1335 } else if (stateCert & GNUTLS_CERT_SIGNER_NOT_CA) {
1336 pszErrCause = "signer is not a CA";
1337 bAbort = RSTRUE;
1338 } else if (stateCert & GNUTLS_CERT_INSECURE_ALGORITHM) {
1339 pszErrCause = "insecure algorithm";
1340 bAbort = RSTRUE;
1341 } else if (stateCert & GNUTLS_CERT_REVOKED) {
1342 pszErrCause = "certificate revoked";
1343 bAbort = RSTRUE;
1344 iAbortCode = RS_RET_CERT_REVOKED;
1345 #ifdef EXTENDED_CERT_CHECK_AVAILABLE
1346 } else if (stateCert & GNUTLS_CERT_PURPOSE_MISMATCH) {
1347 pszErrCause = "key purpose OID does not match";
1348 bAbort = RSTRUE;
1349 #endif
1350 } else {
1351 pszErrCause = "GnuTLS returned no specific reason";
1352 dbgprintf(
1353 "GnuTLS returned no specific reason for GNUTLS_CERT_INVALID, certificate "
1354 "status is %d\n",
1355 stateCert);
1356 bAbort = RSTRUE;
1357 }
1358 }
1359
1360 if (bAbort == RSTRUE) {
1361 uchar *fromHost = NULL;
1362 nsd_ptcp.GetRemoteHName((nsd_t *)pThis->pTcp, &fromHost);
1363 LogError(0, NO_ERRCODE, "not permitted to talk to peer '%s', certificate invalid: %s", fromHost, pszErrCause);
1364 free(fromHost);
1365 gtlsGetCertInfo(pThis, &pStr);
1366 LogError(0, NO_ERRCODE, "invalid cert info: %s", cstrGetSzStrNoNULL(pStr));
1367 cstrDestruct(&pStr);
1368 ABORT_FINALIZE(iAbortCode);
1369 }
1370
1371 /* get current time for certificate validation */
1372 if (datetime.GetTime(&ttNow) == -1) ABORT_FINALIZE(RS_RET_SYS_ERR);
1373
1374 /* as it looks, we need to validate the expiration dates ourselves...
1375 * We need to loop through all certificates as we need to make sure the
1376 * interim certificates are also not expired.
1377 */
1378 for (i = 0; i < cert_list_size; ++i) {
1379 CHKgnutls(gnutls_x509_crt_init(&cert));
1380 CHKgnutls(gnutls_x509_crt_import(cert, &cert_list[i], GNUTLS_X509_FMT_DER));
1381 ttCert = gnutls_x509_crt_get_activation_time(cert);
1382 if (ttCert == -1)
1383 ABORT_FINALIZE(RS_RET_TLS_CERT_ERR);
1384 else if (ttCert > ttNow) {
1385 uchar *fromHost = NULL;
1386 nsd_ptcp.GetRemoteHName((nsd_t *)pThis->pTcp, &fromHost);
1387 LogError(0, RS_RET_CERT_NOT_YET_ACTIVE,
1388 "not permitted to talk to peer '%s': "
1389 "certificate %d not yet active",
1390 fromHost, i);
1391 free(fromHost);
1392 gtlsGetCertInfo(pThis, &pStr);
1393 LogError(0, RS_RET_CERT_NOT_YET_ACTIVE, "invalid cert info: %s", cstrGetSzStrNoNULL(pStr));
1394 cstrDestruct(&pStr);
1395 ABORT_FINALIZE(RS_RET_CERT_NOT_YET_ACTIVE);
1396 }
1397
1398 gnutls_x509_crt_deinit(cert);
1399 }
1400
1401 finalize_it:
1402 RETiRet;
1403 }
1404
1405
1406 /* Check if the cached CRL has expired since startup.
1407 * Called on each TLS handshake to match OpenSSL behavior.
1408 */
1409 static rsRetVal gtlsChkCrlValidity(nsd_gtls_t *pThis) {
1410 DEFiRet;
1411 if (pThis->crlNextUpdate > 0 && time(NULL) > pThis->crlNextUpdate) {
1412 uchar *fromHost = NULL;
1413 nsd_ptcp.GetRemoteHName((nsd_t *)pThis->pTcp, &fromHost);
1414 LogError(0, RS_RET_CRL_INVALID, "CRL has expired (nextUpdate passed), rejecting peer '%s'", fromHost);
1415 free(fromHost);
1416 ABORT_FINALIZE(RS_RET_CRL_INVALID);
1417 }
1418 finalize_it:
1419 RETiRet;
1420 }
1421
1422
1423 /* check if it is OK to talk to the remote peer
1424 * rgerhards, 2008-05-21
1425 */
1426 rsRetVal gtlsChkPeerAuth(nsd_gtls_t *pThis) {
1427 DEFiRet;
1428
1429 ISOBJ_TYPE_assert(pThis, nsd_gtls);
1430
1431 CHKiRet(gtlsChkCrlValidity(pThis));
1432
1433 /* call the actual function based on current auth mode */
1434 switch (pThis->authMode) {
1435 case GTLS_AUTH_CERTNAME:
1436 /* if we check the name, we must ensure the cert is valid */
1437 CHKiRet(gtlsChkPeerCertValidity(pThis));
1438 CHKiRet(gtlsChkPeerID(pThis));
1439 break;
1440 case GTLS_AUTH_CERTFINGERPRINT:
1441 CHKiRet(gtlsChkPeerID(pThis));
1442 break;
1443 case GTLS_AUTH_CERTVALID:
1444 CHKiRet(gtlsChkPeerCertValidity(pThis));
1445 break;
1446 case GTLS_AUTH_CERTANON:
1447 FINALIZE;
1448 break;
1449 default:
1450 // No action needed for other cases
1451 break;
1452 }
1453
1454 finalize_it:
1455 RETiRet;
1456 }
1457
1458
1459 /* globally de-initialize GnuTLS */
1460 static rsRetVal gtlsGlblExit(void) {
1461 DEFiRet;
1462 gnutls_anon_free_server_credentials(anoncredSrv);
1463 gnutls_dh_params_deinit(dh_params);
1464 gnutls_global_deinit();
1465 RETiRet;
1466 }
1467
1468
1469 /* end a GnuTLS session
1470 * The function checks if we have a session and ends it only if so. So it can
1471 * always be called, even if there currently is no session.
1472 */
1473 static rsRetVal gtlsEndSess(nsd_gtls_t *pThis) {
1474 int gnuRet;
1475 DEFiRet;
1476
1477 if (pThis->bHaveSess) {
1478 if (pThis->bIsInitiator) {
1479 gnuRet = gnutls_bye(pThis->sess, GNUTLS_SHUT_WR);
1480 while (gnuRet == GNUTLS_E_INTERRUPTED || gnuRet == GNUTLS_E_AGAIN) {
1481 gnuRet = gnutls_bye(pThis->sess, GNUTLS_SHUT_WR);
1482 }
1483 }
1484 gnutls_deinit(pThis->sess);
1485 pThis->bHaveSess = 0;
1486 }
1487 RETiRet;
1488 }
1489
1490
1491 /* a small wrapper for gnutls_transport_set_ptr(). The main intension for
1492 * creating this wrapper is to get the annoying "cast to pointer from different
1493 * size" compiler warning just once. There seems to be no way around it, see:
1494 * http://lists.gnu.org/archive/html/help-gnutls/2008-05/msg00000.html
1495 * rgerhards, 2008.05-07
1496 */
1497 #pragma GCC diagnostic ignored "-Wint-to-pointer-cast"
1498 static inline void gtlsSetTransportPtr(nsd_gtls_t *pThis, int sock) {
1499 /* Note: the compiler warning for the next line is OK - see header comment! */
1500 gnutls_transport_set_ptr(pThis->sess, (gnutls_transport_ptr_t)sock);
1501 }
1502 #pragma GCC diagnostic warning "-Wint-to-pointer-cast"
1503
1504 /* ---------------------------- end GnuTLS specifics ---------------------------- */
1505
1506
1507 /* Standard-Constructor */
1508 BEGINobjConstruct(nsd_gtls) /* be sure to specify the object type also in END macro! */
1509 iRet = nsd_ptcp.Construct(&pThis->pTcp);
1510 pThis->bReportAuthErr = 1;
1511 ENDobjConstruct(nsd_gtls)
1512
1513
1514 /* destructor for the nsd_gtls object */
1515 BEGINobjDestruct(nsd_gtls) /* be sure to specify the object type also in END and CODESTART macros! */
1516 CODESTARTobjDestruct(nsd_gtls);
1517 if (pThis->iMode == 1) {
1518 gtlsEndSess(pThis);
1519 }
1520
1521 if (pThis->pTcp != NULL) {
1522 nsd_ptcp.Destruct(&pThis->pTcp);
1523 }
1524
1525 free(pThis->pszConnectHost);
1526 free(pThis->pszRcvBuf);
1527 free((void *)pThis->pszCAFile);
1528 free((void *)pThis->pszCRLFile);
1529 free(pThis->remoteSNI);
1530
1531 if (pThis->bOurCertIsInit)
1532 for (unsigned i = 0; i < pThis->nOurCerts; ++i) {
1533 gnutls_x509_crt_deinit(pThis->pOurCerts[i]);
1534 }
1535 if (pThis->bOurKeyIsInit) gnutls_x509_privkey_deinit(pThis->ourKey);
1536 if (pThis->bHaveSess) gnutls_deinit(pThis->sess);
1537 if (pThis->xcred != NULL &&
1538 (pThis->bIsInitiator || (!pThis->xcred_is_copy && (!pThis->bIsInitiator || pThis->bHaveSess)))) {
1539 gnutls_certificate_free_credentials(pThis->xcred);
1540 free((void *)pThis->pszKeyFile);
1541 free((void *)pThis->pszCertFile);
1542 }
1543 ENDobjDestruct(nsd_gtls)
1544
1545
1546 /* Set the driver mode. For us, this has the following meaning:
1547 * 0 - work in plain tcp mode, without tls (e.g. before a STARTTLS)
1548 * 1 - work in TLS mode
1549 * rgerhards, 2008-04-28
1550 */
1551 static rsRetVal SetMode(nsd_t *const pNsd, const int mode) {
1552 DEFiRet;
1553 nsd_gtls_t *pThis = (nsd_gtls_t *)pNsd;
1554
1555 ISOBJ_TYPE_assert((pThis), nsd_gtls);
1556 dbgprintf("(tls) mode: %d\n", mode);
1557 if (mode != 0 && mode != 1) {
1558 LogError(0, RS_RET_INVALID_DRVR_MODE,
1559 "error: driver mode %d not supported by "
1560 "gtls netstream driver",
1561 mode);
1562 ABORT_FINALIZE(RS_RET_INVALID_DRVR_MODE);
1563 }
1564
1565 pThis->iMode = mode;
1566
1567 finalize_it:
1568 RETiRet;
1569 }
1570
1571 /* Set the authentication mode. For us, the following is supported:
1572 * anon - no certificate checks whatsoever (discouraged, but supported)
1573 * x509/certvalid - (just) check certificate validity
1574 * x509/fingerprint - certificate fingerprint
1575 * x509/name - cerfificate name check
1576 * mode == NULL is valid and defaults to x509/name
1577 * rgerhards, 2008-05-16
1578 */
1579 static rsRetVal SetAuthMode(nsd_t *pNsd, uchar *mode) {
1580 DEFiRet;
1581 nsd_gtls_t *pThis = (nsd_gtls_t *)pNsd;
1582
1583 ISOBJ_TYPE_assert((pThis), nsd_gtls);
1584 if (mode == NULL || !strcasecmp((char *)mode, "x509/name")) {
1585 pThis->authMode = GTLS_AUTH_CERTNAME;
1586 } else if (!strcasecmp((char *)mode, "x509/fingerprint")) {
1587 pThis->authMode = GTLS_AUTH_CERTFINGERPRINT;
1588 } else if (!strcasecmp((char *)mode, "x509/certvalid")) {
1589 pThis->authMode = GTLS_AUTH_CERTVALID;
1590 } else if (!strcasecmp((char *)mode, "anon")) {
1591 pThis->authMode = GTLS_AUTH_CERTANON;
1592 } else {
1593 LogError(0, RS_RET_VALUE_NOT_SUPPORTED,
1594 "error: authentication mode '%s' not supported by "
1595 "gtls netstream driver",
1596 mode);
1597 ABORT_FINALIZE(RS_RET_VALUE_NOT_SUPPORTED);
1598 }
1599
1600 dbgprintf("SetAuthMode to %s\n", (mode != NULL ? (char *)mode : "NULL"));
1601 /* TODO: clear stored IDs! */
1602
1603 finalize_it:
1604 RETiRet;
1605 }
1606
1607
1608 /* Set the PermitExpiredCerts mode. For us, the following is supported:
1609 * on - fail if certificate is expired
1610 * off - ignore expired certificates
1611 * warn - warn if certificate is expired
1612 * alorbach, 2018-12-20
1613 */
1614 static rsRetVal SetPermitExpiredCerts(nsd_t *pNsd, uchar *mode) {
1615 DEFiRet;
1616 nsd_gtls_t *pThis = (nsd_gtls_t *)pNsd;
1617
1618 ISOBJ_TYPE_assert((pThis), nsd_gtls);
1619 /* default is set to off! */
1620 if (mode == NULL || !strcasecmp((char *)mode, "off")) {
1621 pThis->permitExpiredCerts = GTLS_EXPIRED_DENY;
1622 } else if (!strcasecmp((char *)mode, "warn")) {
1623 pThis->permitExpiredCerts = GTLS_EXPIRED_WARN;
1624 } else if (!strcasecmp((char *)mode, "on")) {
1625 pThis->permitExpiredCerts = GTLS_EXPIRED_PERMIT;
1626 } else {
1627 LogError(0, RS_RET_VALUE_NOT_SUPPORTED,
1628 "error: permitexpiredcerts mode '%s' not supported by "
1629 "gtls netstream driver",
1630 mode);
1631 ABORT_FINALIZE(RS_RET_VALUE_NOT_SUPPORTED);
1632 }
1633
1634 dbgprintf("SetPermitExpiredCerts: Set Mode %s/%d\n", (mode != NULL ? (char *)mode : "NULL"),
1635 pThis->permitExpiredCerts);
1636
1637 /* TODO: clear stored IDs! */
1638
1639 finalize_it:
1640 RETiRet;
1641 }
1642
1643
1644 /* Set permitted peers. It is depending on the auth mode if this are
1645 * fingerprints or names. -- rgerhards, 2008-05-19
1646 */
1647 static rsRetVal SetPermPeers(nsd_t *pNsd, permittedPeers_t *pPermPeers) {
1648 DEFiRet;
1649 nsd_gtls_t *pThis = (nsd_gtls_t *)pNsd;
1650
1651 ISOBJ_TYPE_assert((pThis), nsd_gtls);
1652 if (pPermPeers == NULL) FINALIZE;
1653
1654 if (pThis->authMode != GTLS_AUTH_CERTFINGERPRINT && pThis->authMode != GTLS_AUTH_CERTNAME) {
1655 LogError(0, RS_RET_VALUE_NOT_IN_THIS_MODE,
1656 "authentication not supported by "
1657 "gtls netstream driver in the configured authentication mode - ignored");
1658 ABORT_FINALIZE(RS_RET_VALUE_NOT_IN_THIS_MODE);
1659 }
1660
1661 pThis->pPermPeers = pPermPeers;
1662
1663 finalize_it:
1664 RETiRet;
1665 }
1666
1667 /* gnutls priority string
1668 * PascalWithopf 2017-08-16
1669 */
1670 static rsRetVal SetGnutlsPriorityString(nsd_t *pNsd, uchar *gnutlsPriorityString) {
1671 DEFiRet;
1672 nsd_gtls_t *pThis = (nsd_gtls_t *)pNsd;
1673
1674 ISOBJ_TYPE_assert((pThis), nsd_gtls);
1675 pThis->gnutlsPriorityString = gnutlsPriorityString;
1676 dbgprintf("gnutlsPriorityString: set to '%s'\n",
1677 (gnutlsPriorityString != NULL ? (char *)gnutlsPriorityString : "NULL"));
1678 RETiRet;
1679 }
1680
1681 /* Set the driver cert extended key usage check setting
1682 * 0 - ignore contents of extended key usage
1683 * 1 - verify that cert contents is compatible with appropriate OID
1684 * jvymazal, 2019-08-16
1685 */
1686 static rsRetVal SetCheckExtendedKeyUsage(nsd_t *pNsd, int ChkExtendedKeyUsage) {
1687 DEFiRet;
1688 nsd_gtls_t *pThis = (nsd_gtls_t *)pNsd;
1689
1690 ISOBJ_TYPE_assert((pThis), nsd_gtls);
1691 if (ChkExtendedKeyUsage != 0 && ChkExtendedKeyUsage != 1) {
1692 LogError(0, RS_RET_VALUE_NOT_SUPPORTED,
1693 "error: driver ChkExtendedKeyUsage %d "
1694 "not supported by gtls netstream driver",
1695 ChkExtendedKeyUsage);
1696 ABORT_FINALIZE(RS_RET_VALUE_NOT_SUPPORTED);
1697 }
1698
1699 pThis->dataTypeCheck = ChkExtendedKeyUsage;
1700
1701 finalize_it:
1702 RETiRet;
1703 }
1704
1705 /* Set the driver name checking strictness
1706 * 0 - less strict per RFC 5280, section 4.1.2.6 - either SAN or CN match is good
1707 * 1 - more strict per RFC 6125 - if any SAN present it must match (CN is ignored)
1708 * jvymazal, 2019-08-16
1709 */
1710 static rsRetVal SetPrioritizeSAN(nsd_t *pNsd, int prioritizeSan) {
1711 DEFiRet;
1712 nsd_gtls_t *pThis = (nsd_gtls_t *)pNsd;
1713
1714 ISOBJ_TYPE_assert((pThis), nsd_gtls);
1715 if (prioritizeSan != 0 && prioritizeSan != 1) {
1716 LogError(0, RS_RET_VALUE_NOT_SUPPORTED,
1717 "error: driver prioritizeSan %d "
1718 "not supported by gtls netstream driver",
1719 prioritizeSan);
1720 ABORT_FINALIZE(RS_RET_VALUE_NOT_SUPPORTED);
1721 }
1722
1723 pThis->bSANpriority = prioritizeSan;
1724
1725 finalize_it:
1726 RETiRet;
1727 }
1728
1729 /* Set the driver tls verifyDepth
1730 * alorbach, 2019-12-20
1731 */
1732 static rsRetVal SetTlsVerifyDepth(nsd_t *pNsd, int verifyDepth) {
1733 DEFiRet;
1734 nsd_gtls_t *pThis = (nsd_gtls_t *)pNsd;
1735
1736 ISOBJ_TYPE_assert((pThis), nsd_gtls);
1737 if (verifyDepth == 0) {
1738 FINALIZE;
1739 }
1740 assert(verifyDepth >= 2);
1741 pThis->DrvrVerifyDepth = verifyDepth;
1742
1743 finalize_it:
1744 RETiRet;
1745 }
1746
1747 static rsRetVal SetTlsCAFile(nsd_t *pNsd, const uchar *const caFile) {
1748 DEFiRet;
1749 nsd_gtls_t *const pThis = (nsd_gtls_t *)pNsd;
1750
1751 ISOBJ_TYPE_assert((pThis), nsd_gtls);
1752 if (caFile == NULL) {
1753 pThis->pszCAFile = NULL;
1754 } else {
1755 CHKmalloc(pThis->pszCAFile = (const uchar *)strdup((const char *)caFile));
1756 }
1757
1758 finalize_it:
1759 RETiRet;
1760 }
1761
1762 static rsRetVal SetTlsCRLFile(nsd_t *pNsd, const uchar *const crlFile) {
1763 DEFiRet;
1764 nsd_gtls_t *const pThis = (nsd_gtls_t *)pNsd;
1765
1766 ISOBJ_TYPE_assert((pThis), nsd_gtls);
1767 if (crlFile == NULL) {
1768 pThis->pszCRLFile = NULL;
1769 } else {
1770 CHKmalloc(pThis->pszCRLFile = (const uchar *)strdup((const char *)crlFile));
1771 }
1772
1773 finalize_it:
1774 RETiRet;
1775 }
1776
1777 static rsRetVal SetTlsKeyFile(nsd_t *pNsd, const uchar *const pszFile) {
1778 DEFiRet;
1779 nsd_gtls_t *const pThis = (nsd_gtls_t *)pNsd;
1780
1781 ISOBJ_TYPE_assert((pThis), nsd_gtls);
1782 if (pszFile == NULL) {
1783 pThis->pszKeyFile = NULL;
1784 } else {
1785 CHKmalloc(pThis->pszKeyFile = (const uchar *)strdup((const char *)pszFile));
1786 }
1787
1788 finalize_it:
1789 RETiRet;
1790 }
1791
1792 static rsRetVal SetTlsCertFile(nsd_t *pNsd, const uchar *const pszFile) {
1793 DEFiRet;
1794 nsd_gtls_t *const pThis = (nsd_gtls_t *)pNsd;
1795
1796 ISOBJ_TYPE_assert((pThis), nsd_gtls);
1797 if (pszFile == NULL) {
1798 pThis->pszCertFile = NULL;
1799 } else {
1800 CHKmalloc(pThis->pszCertFile = (const uchar *)strdup((const char *)pszFile));
1801 }
1802
1803 finalize_it:
1804 RETiRet;
1805 }
1806
1807 /* Set the TLS SNI of the remote server */
1808 static rsRetVal SetRemoteSNI(nsd_t *pNsd, uchar *remoteSNI) {
1809 DEFiRet;
1810 nsd_gtls_t *pThis = (nsd_gtls_t *)pNsd;
1811
1812 ISOBJ_TYPE_assert((pThis), nsd_gtls);
1813
1814 free(pThis->remoteSNI);
1815 if (remoteSNI == NULL) {
1816 pThis->remoteSNI = NULL;
1817 } else {
1818 CHKmalloc(pThis->remoteSNI = (uchar *)strdup((char *)remoteSNI));
1819 }
1820
1821 finalize_it:
1822 RETiRet;
1823 }
1824
1825 static rsRetVal SetTlsRevocationCheck(nsd_t *pNsd, int enabled) {
1826 DEFiRet;
1827 nsd_gtls_t *pThis = (nsd_gtls_t *)pNsd;
1828
1829 ISOBJ_TYPE_assert(pThis, nsd_gtls);
1830 pThis->DrvrTlsRevocationCheck = (enabled != 0) ? 1 : 0;
1831
1832 if (pThis->DrvrTlsRevocationCheck) {
1833 LogError(0, RS_RET_VALUE_NOT_SUPPORTED,
1834 "error: TLS revocation checking not supported by "
1835 "gtls netstream driver (GnuTLS does not implement OCSP checking)");
1836 ABORT_FINALIZE(RS_RET_VALUE_NOT_SUPPORTED);
1837 }
1838
1839 finalize_it:
1840 RETiRet;
1841 }
1842
1843 /* Provide access to the underlying OS socket. This is primarily
1844 * useful for other drivers (like nsd_gtls) who utilize ourselfs
1845 * for some of their functionality. -- rgerhards, 2008-04-18
1846 */
1847 static rsRetVal SetSock(nsd_t *pNsd, int sock) {
1848 DEFiRet;
1849 nsd_gtls_t *pThis = (nsd_gtls_t *)pNsd;
1850
1851 ISOBJ_TYPE_assert((pThis), nsd_gtls);
1852 assert(sock >= 0);
1853
1854 nsd_ptcp.SetSock(pThis->pTcp, sock);
1855
1856 RETiRet;
1857 }
1858
1859 static rsRetVal GetRemotePort(nsd_t *pNsd, int *port) {
1860 nsd_gtls_t *pThis = (nsd_gtls_t *)pNsd;
1861 ISOBJ_TYPE_assert((pThis), nsd_gtls);
1862 return nsd_ptcp.GetRemotePort(pThis->pTcp, port);
1863 }
1864
1865 static rsRetVal FmtRemotePortStr(const int port, uchar *const buf, const size_t len) {
1866 return nsd_ptcp.FmtRemotePortStr(port, buf, len);
1867 }
1868
1869
1870 /* Keep Alive Options
1871 */
1872 static rsRetVal SetKeepAliveIntvl(nsd_t *pNsd, int keepAliveIntvl) {
1873 DEFiRet;
1874 nsd_gtls_t *pThis = (nsd_gtls_t *)pNsd;
1875
1876 ISOBJ_TYPE_assert((pThis), nsd_gtls);
1877 assert(keepAliveIntvl >= 0);
1878
1879 nsd_ptcp.SetKeepAliveIntvl(pThis->pTcp, keepAliveIntvl);
1880
1881 RETiRet;
1882 }
1883
1884
1885 /* Keep Alive Options
1886 */
1887 static rsRetVal SetKeepAliveProbes(nsd_t *pNsd, int keepAliveProbes) {
1888 DEFiRet;
1889 nsd_gtls_t *pThis = (nsd_gtls_t *)pNsd;
1890
1891 ISOBJ_TYPE_assert((pThis), nsd_gtls);
1892 assert(keepAliveProbes >= 0);
1893
1894 nsd_ptcp.SetKeepAliveProbes(pThis->pTcp, keepAliveProbes);
1895
1896 RETiRet;
1897 }
1898
1899
1900 /* Keep Alive Options
1901 */
1902 static rsRetVal SetKeepAliveTime(nsd_t *pNsd, int keepAliveTime) {
1903 DEFiRet;
1904 nsd_gtls_t *pThis = (nsd_gtls_t *)pNsd;
1905
1906 ISOBJ_TYPE_assert((pThis), nsd_gtls);
1907 assert(keepAliveTime >= 0);
1908
1909 nsd_ptcp.SetKeepAliveTime(pThis->pTcp, keepAliveTime);
1910
1911 RETiRet;
1912 }
1913
1914
1915 /* abort a connection. This is meant to be called immediately
1916 * before the Destruct call. -- rgerhards, 2008-03-24
1917 */
1918 static rsRetVal Abort(nsd_t *pNsd) {
1919 nsd_gtls_t *pThis = (nsd_gtls_t *)pNsd;
1920 DEFiRet;
1921
1922 ISOBJ_TYPE_assert((pThis), nsd_gtls);
1923
1924 if (pThis->iMode == 0) {
1925 nsd_ptcp.Abort(pThis->pTcp);
1926 }
1927
1928 RETiRet;
1929 }
1930
1931
1932 /* Callback after netstrm obj init in nsd_ptcp - permits us to add some data */
1933 static rsRetVal LstnInitDrvr(netstrm_t *const pThis) {
1934 DEFiRet;
1935 CHKiRet(gtlsInitCred((nsd_gtls_t *)pThis->pDrvrData));
1936 CHKiRet(gtlsAddOurCert((nsd_gtls_t *)pThis->pDrvrData));
1937 finalize_it:
1938 RETiRet;
1939 }
1940
1941
1942 /* initialize the tcp socket for a listner
1943 * Here, we use the ptcp driver - because there is nothing special
1944 * at this point with GnuTLS. Things become special once we accept
1945 * a session, but not during listener setup.
1946 * gerhards, 2008-04-25
1947 */
1948 static rsRetVal ATTR_NONNULL(1, 3, 5) LstnInit(netstrms_t *pNS,
1949 void *pUsr,
1950 rsRetVal (*fAddLstn)(void *, netstrm_t *),
1951 const int iSessMax,
1952 const tcpLstnParams_t *const cnf_params) {
1953 DEFiRet;
1954 pNS->fLstnInitDrvr = LstnInitDrvr;
1955 iRet = nsd_ptcp.LstnInit(pNS, pUsr, fAddLstn, iSessMax, cnf_params);
1956 // finalize_it:
1957 RETiRet;
1958 }
1959
1960
1961 /* This function checks if the connection is still alive - well, kind of...
1962 * This is a dummy here. For details, check function common in ptcp driver.
1963 * rgerhards, 2008-06-09
1964 */
1965 static rsRetVal CheckConnection(nsd_t __attribute__((unused)) * pNsd) {
1966 nsd_gtls_t *pThis = (nsd_gtls_t *)pNsd;
1967 ISOBJ_TYPE_assert(pThis, nsd_gtls);
1968
1969 dbgprintf("CheckConnection for %p\n", pNsd);
1970 return nsd_ptcp.CheckConnection(pThis->pTcp);
1971 }
1972
1973
1974 /* Provide access to the underlying OS socket.
1975 */
1976 static rsRetVal GetSock(nsd_t *pNsd, int *pSock) {
1977 nsd_gtls_t *pThis = (nsd_gtls_t *)pNsd;
1978 return nsd_ptcp.GetSock(pThis->pTcp, pSock);
1979 }
1980
1981
1982 /* get the remote hostname. The returned hostname must be freed by the caller.
1983 * rgerhards, 2008-04-25
1984 */
1985 static rsRetVal GetRemoteHName(nsd_t *pNsd, uchar **ppszHName) {
1986 DEFiRet;
1987 nsd_gtls_t *pThis = (nsd_gtls_t *)pNsd;
1988 ISOBJ_TYPE_assert(pThis, nsd_gtls);
1989 iRet = nsd_ptcp.GetRemoteHName(pThis->pTcp, ppszHName);
1990 RETiRet;
1991 }
1992
1993
1994 /* Provide access to the sockaddr_storage of the remote peer. This
1995 * is needed by the legacy ACL system. --- gerhards, 2008-12-01
1996 */
1997 static rsRetVal GetRemAddr(nsd_t *pNsd, struct sockaddr_storage **ppAddr) {
1998 DEFiRet;
1999 nsd_gtls_t *pThis = (nsd_gtls_t *)pNsd;
2000 ISOBJ_TYPE_assert(pThis, nsd_gtls);
2001 iRet = nsd_ptcp.GetRemAddr(pThis->pTcp, ppAddr);
2002 RETiRet;
2003 }
2004
2005
2006 /* get the remote host's IP address. Caller must Destruct the object. */
2007 static rsRetVal GetRemoteIP(nsd_t *pNsd, prop_t **ip) {
2008 DEFiRet;
2009 nsd_gtls_t *pThis = (nsd_gtls_t *)pNsd;
2010 ISOBJ_TYPE_assert(pThis, nsd_gtls);
2011 iRet = nsd_ptcp.GetRemoteIP(pThis->pTcp, ip);
2012 RETiRet;
2013 }
2014
2015
2016 /* accept an incoming connection request - here, we do the usual accept
2017 * handling. TLS specific handling is done thereafter (and if we run in TLS
2018 * mode at this time).
2019 * rgerhards, 2008-04-25
2020 */
2021 static rsRetVal AcceptConnReq(nsd_t *pNsd, nsd_t **ppNew, char *const connInfo) {
2022 DEFiRet;
2023 int gnuRet;
2024 nsd_gtls_t *pNew = NULL;
2025 nsd_gtls_t *pThis = (nsd_gtls_t *)pNsd;
2026 const char *error_position = NULL;
2027
2028 ISOBJ_TYPE_assert((pThis), nsd_gtls);
2029 CHKiRet(nsd_gtlsConstruct(&pNew)); // TODO: prevent construct/destruct!
2030 CHKiRet(nsd_ptcp.Destruct(&pNew->pTcp));
2031 CHKiRet(nsd_ptcp.AcceptConnReq(pThis->pTcp, &pNew->pTcp, connInfo));
2032
2033
2034 if (pThis->iMode == 0) {
2035 /* we are in non-TLS mode, so we are done */
2036 *ppNew = (nsd_t *)pNew;
2037 FINALIZE;
2038 }
2039 /* copy Properties to pnew first */
2040 pNew->authMode = pThis->authMode;
2041 pNew->permitExpiredCerts = pThis->permitExpiredCerts;
2042 pNew->pPermPeers = pThis->pPermPeers;
2043 pNew->gnutlsPriorityString = pThis->gnutlsPriorityString;
2044 pNew->DrvrVerifyDepth = pThis->DrvrVerifyDepth;
2045 pNew->DrvrTlsRevocationCheck = pThis->DrvrTlsRevocationCheck;
2046 pNew->crlNextUpdate = pThis->crlNextUpdate;
2047 pNew->dataTypeCheck = pThis->dataTypeCheck;
2048 pNew->bSANpriority = pThis->bSANpriority;
2049 pNew->pszCertFile = pThis->pszCertFile;
2050 pNew->pszKeyFile = pThis->pszKeyFile;
2051 pNew->xcred = pThis->xcred; // TODO: verify once again; xcred is read only at this stage
2052 pNew->xcred_is_copy = 1; // do not free on pNew Destruction
2053
2054 /* if we reach this point, we are in TLS mode */
2055 iRet = gtlsInitSession(pNew);
2056 if (iRet != RS_RET_OK) {
2057 if (iRet == RS_RET_CERTLESS) {
2058 dbgprintf("AcceptConnReq certless mode\n");
2059 /* Set status to OK */
2060 iRet = RS_RET_OK;
2061 } else {
2062 goto finalize_it;
2063 }
2064 }
2065 gtlsSetTransportPtr(pNew, ((nsd_ptcp_t *)(pNew->pTcp))->sock);
2066
2067 dbgprintf("AcceptConnReq bOurCertIsInit=%hu bOurKeyIsInit=%hu \n", pNew->bOurCertIsInit, pNew->bOurKeyIsInit);
2068
2069 /* here is the priorityString set */
2070 if (pNew->gnutlsPriorityString != NULL) {
2071 dbgprintf("AcceptConnReq setting configured priority string (ciphers)\n");
2072 if (gnutls_priority_set_direct(pNew->sess, (const char *)pNew->gnutlsPriorityString, &error_position) ==
2073 GNUTLS_E_INVALID_REQUEST) {
2074 LogError(0, RS_RET_GNUTLS_ERR,
2075 "Syntax error or unsupported option in "
2076 "Priority String near: \"%s\"\n",
2077 error_position);
2078 }
2079 } else {
2080 if (pThis->authMode == GTLS_AUTH_CERTANON) {
2081 /* Allow ANON Ciphers */
2082 dbgprintf("AcceptConnReq setting anon ciphers Try1: %s\n", GTLS_ANON_PRIO_NOTLSV13);
2083 if (gnutls_priority_set_direct(pNew->sess, (const char *)GTLS_ANON_PRIO_NOTLSV13, &error_position) ==
2084 GNUTLS_E_INVALID_REQUEST) {
2085 dbgprintf("AcceptConnReq setting anon ciphers Try2 (TLS1.3 unknown): %s\n", GTLS_ANON_PRIO);
2086 CHKgnutls(gnutls_priority_set_direct(pNew->sess, GTLS_ANON_PRIO, &error_position));
2087 }
2088 /* Uncomment for DEBUG
2089 print_cipher_suite_list("NORMAL:+ANON-DH:+ANON-ECDH:+COMP-ALL"); */
2090 } else {
2091 /* Use default priorities */
2092 dbgprintf("AcceptConnReq setting default ciphers\n");
2093 CHKgnutls(gnutls_set_default_priority(pNew->sess));
2094 }
2095 }
2096
2097 /* we now do the handshake. This is a bit complicated, because we are
2098 * on non-blocking sockets. Usually, the handshake will not complete
2099 * immediately, so that we need to retry it some time later.
2100 */
2101 gnuRet = gnutls_handshake(pNew->sess);
2102 if (gnuRet == GNUTLS_E_AGAIN || gnuRet == GNUTLS_E_INTERRUPTED) {
2103 pNew->rtryCall = gtlsRtry_handshake;
2104 dbgprintf(
2105 "GnuTLS handshake does not complete immediately - "
2106 "setting to retry (this is OK and normal)\n");
2107 } else if (gnuRet == 0) {
2108 /* we got a handshake, now check authorization */
2109 CHKiRet(gtlsChkPeerAuth(pNew));
2110 } else {
2111 uchar *pGnuErr = gtlsStrerror(gnuRet);
2112 uchar *fromHostIP = NULL;
2113 int remotePort;
2114 uchar remotePortStr[8];
2115 nsd_ptcp.GetRemoteHName((nsd_t *)pNew->pTcp, &fromHostIP);
2116 nsd_ptcp.GetRemotePort((nsd_t *)pNew->pTcp, &remotePort);
2117 nsd_ptcp.FmtRemotePortStr(remotePort, remotePortStr, sizeof(remotePortStr));
2118 LogError(0, RS_RET_TLS_HANDSHAKE_ERR,
2119 "nsd_gtls:TLS session terminated with remote client '%s:%s': "
2120 "gnutls returned error on handshake: %s",
2121 fromHostIP, remotePortStr, pGnuErr);
2122 free(fromHostIP);
2123 free(pGnuErr);
2124 ABORT_FINALIZE(RS_RET_TLS_HANDSHAKE_ERR);
2125 }
2126
2127 pNew->iMode = 1; /* this session is now in TLS mode! */
2128
2129 *ppNew = (nsd_t *)pNew;
2130
2131 finalize_it:
2132 if (iRet != RS_RET_OK) {
2133 if (error_position != NULL) {
2134 dbgprintf("AcceptConnReq error_position=%s\n", error_position);
2135 }
2136
2137 if (pNew != NULL) nsd_gtlsDestruct(&pNew);
2138 }
2139 RETiRet;
2140 }
2141
2142
2143 /* receive data from a tcp socket
2144 * The lenBuf parameter must contain the max buffer size on entry and contains
2145 * the number of octets read on exit. This function
2146 * never blocks, not even when called on a blocking socket. That is important
2147 * for client sockets, which are set to block during send, but should not
2148 * block when trying to read data. -- rgerhards, 2008-03-17
2149 * The function now follows the usual iRet calling sequence.
2150 * With GnuTLS, we may need to restart a recv() system call. If so, we need
2151 * to supply the SAME buffer on the retry. We can not assure this, as the
2152 * caller is free to call us with any buffer location (and in current
2153 * implementation, it is on the stack and extremely likely to change). To
2154 * work-around this problem, we allocate a buffer ourselfs and always receive
2155 * into that buffer. We pass data on to the caller only after we have received it.
2156 * To save some space, we allocate that internal buffer only when it is actually
2157 * needed, which means when we reach this function for the first time. To keep
2158 * the algorithm simple, we always supply data only from the internal buffer,
2159 * even if it is a single byte. As we have a stream, the caller must be prepared
2160 * to accept messages in any order, so we do not need to take care about this.
2161 * Please note that the logic also forces us to do some "faking" in select(), as
2162 * we must provide a fake "is ready for readign" status if we have data inside our
2163 * buffer. -- rgerhards, 2008-06-23
2164 */
2165 static rsRetVal Rcv(nsd_t *pNsd, uchar *pBuf, ssize_t *pLenBuf, int *const oserr, unsigned *const nextIODirection) {
2166 DEFiRet;
2167 ssize_t iBytesCopy; /* how many bytes are to be copied to the client buffer? */
2168 nsd_gtls_t *pThis = (nsd_gtls_t *)pNsd;
2169 ISOBJ_TYPE_assert(pThis, nsd_gtls);
2170
2171 if (pThis->bAbortConn) ABORT_FINALIZE(RS_RET_CONNECTION_ABORTREQ);
2172
2173 if (pThis->iMode == 0) {
2174 CHKiRet(nsd_ptcp.Rcv(pThis->pTcp, pBuf, pLenBuf, oserr, nextIODirection));
2175 FINALIZE;
2176 }
2177
2178 /* --- in TLS mode now --- */
2179 if (pThis->rtryCall == gtlsRtry_handshake) {
2180 /* note: we are in receive, so we acually will retry receive in any case */
2181 DBGPRINTF("need to do retry handshake\n");
2182 CHKiRet(doRetry(pThis));
2183 ABORT_FINALIZE(RS_RET_RETRY);
2184 }
2185
2186 /* Buffer logic applies only if we are in TLS mode. Here we
2187 * assume that we will switch from plain to TLS, but never back. This
2188 * assumption may be unsafe, but it is the model for the time being and I
2189 * do not see any valid reason why we should switch back to plain TCP after
2190 * we were in TLS mode. However, in that case we may lose something that
2191 * is already in the receive buffer ... risk accepted. -- rgerhards, 2008-06-23
2192 */
2193
2194 if (pThis->pszRcvBuf == NULL) {
2195 /* we have no buffer, so we need to malloc one */
2196 CHKmalloc(pThis->pszRcvBuf = malloc(NSD_GTLS_MAX_RCVBUF));
2197 pThis->lenRcvBuf = -1;
2198 }
2199
2200 /* now check if we have something in our buffer. If so, we satisfy
2201 * the request from buffer contents.
2202 */
2203 if (pThis->lenRcvBuf == -1) { /* no data present, must read */
2204 CHKiRet(gtlsRecordRecv(pThis, nextIODirection));
2205 }
2206
2207 if (pThis->lenRcvBuf == 0) { /* EOS */
2208 *oserr = errno;
2209 ABORT_FINALIZE(RS_RET_CLOSED);
2210 }
2211
2212 /* if we reach this point, data is present in the buffer and must be copied */
2213 iBytesCopy = pThis->lenRcvBuf - pThis->ptrRcvBuf;
2214 if (iBytesCopy > *pLenBuf) {
2215 iBytesCopy = *pLenBuf;
2216 } else {
2217 pThis->lenRcvBuf = -1; /* buffer will be emptied below */
2218 }
2219
2220 memcpy(pBuf, pThis->pszRcvBuf + pThis->ptrRcvBuf, iBytesCopy);
2221 pThis->ptrRcvBuf += iBytesCopy;
2222 *pLenBuf = iBytesCopy;
2223
2224 finalize_it:
2225 if (iRet != RS_RET_OK && iRet != RS_RET_RETRY) {
2226 /* We need to free the receive buffer in error error case unless a retry is wanted. , if we
2227 * allocated one. -- rgerhards, 2008-12-03 -- moved here by alorbach, 2015-12-01
2228 */
2229 *pLenBuf = 0;
2230 free(pThis->pszRcvBuf);
2231 pThis->pszRcvBuf = NULL;
2232 }
2233 dbgprintf("gtlsRcv return. nsd %p, iRet %d, lenRcvBuf %d, ptrRcvBuf %d\n", pThis, iRet, pThis->lenRcvBuf,
2234 pThis->ptrRcvBuf);
2235 RETiRet;
2236 }
2237
2238
2239 /* send a buffer. On entry, pLenBuf contains the number of octets to
2240 * write. On exit, it contains the number of octets actually written.
2241 * If this number is lower than on entry, only a partial buffer has
2242 * been written.
2243 * rgerhards, 2008-03-19
2244 */
2245 static rsRetVal Send(nsd_t *pNsd, uchar *pBuf, ssize_t *pLenBuf) {
2246 int iSent;
2247 int wantsWriteData = 0;
2248 nsd_gtls_t *pThis = (nsd_gtls_t *)pNsd;
2249 DEFiRet;
2250 ISOBJ_TYPE_assert(pThis, nsd_gtls);
2251
2252 if (pThis->rtryCall == gtlsRtry_recv) {
2253 CHKiRet(doRetry(pThis));
2254 FINALIZE;
2255 }
2256 if (pThis->bAbortConn) ABORT_FINALIZE(RS_RET_CONNECTION_ABORTREQ);
2257
2258 if (pThis->iMode == 0) {
2259 CHKiRet(nsd_ptcp.Send(pThis->pTcp, pBuf, pLenBuf));
2260 FINALIZE;
2261 }
2262
2263 while (1) { /* loop broken inside */
2264 iSent = gnutls_record_send(pThis->sess, pBuf, *pLenBuf);
2265 if (iSent >= 0) {
2266 *pLenBuf = iSent;
2267 break;
2268 }
2269 if (iSent == GNUTLS_E_AGAIN || iSent == GNUTLS_E_INTERRUPTED) {
2270 /*
2271 * GnuTLS may require us to read to make progress (e.g. KeyUpdate).
2272 * If direction is READ, call the buffered recv helper so we do not lose data.
2273 */
2274 if (gnutls_record_get_direction(pThis->sess) == gtlsDir_READ) {
2275 unsigned nextIODirection ATTR_UNUSED;
2276 rsRetVal rcvRet = gtlsRecordRecv(pThis, &nextIODirection);
2277 if (rcvRet == RS_RET_CLOSED || pThis->lenRcvBuf == 0) { /* check for explicit close or 0-byte read */
2278 ABORT_FINALIZE(RS_RET_CLOSED);
2279 } else if (rcvRet != RS_RET_OK && rcvRet != RS_RET_RETRY) {
2280 ABORT_FINALIZE(rcvRet);
2281 }
2282 }
2283 continue; /* retry send */
2284 } else {
2285 /* Check if the underlaying file descriptor needs to read or write data!*/
2286 wantsWriteData = gnutls_record_get_direction(pThis->sess);
2287 uchar *pErr = gtlsStrerror(iSent);
2288 LogError(0, RS_RET_GNUTLS_ERR,
2289 "unexpected GnuTLS error %d, wantsWriteData=%d - this "
2290 "could be caused by a broken connection. GnuTLS reports: %s\n",
2291 iSent, wantsWriteData, pErr);
2292 free(pErr);
2293 gnutls_perror(iSent);
2294 ABORT_FINALIZE(RS_RET_GNUTLS_ERR);
2295 }
2296 }
2297
2298 finalize_it:
2299 RETiRet;
2300 }
2301
2302 /* Enable KEEPALIVE handling on the socket.
2303 * rgerhards, 2009-06-02
2304 */
2305 static rsRetVal EnableKeepAlive(nsd_t *pNsd) {
2306 nsd_gtls_t *pThis = (nsd_gtls_t *)pNsd;
2307 ISOBJ_TYPE_assert(pThis, nsd_gtls);
2308 return nsd_ptcp.EnableKeepAlive(pThis->pTcp);
2309 }
2310
2311
2312 /*
2313 * SNI should not be used if the hostname is a bare IP address
2314 */
2315 static int SetServerNameIfPresent(nsd_gtls_t *pThis, uchar *host) {
2316 struct sockaddr_in sa;
2317 struct sockaddr_in6 sa6;
2318 int inet_pton_ret;
2319
2320 /* Always use the configured remote SNI if present */
2321 if (pThis->remoteSNI != NULL) {
2322 return gnutls_server_name_set(pThis->sess, GNUTLS_NAME_DNS, pThis->remoteSNI, ustrlen(pThis->remoteSNI));
2323 }
2324
2325 inet_pton_ret = inet_pton(AF_INET, CHAR_CONVERT(host), &(sa.sin_addr));
2326
2327 if (inet_pton_ret == 0) { // host wasn't a bare IPv4 address: try IPv6
2328 inet_pton_ret = inet_pton(AF_INET6, CHAR_CONVERT(host), &(sa6.sin6_addr));
2329 }
2330
2331 switch (inet_pton_ret) {
2332 case 1: // host is a valid IP address: don't use SNI
2333 return 0;
2334 case 0: // host isn't a valid IP address: assume it's a domain name, use SNI
2335 return gnutls_server_name_set(pThis->sess, GNUTLS_NAME_DNS, host, ustrlen(host));
2336 default: // unexpected error
2337 return -1;
2338 }
2339 }
2340
2341 /* open a connection to a remote host (server). With GnuTLS, we always
2342 * open a plain tcp socket and then, if in TLS mode, do a handshake on it.
2343 * rgerhards, 2008-03-19
2344 */
2345 #pragma GCC diagnostic push
2346 #pragma GCC diagnostic ignored "-Wdeprecated-declarations" /* TODO: FIX Warnings! */
2347 static rsRetVal Connect(nsd_t *pNsd, int family, uchar *port, uchar *host, char *device) {
2348 nsd_gtls_t *pThis = (nsd_gtls_t *)pNsd;
2349 int sock;
2350 int gnuRet;
2351 const char *error_position;
2352 #ifdef HAVE_GNUTLS_CERTIFICATE_TYPE_SET_PRIORITY
2353 static const int cert_type_priority[2] = {GNUTLS_CRT_X509, 0};
2354 #endif
2355 DEFiRet;
2356 dbgprintf("Connect to %s:%s\n", host, port);
2357
2358 ISOBJ_TYPE_assert(pThis, nsd_gtls);
2359 assert(port != NULL);
2360 assert(host != NULL);
2361
2362 CHKiRet(gtlsInitCred(pThis));
2363 CHKiRet(gtlsAddOurCert(pThis));
2364 CHKiRet(nsd_ptcp.Connect(pThis->pTcp, family, port, host, device));
2365
2366 if (pThis->iMode == 0) FINALIZE;
2367
2368 /* we reach this point if in TLS mode */
2369 CHKgnutls(gnutls_init(&pThis->sess, GNUTLS_CLIENT));
2370 pThis->bHaveSess = 1;
2371 pThis->bIsInitiator = 1;
2372
2373 CHKgnutls(SetServerNameIfPresent(pThis, host));
2374
2375 /* in the client case, we need to set a callback that ensures our certificate
2376 * will be presented to the server even if it is not signed by one of the server's
2377 * trusted roots. This is necessary to support fingerprint authentication.
2378 */
2379 /* store a pointer to ourselfs (needed by callback) */
2380 gnutls_session_set_ptr(pThis->sess, (void *)pThis);
2381 iRet = gtlsLoadOurCertKey(pThis); /* first load .pem files */
2382 if (iRet == RS_RET_OK) {
2383 #if HAVE_GNUTLS_CERTIFICATE_SET_RETRIEVE_FUNCTION
2384 gnutls_certificate_set_retrieve_function(pThis->xcred, gtlsClientCertCallback);
2385 #else
2386 gnutls_certificate_client_set_retrieve_function(pThis->xcred, gtlsClientCertCallback);
2387 #endif
2388 dbgprintf("Connect: enable certificate checking (VerifyDepth=%d)\n", pThis->DrvrVerifyDepth);
2389 if (pThis->DrvrVerifyDepth != 0) {
2390 gnutls_certificate_set_verify_limits(pThis->xcred, 8200, pThis->DrvrVerifyDepth);
2391 }
2392 } else if (iRet == RS_RET_CERTLESS) {
2393 dbgprintf("Connect: certificates not configured, not loaded.\n");
2394 } else {
2395 LogError(0, iRet, "Connect failed to INIT Session %d", gnuRet);
2396 ABORT_FINALIZE(iRet);
2397 ; /* we have an error case! */
2398 }
2399
2400 /*priority string setzen*/
2401 if (pThis->gnutlsPriorityString != NULL) {
2402 dbgprintf("Connect: setting configured priority string (ciphers)\n");
2403 if (gnutls_priority_set_direct(pThis->sess, (const char *)pThis->gnutlsPriorityString, &error_position) ==
2404 GNUTLS_E_INVALID_REQUEST) {
2405 LogError(0, RS_RET_GNUTLS_ERR,
2406 "Syntax error or unsupported option in "
2407 "Priority String near: \"%s\"\n",
2408 error_position);
2409 }
2410 } else {
2411 if (pThis->authMode == GTLS_AUTH_CERTANON || pThis->bOurCertIsInit == 0) {
2412 /* Allow ANON Ciphers */
2413 dbgprintf("Connect: setting anon ciphers Try1: %s\n", GTLS_ANON_PRIO_NOTLSV13);
2414 if (gnutls_priority_set_direct(pThis->sess, (const char *)GTLS_ANON_PRIO_NOTLSV13, &error_position) ==
2415 GNUTLS_E_INVALID_REQUEST) {
2416 dbgprintf("Connect: setting anon ciphers Try2 (TLS1.3 unknown): %s\n", GTLS_ANON_PRIO);
2417 CHKgnutls(gnutls_priority_set_direct(pThis->sess, GTLS_ANON_PRIO, &error_position));
2418 }
2419 /* Uncomment for DEBUG
2420 print_cipher_suite_list("NORMAL:+ANON-DH:+ANON-ECDH:+COMP-ALL"); */
2421 } else {
2422 /* Use default priorities */
2423 dbgprintf("Connect: setting default ciphers\n");
2424 CHKgnutls(gnutls_set_default_priority(pThis->sess));
2425 }
2426 }
2427
2428 #ifdef HAVE_GNUTLS_CERTIFICATE_TYPE_SET_PRIORITY
2429 /* The gnutls_certificate_type_set_priority function is deprecated
2430 * and not available in recent GnuTLS versions. However, there is no
2431 * doc how to properly replace it with gnutls_priority_set_direct.
2432 * A lot of folks have simply removed it, when they also called
2433 * gnutls_set_default_priority. This is what we now also do. If
2434 * this causes problems or someone has an idea of how to replace
2435 * the deprecated function in a better way, please let us know!
2436 * In any case, we use it as long as it is available and let
2437 * not insult us by the deprecation warnings.
2438 * 2015-05-18 rgerhards
2439 */
2440 CHKgnutls(gnutls_certificate_type_set_priority(pThis->sess, cert_type_priority));
2441 #endif
2442
2443 /* put the x509 credentials to the current session */
2444 CHKgnutls(gnutls_credentials_set(pThis->sess, GNUTLS_CRD_CERTIFICATE, pThis->xcred));
2445
2446 /* check for anon authmode */
2447 if (pThis->authMode == GTLS_AUTH_CERTANON) {
2448 dbgprintf("Connect: anon authmode, gnutls_credentials_set GNUTLS_CRD_ANON\n");
2449 CHKgnutls(gnutls_credentials_set(pThis->sess, GNUTLS_CRD_ANON, anoncred));
2450 gnutls_dh_set_prime_bits(pThis->sess, dhMinBits);
2451 }
2452
2453 CHKiRet(nsd_ptcp.GetSock(pThis->pTcp, &sock));
2454
2455 /* assign the socket to GnuTls */
2456 gtlsSetTransportPtr(pThis, sock);
2457
2458
2459 /* we need to store the hostname as an alternate mean of authentication if no
2460 * permitted peer names are given. Using the hostname is quite useful. It permits
2461 * auto-configuration of security if a commen root cert is present. -- rgerhards, 2008-05-26
2462 */
2463 CHKmalloc(pThis->pszConnectHost = (uchar *)strdup((char *)host));
2464
2465 /* and perform the handshake */
2466 gnutls_handshake_set_timeout(pThis->sess, 3000);
2467 CHKgnutls(gnutls_handshake(pThis->sess));
2468 dbgprintf("GnuTLS handshake succeeded\n");
2469
2470 /* now check if the remote peer is permitted to talk to us - ideally, we
2471 * should do this during the handshake, but GnuTLS does not yet provide
2472 * the necessary callbacks -- rgerhards, 2008-05-26
2473 */
2474 CHKiRet(gtlsChkPeerAuth(pThis));
2475
2476 finalize_it:
2477 if (iRet != RS_RET_OK) {
2478 if (pThis->bHaveSess) {
2479 gnutls_deinit(pThis->sess);
2480 pThis->bHaveSess = 0;
2481 /* Free memory using gnutls api first*/
2482 gnutls_certificate_free_credentials(pThis->xcred);
2483 pThis->xcred = NULL;
2484 /* Free other memory */
2485 free(pThis->pszConnectHost);
2486 pThis->pszConnectHost = NULL;
2487 }
2488 }
2489
2490 RETiRet;
2491 }
2492 #pragma GCC diagnostic pop
2493
2494
2495 /* queryInterface function */
2496 BEGINobjQueryInterface(nsd_gtls)
2497 CODESTARTobjQueryInterface(nsd_gtls);
2498 if (pIf->ifVersion != nsdCURR_IF_VERSION) { /* check for current version, increment on each change */
2499 ABORT_FINALIZE(RS_RET_INTERFACE_NOT_SUPPORTED);
2500 }
2501
2502 /* ok, we have the right interface, so let's fill it
2503 * Please note that we may also do some backwards-compatibility
2504 * work here (if we can support an older interface version - that,
2505 * of course, also affects the "if" above).
2506 */
2507 pIf->Construct = (rsRetVal(*)(nsd_t **))nsd_gtlsConstruct;
2508 pIf->Destruct = (rsRetVal(*)(nsd_t **))nsd_gtlsDestruct;
2509 pIf->Abort = Abort;
2510 pIf->LstnInit = LstnInit;
2511 pIf->AcceptConnReq = AcceptConnReq;
2512 pIf->Rcv = Rcv;
2513 pIf->Send = Send;
2514 pIf->Connect = Connect;
2515 pIf->GetSock = GetSock;
2516 pIf->SetSock = SetSock;
2517 pIf->SetMode = SetMode;
2518 pIf->SetAuthMode = SetAuthMode;
2519 pIf->SetPermitExpiredCerts = SetPermitExpiredCerts;
2520 pIf->SetPermPeers = SetPermPeers;
2521 pIf->CheckConnection = CheckConnection;
2522 pIf->GetRemoteHName = GetRemoteHName;
2523 pIf->GetRemoteIP = GetRemoteIP;
2524 pIf->GetRemAddr = GetRemAddr;
2525 pIf->EnableKeepAlive = EnableKeepAlive;
2526 pIf->SetKeepAliveIntvl = SetKeepAliveIntvl;
2527 pIf->SetKeepAliveProbes = SetKeepAliveProbes;
2528 pIf->SetKeepAliveTime = SetKeepAliveTime;
2529 pIf->SetGnutlsPriorityString = SetGnutlsPriorityString;
2530 pIf->SetCheckExtendedKeyUsage = SetCheckExtendedKeyUsage;
2531 pIf->SetPrioritizeSAN = SetPrioritizeSAN;
2532 pIf->SetTlsVerifyDepth = SetTlsVerifyDepth;
2533 pIf->SetTlsCAFile = SetTlsCAFile;
2534 pIf->SetTlsCRLFile = SetTlsCRLFile;
2535 pIf->SetTlsKeyFile = SetTlsKeyFile;
2536 pIf->SetTlsCertFile = SetTlsCertFile;
2537 pIf->GetRemotePort = GetRemotePort;
2538 pIf->FmtRemotePortStr = FmtRemotePortStr;
2539 pIf->SetRemoteSNI = SetRemoteSNI;
2540 pIf->SetTlsRevocationCheck = SetTlsRevocationCheck;
2541
2542 finalize_it:
2543 ENDobjQueryInterface(nsd_gtls)
2544
2545
2546 /* exit our class
2547 */
2548 BEGINObjClassExit(nsd_gtls, OBJ_IS_LOADABLE_MODULE) /* CHANGE class also in END MACRO! */
2549 CODESTARTObjClassExit(nsd_gtls);
2550 gtlsGlblExit(); /* shut down GnuTLS */
2551
2552 /* release objects we no longer need */
2553 objRelease(nsd_ptcp, LM_NSD_PTCP_FILENAME);
2554 objRelease(net, LM_NET_FILENAME);
2555 objRelease(glbl, CORE_COMPONENT);
2556 objRelease(datetime, CORE_COMPONENT);
2557 ENDObjClassExit(nsd_gtls)
2558
2559
2560 /* Initialize the nsd_gtls class. Must be called as the very first method
2561 * before anything else is called inside this class.
2562 * rgerhards, 2008-02-19
2563 */
2564 BEGINObjClassInit(nsd_gtls, 1, OBJ_IS_LOADABLE_MODULE) /* class, version */
2565 /* request objects we use */
2566 CHKiRet(objUse(datetime, CORE_COMPONENT));
2567 CHKiRet(objUse(glbl, CORE_COMPONENT));
2568 CHKiRet(objUse(net, LM_NET_FILENAME));
2569 CHKiRet(objUse(nsd_ptcp, LM_NSD_PTCP_FILENAME));
2570
2571 /* now do global TLS init stuff */
2572 CHKiRet(gtlsGlblInit());
2573 ENDObjClassInit(nsd_gtls)
2574
2575
2576 /* --------------- here now comes the plumbing that makes as a library module --------------- */
2577
2578
2579 BEGINmodExit
2580 CODESTARTmodExit;
2581 nsd_gtlsClassExit();
2582 pthread_mutex_destroy(&mutGtlsStrerror);
2583 ENDmodExit
2584
2585
2586 BEGINqueryEtryPt
2587 CODESTARTqueryEtryPt;
2588 CODEqueryEtryPt_STD_LIB_QUERIES;
2589 ENDqueryEtryPt
2590
2591
2592 BEGINmodInit()
2593 CODESTARTmodInit;
2594 *ipIFVersProvided = CURR_MOD_IF_VERSION; /* we only support the current interface specification */
2595
2596 /* Initialize all classes that are in our module - this includes ourselfs */
2597 CHKiRet(nsd_gtlsClassInit(pModInfo)); /* must be done after tcps_sess, as we use it */
2598
2599 pthread_mutex_init(&mutGtlsStrerror, NULL);
2600 ENDmodInit