1 /*
2 Copyright 2021 Northern.tech AS
3
4 This file is part of CFEngine 3 - written and maintained by Northern.tech AS.
5
6 This program is free software; you can redistribute it and/or modify it
7 under the terms of the GNU General Public License as published by the
8 Free Software Foundation; version 3.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
18
19 To the extent this program is licensed as part of the Enterprise
20 versions of CFEngine, the applicable Commercial Open Source License
21 (COSL) may apply to this file if you as a licensee so wish it. See
22 included file COSL.txt.
23 */
24
25 #include <cf3.defs.h> // CF_DEFAULT_DIGEST
26 #include <cfnet.h>
27
28 #include <openssl/err.h>
29 #include <openssl/crypto.h>
30 #include <openssl/ssl.h>
31
32 #include <logging.h> /* LogLevel */
33 #include <misc_lib.h>
34 #include <string_lib.h>
35
36 /* TODO move crypto.h to libutils */
37 #include <crypto.h> /* HavePublicKeyByIP */
38 #include <hash.h> /* HashPubKey */
39
40 #include <assert.h>
41
42 /* known TLS versions */
43 enum tls_version {
44 TLS_1_0 = 0,
45 TLS_1_1 = 1,
46 TLS_1_2 = 2,
47 TLS_1_3 = 3,
48 };
49 #define TLS_LAST TLS_1_3
50
51 /* determine the highest TLS version supported by the available/used version of
52 * OpenSSL */
53 #if defined(SSL_OP_NO_TLSv1_3)
54 #define TLS_HIGHEST_SUPPORTED TLS_1_3
55 #elif defined(SSL_OP_NO_TLSv1_2)
56 #define TLS_HIGHEST_SUPPORTED TLS_1_2
57 #elif defined(SSL_OP_NO_TLSv1_1)
58 #define TLS_HIGHEST_SUPPORTED TLS_1_1
59 #else
60 #define TLS_HIGHEST_SUPPORTED TLS_1_0
61 #endif
62
63 /* the lowest version of TLS we always require */
64 #define TLS_LOWEST_REQUIRED TLS_1_0
65
66 /* the lowest version of TLS we recommend (also the default) */
67 #define TLS_LOWEST_RECOMMENDED TLS_1_1
68
69 #ifndef SSL_OP_NO_TLSv1_3
70 #define SSL_OP_NO_TLSv1_3 0 /* no-op when ORed with bit flags */
71 #endif
72 #ifndef SSL_OP_NO_TLSv1_2
73 #define SSL_OP_NO_TLSv1_2 0
74 #endif
75 #ifndef SSL_OP_NO_TLSv1_1
76 #define SSL_OP_NO_TLSv1_1 0
77 #endif
78
79 static const char *const tls_version_strings[TLS_LAST + 1] = {"1.0", "1.1", "1.2", "1.3"};
80 static unsigned int tls_disable_flags[TLS_LAST + 1] = {SSL_OP_NO_TLSv1, SSL_OP_NO_TLSv1_1, SSL_OP_NO_TLSv1_2, SSL_OP_NO_TLSv1_3};
81
82 int CONNECTIONINFO_SSL_IDX = -1;
83
84 #define MAX_READ_RETRIES 5
85 #define MAX_WRITE_RETRIES 5
86
TLSErrorString(intmax_t errcode)87 const char *TLSErrorString(intmax_t errcode)
88 {
89 const char *errmsg = ERR_reason_error_string((unsigned long) errcode);
90 return (errmsg != NULL) ? errmsg : "no error message";
91 }
92
TLSGenericInitialize()93 bool TLSGenericInitialize()
94 {
95 static bool is_initialised = false;
96
97 /* We must make sure that SSL_get_ex_new_index() is called only once! */
98 if (is_initialised)
99 {
100 return true;
101 }
102
103 /* OpenSSL is needed for TLS. */
104 SSL_library_init();
105 SSL_load_error_strings();
106
107 /* Register a unique place to store ConnectionInfo within SSL struct. */
108 CONNECTIONINFO_SSL_IDX =
109 SSL_get_ex_new_index(0, "Pointer to ConnectionInfo",
110 NULL, NULL, NULL);
111
112 is_initialised = true;
113 return true;
114 }
115
116 /**
117 * @retval 1 equal
118 * @retval 0 not equal
119 * @retval -1 error
120 */
CompareCertToRSA(X509 * cert,RSA * rsa_key)121 static int CompareCertToRSA(X509 *cert, RSA *rsa_key)
122 {
123 int ret;
124 int retval = -1; /* ERROR */
125
126 EVP_PKEY *cert_pkey = X509_get_pubkey(cert);
127 if (cert_pkey == NULL)
128 {
129 Log(LOG_LEVEL_ERR, "X509_get_pubkey: %s",
130 TLSErrorString(ERR_get_error()));
131 goto ret1;
132 }
133 if (EVP_PKEY_base_id(cert_pkey) != EVP_PKEY_RSA)
134 {
135 Log(LOG_LEVEL_ERR,
136 "Received key of unknown type, only RSA currently supported!");
137 goto ret2;
138 }
139
140 RSA *cert_rsa_key = EVP_PKEY_get1_RSA(cert_pkey);
141 if (cert_rsa_key == NULL)
142 {
143 Log(LOG_LEVEL_ERR, "TLSVerifyPeer: EVP_PKEY_get1_RSA failed!");
144 goto ret2;
145 }
146
147 EVP_PKEY *rsa_pkey = EVP_PKEY_new();
148 if (rsa_pkey == NULL)
149 {
150 Log(LOG_LEVEL_ERR, "TLSVerifyPeer: EVP_PKEY_new allocation failed!");
151 goto ret3;
152 }
153
154 ret = EVP_PKEY_set1_RSA(rsa_pkey, rsa_key);
155 if (ret == 0)
156 {
157 Log(LOG_LEVEL_ERR, "TLSVerifyPeer: EVP_PKEY_set1_RSA failed!");
158 goto ret4;
159 }
160
161 ret = EVP_PKEY_cmp(cert_pkey, rsa_pkey);
162 if (ret == 1)
163 {
164 Log(LOG_LEVEL_DEBUG,
165 "Public key to certificate compare equal");
166 retval = 1; /* EQUAL */
167 }
168 else if (ret == 0 || ret == -1)
169 {
170 Log(LOG_LEVEL_DEBUG,
171 "Public key to certificate compare different");
172 retval = 0; /* NOT EQUAL */
173 }
174 else
175 {
176 Log(LOG_LEVEL_ERR, "OpenSSL EVP_PKEY_cmp: %d %s",
177 ret, TLSErrorString(ERR_get_error()));
178 }
179
180 ret4:
181 EVP_PKEY_free(rsa_pkey);
182 ret3:
183 RSA_free(cert_rsa_key);
184 ret2:
185 EVP_PKEY_free(cert_pkey);
186
187 ret1:
188 return retval;
189 }
190
191 /**
192 * The only thing we make sure here is that any key change is not allowed. All
193 * the rest of authentication happens separately *after* the initial
194 * handshake, thus *after* this callback has returned successfully and TLS
195 * session has been established.
196 * @return 0 on error, 1 on success
197 * @note This is an SSL callback, return type has to be int, not bool
198 */
TLSVerifyCallback(X509_STORE_CTX * store_ctx,void * arg ARG_UNUSED)199 int TLSVerifyCallback(X509_STORE_CTX *store_ctx,
200 void *arg ARG_UNUSED)
201 {
202
203 /* It's kind of tricky to get custom connection-specific info in this
204 * callback. We first acquire a pointer to the SSL struct of the
205 * connection and... */
206 int ssl_idx = SSL_get_ex_data_X509_STORE_CTX_idx();
207 SSL *ssl = X509_STORE_CTX_get_ex_data(store_ctx, ssl_idx);
208 if (ssl == NULL)
209 {
210 UnexpectedError("No SSL context during handshake, denying!");
211 return 0;
212 }
213
214 /* ...and then we ask for the custom data we attached there. */
215 ConnectionInfo *conn_info = SSL_get_ex_data(ssl, CONNECTIONINFO_SSL_IDX);
216 if (conn_info == NULL)
217 {
218 UnexpectedError("No conn_info at index %d", CONNECTIONINFO_SSL_IDX);
219 return 0;
220 }
221
222 /* From that data get the key if the connection is already established. */
223 RSA *already_negotiated_key = KeyRSA(conn_info->remote_key);
224 /* Is there an already negotiated certificate? */
225 X509 *previous_tls_cert = SSL_get_peer_certificate(ssl);
226
227 if (previous_tls_cert == NULL)
228 {
229 Log(LOG_LEVEL_DEBUG, "TLSVerifyCallback: no ssl->peer_cert");
230 if (already_negotiated_key == NULL)
231 {
232 Log(LOG_LEVEL_DEBUG, "TLSVerifyCallback: no conn_info->key");
233 Log(LOG_LEVEL_DEBUG,
234 "This must be the initial TLS handshake, accepting");
235 return 1; /* ACCEPT HANDSHAKE */
236 }
237 else
238 {
239 UnexpectedError("Initial handshake, but old keys differ, denying!");
240 return 0;
241 }
242 }
243 else /* TLS renegotiation handshake */
244 {
245 if (already_negotiated_key == NULL)
246 {
247 Log(LOG_LEVEL_DEBUG, "TLSVerifyCallback: no conn_info->key");
248 Log(LOG_LEVEL_ERR,
249 "Renegotiation handshake before trust was established, denying!");
250 X509_free(previous_tls_cert);
251 return 0; /* fishy */
252 }
253 else
254 {
255 /* previous_tls_cert key should match already_negotiated_key. */
256 if (CompareCertToRSA(previous_tls_cert,
257 already_negotiated_key) != 1)
258 {
259 UnexpectedError("Renegotiation caused keys to differ, denying!");
260 X509_free(previous_tls_cert);
261 return 0;
262 }
263 else
264 {
265 /* THIS IS THE ONLY WAY TO CONTINUE */
266 }
267 }
268 }
269
270 assert(previous_tls_cert != NULL);
271 assert(already_negotiated_key != NULL);
272
273 /* At this point we have ensured that previous_tls_cert->key is equal
274 * to already_negotiated_key, so we might as well forget the former. */
275 X509_free(previous_tls_cert);
276
277 /* We want to compare already_negotiated_key to the one the peer
278 * negotiates in this TLS renegotiation. So, extract first certificate out
279 * of the chain the peer sent. It should be the only one since we do not
280 * support certificate chains, we just want the RSA key. */
281 STACK_OF(X509) *chain = X509_STORE_CTX_get_chain(store_ctx);
282 if (chain == NULL)
283 {
284 Log(LOG_LEVEL_ERR,
285 "No certificate chain inside TLS handshake, denying!");
286 return 0;
287 }
288
289 int chain_len = sk_X509_num(chain);
290 if (chain_len != 1)
291 {
292 Log(LOG_LEVEL_ERR,
293 "More than one certificate presented in TLS handshake, refusing handshake!");
294 return 0;
295 }
296
297 X509 *new_cert = sk_X509_value(chain, 0);
298 if (new_cert == NULL)
299 {
300 UnexpectedError("NULL certificate at the beginning of chain!");
301 return 0;
302 }
303
304 if (CompareCertToRSA(new_cert, already_negotiated_key) != 1)
305 {
306 Log(LOG_LEVEL_ERR,
307 "Peer attempted to change key during TLS renegotiation, denying!");
308 return 0;
309 }
310
311 Log(LOG_LEVEL_DEBUG,
312 "TLS renegotiation occurred but keys are still the same, accepting");
313 return 1; /* ACCEPT HANDSHAKE */
314 }
315
316 /**
317 * @retval 1 if the public key used by the peer in the TLS handshake is the
318 * same with the one stored for that host.
319 * @retval 0 if stored key for the host is missing or differs from the one
320 * received.
321 * @retval -1 in case of other error (error will be Log()ed).
322 * @note When return value is != -1 (so no error occurred) the #conn_info struct
323 * should have been populated, with key received and its hash.
324 */
TLSVerifyPeer(ConnectionInfo * conn_info,const char * remoteip,const char * username)325 int TLSVerifyPeer(ConnectionInfo *conn_info, const char *remoteip, const char *username)
326 {
327 int ret, retval;
328
329 X509 *received_cert = SSL_get_peer_certificate(conn_info->ssl);
330 if (received_cert == NULL)
331 {
332 Log(LOG_LEVEL_ERR,
333 "No certificate presented by remote peer (openssl: %s)",
334 TLSErrorString(ERR_get_error()));
335 retval = -1;
336 goto ret1;
337 }
338
339 EVP_PKEY *received_pubkey = X509_get_pubkey(received_cert);
340 if (received_pubkey == NULL)
341 {
342 Log(LOG_LEVEL_ERR, "X509_get_pubkey: %s",
343 TLSErrorString(ERR_get_error()));
344 retval = -1;
345 goto ret2;
346 }
347 if (EVP_PKEY_base_id(received_pubkey) != EVP_PKEY_RSA)
348 {
349 Log(LOG_LEVEL_ERR,
350 "Received key of unknown type, only RSA currently supported!");
351 retval = -1;
352 goto ret3;
353 }
354
355 RSA *remote_key = EVP_PKEY_get1_RSA(received_pubkey);
356 if (remote_key == NULL)
357 {
358 Log(LOG_LEVEL_ERR, "TLSVerifyPeer: EVP_PKEY_get1_RSA failed!");
359 retval = -1;
360 goto ret3;
361 }
362
363 Key *key = KeyNew(remote_key, CF_DEFAULT_DIGEST);
364 conn_info->remote_key = key;
365
366 /*
367 * Compare the key received with the one stored.
368 */
369 const char *key_hash = KeyPrintableHash(key);
370 RSA *expected_rsa_key = HavePublicKey(username, remoteip, key_hash);
371
372 if (expected_rsa_key == NULL)
373 {
374 /* TODO LOG_LEVEL_NOTICE once cf-serverd logs to a different file. */
375 Log(LOG_LEVEL_VERBOSE,
376 "Received key '%s' not found in ppkeys", key_hash);
377 retval = 0;
378 goto ret4;
379 }
380
381 EVP_PKEY *expected_pubkey = EVP_PKEY_new();
382 if (expected_pubkey == NULL)
383 {
384 Log(LOG_LEVEL_ERR, "TLSVerifyPeer: EVP_PKEY_new allocation failed!");
385 retval = -1;
386 goto ret5;
387 }
388
389 ret = EVP_PKEY_set1_RSA(expected_pubkey, expected_rsa_key);
390 if (ret == 0)
391 {
392 Log(LOG_LEVEL_ERR, "TLSVerifyPeer: EVP_PKEY_set1_RSA failed!");
393 retval = -1;
394 goto ret6;
395 }
396
397 ret = EVP_PKEY_cmp(received_pubkey, expected_pubkey);
398 if (ret == 1)
399 {
400 Log(LOG_LEVEL_VERBOSE,
401 "Received public key compares equal to the one we have stored");
402 retval = 1; /* TRUSTED KEY, equal to the expected one */
403 goto ret6;
404 }
405 else if (ret == 0 || ret == -1)
406 {
407 Log(LOG_LEVEL_NOTICE,
408 "Received key '%s' compares different to the one in ppkeys",
409 key_hash);
410 retval = 0;
411 goto ret6;
412 }
413 else
414 {
415 Log(LOG_LEVEL_ERR, "OpenSSL EVP_PKEY_cmp: %d %s",
416 ret, TLSErrorString(ERR_get_error()));
417 retval = -1;
418 goto ret6;
419 }
420
421 UnexpectedError("Unreachable!");
422 return 0;
423
424 ret6:
425 EVP_PKEY_free(expected_pubkey);
426 ret5:
427 RSA_free(expected_rsa_key);
428 ret4:
429 if (retval == -1)
430 {
431 /* We won't be needing conn_info->remote_key */
432 KeyDestroy(&key);
433 conn_info->remote_key = NULL;
434 }
435 ret3:
436 EVP_PKEY_free(received_pubkey);
437 ret2:
438 X509_free(received_cert);
439 ret1:
440 return retval;
441 }
442
443 /**
444 * @brief Generate and return a dummy in-memory X509 certificate signed with
445 * the private key passed. It is valid from now to 50 years later...
446 */
TLSGenerateCertFromPrivKey(RSA * privkey)447 X509 *TLSGenerateCertFromPrivKey(RSA *privkey)
448 {
449 int ret;
450 X509 *x509 = X509_new();
451 if (x509 == NULL)
452 {
453 Log(LOG_LEVEL_ERR, "X509_new: %s",
454 TLSErrorString(ERR_get_error()));
455 goto err1;
456 }
457
458 ASN1_TIME *t1 = X509_gmtime_adj(X509_get_notBefore(x509), 0);
459 ASN1_TIME *t2 = X509_gmtime_adj(X509_get_notAfter(x509), 60*60*24*365*10);
460 if (t1 == NULL || t2 == NULL)
461 {
462 Log(LOG_LEVEL_ERR, "X509_gmtime_adj: %s",
463 TLSErrorString(ERR_get_error()));
464 goto err2;
465 }
466
467 EVP_PKEY *pkey = EVP_PKEY_new();
468 if (pkey == NULL)
469 {
470 Log(LOG_LEVEL_ERR, "EVP_PKEY_new: %s",
471 TLSErrorString(ERR_get_error()));
472 goto err2;
473 }
474
475 ret = EVP_PKEY_set1_RSA(pkey, privkey);
476 if (ret != 1)
477 {
478 Log(LOG_LEVEL_ERR, "EVP_PKEY_set1_RSA: %s",
479 TLSErrorString(ERR_get_error()));
480 goto err3;
481 }
482
483 X509_NAME *name = X509_get_subject_name(x509);
484 if (name == NULL)
485 {
486 Log(LOG_LEVEL_ERR, "X509_get_subject_name: %s",
487 TLSErrorString(ERR_get_error()));
488 goto err3;
489 }
490
491 ret = 0;
492 ret += X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC,
493 (const unsigned char *) "a",
494 -1, -1, 0);
495 ret += X509_set_issuer_name(x509, name);
496 ret += X509_set_pubkey(x509, pkey);
497 if (ret < 3)
498 {
499 Log(LOG_LEVEL_ERR, "Failed to set certificate details: %s",
500 TLSErrorString(ERR_get_error()));
501 goto err3;
502 }
503
504 const EVP_MD *md = EVP_get_digestbyname("sha384");
505 if (md == NULL)
506 {
507 Log(LOG_LEVEL_ERR, "OpenSSL: Unknown digest algorithm %s",
508 "sha384");
509 goto err3;
510 }
511
512 if (getenv("CFENGINE_TEST_PURIFY_OPENSSL") != NULL)
513 {
514 RSA_blinding_off(privkey);
515 }
516
517 /* Not really needed since the other side does not
518 verify the signature. */
519 ret = X509_sign(x509, pkey, md);
520 /* X509_sign obscurely returns the length of the signature... */
521 if (ret == 0)
522 {
523 Log(LOG_LEVEL_ERR, "X509_sign: %s",
524 TLSErrorString(ERR_get_error()));
525 goto err3;
526 }
527
528 EVP_PKEY_free(pkey);
529
530 assert(x509 != NULL);
531 return x509;
532
533
534 err3:
535 EVP_PKEY_free(pkey);
536 err2:
537 X509_free(x509);
538 err1:
539 return NULL;
540 }
541
TLSPrimarySSLError(int code)542 static const char *TLSPrimarySSLError(int code)
543 {
544 switch (code)
545 {
546 case SSL_ERROR_NONE:
547 return "TLSGetSSLErrorString: No SSL error!";
548 case SSL_ERROR_ZERO_RETURN:
549 return "TLS session has been terminated (SSL_ERROR_ZERO_RETURN)";
550 case SSL_ERROR_WANT_READ:
551 return "SSL_ERROR_WANT_READ";
552 case SSL_ERROR_WANT_WRITE:
553 return "SSL_ERROR_WANT_WRITE";
554 case SSL_ERROR_WANT_CONNECT:
555 return "SSL_ERROR_WANT_CONNECT";
556 case SSL_ERROR_WANT_ACCEPT:
557 return "SSL_ERROR_WANT_ACCEPT";
558 case SSL_ERROR_WANT_X509_LOOKUP:
559 return "SSL_ERROR_WANT_X509_LOOKUP";
560 case SSL_ERROR_SYSCALL:
561 return "SSL_ERROR_SYSCALL";
562 case SSL_ERROR_SSL:
563 return "SSL_ERROR_SSL";
564 }
565 return "Unknown OpenSSL error code!";
566 }
567
568 /**
569 * @brief OpenSSL is missing an SSL_reason_error_string() like
570 * ERR_reason_error_string(). Provide missing functionality here,
571 * since it's kind of complicated.
572 * @param #prepend String to prepend to the SSL error.
573 * @param #code Return code from the OpenSSL function call.
574 * @warning Use only for SSL_connect(), SSL_accept(), SSL_do_handshake(),
575 * SSL_read(), SSL_peek(), SSL_write(), see SSL_get_error man page.
576 */
TLSLogError(SSL * ssl,LogLevel level,const char * prepend,int retcode)577 int TLSLogError(SSL *ssl, LogLevel level, const char *prepend, int retcode)
578 {
579 assert(prepend != NULL);
580
581 /* For when retcode==SSL_ERROR_SYSCALL. */
582 const char *syserr = (errno != 0) ? GetErrorStr() : "";
583 int errcode = SSL_get_error(ssl, retcode);
584 const char *errstr1 = TLSPrimarySSLError(errcode);
585 /* For SSL_ERROR_SSL, SSL_ERROR_SYSCALL (man SSL_get_error). It's not
586 * useful for SSL_read() and SSL_write(). */
587 const char *errstr2 = ERR_reason_error_string(ERR_get_error());
588
589 /* We know the socket is always blocking. However our blocking sockets
590 * have a timeout set via means of setsockopt(SO_RCVTIMEO), so internally
591 * OpenSSL can still get the EWOULDBLOCK error code from recv(). In that
592 * case OpenSSL gives us SSL_ERROR_WANT_READ despite the socket being
593 * blocking. So we log a proper error message! */
594 if (errcode == SSL_ERROR_WANT_READ)
595 {
596 Log(level, "%s: receive timeout", prepend);
597 }
598 else if (errcode == SSL_ERROR_WANT_WRITE)
599 {
600 Log(level, "%s: send timeout", prepend);
601 }
602 /* if we got SSL_ERROR_SYSCALL and ERR_get_error() returned 0 then take
603 * ret into account (man SSL_get_error). */
604 else if (errcode == SSL_ERROR_SYSCALL && errstr2 == NULL &&
605 (retcode == 0 || retcode == -1))
606 {
607 /* This is not described in SSL_get_error manual, but play it safe. */
608 if ((SSL_get_shutdown(ssl) & SSL_RECEIVED_SHUTDOWN) != 0)
609 {
610 Log(level, "%s: remote peer terminated TLS session",
611 prepend);
612 }
613 /* "an EOF was observed that violates the protocol" */
614 else if (retcode == 0)
615 {
616 Log(level, "%s: socket closed", prepend);
617 }
618 /* "the underlying BIO reported an I/O error" */
619 else if (retcode == -1)
620 {
621 Log(level, "%s: underlying network error (%s)", prepend, syserr);
622 }
623 }
624 else /* generic error printing fallback */
625 {
626 Log(level, "%s: (%d %s) %s %s",
627 prepend, retcode, errstr1,
628 (errstr2 == NULL) ? "" : errstr2, /* most likely empty */
629 syserr);
630 }
631
632 return errcode;
633 }
634
assert_SSLIsBlocking(const SSL * ssl)635 static void assert_SSLIsBlocking(const SSL *ssl)
636 {
637 #if !defined(NDEBUG) && !defined(__MINGW32__)
638 int fd = SSL_get_fd(ssl);
639 if (fd >= 0)
640 {
641 int flags = fcntl(fd, F_GETFL, 0);
642 if (flags != -1 && (flags & O_NONBLOCK) != 0)
643 {
644 ProgrammingError("OpenSSL socket is non-blocking!");
645 }
646 }
647 #else // silence compiler warning
648 ssl = NULL;
649 #endif
650 }
651
652 /**
653 * @brief Sends the data stored on the buffer using a TLS session.
654 * @param ssl SSL information.
655 * @param buffer Data to send.
656 * @param length Length of the data to send.
657 * @return The length of the data sent (always equals #length if SSL is set
658 * up correctly, see note), or -1 in case of error, or 0 for connection
659 * closed.
660 *
661 * @note Use only for *blocking* sockets. Set
662 * SSL_CTX_set_mode(SSL_MODE_AUTO_RETRY) and make sure you haven't
663 * turned on SSL_MODE_ENABLE_PARTIAL_WRITE so that either the
664 * operation is completed (retval==length) or an error occurred.
665 *
666 * @TODO ERR_get_error is only meaningful for some error codes, so check and
667 * return empty string otherwise.
668 */
TLSSend(SSL * ssl,const char * buffer,int length)669 int TLSSend(SSL *ssl, const char *buffer, int length)
670 {
671 assert(length >= 0);
672 assert_SSLIsBlocking(ssl);
673
674 if (length == 0)
675 {
676 UnexpectedError("TLSSend: Zero length buffer!");
677 return 0;
678 }
679
680 EnforceBwLimit(length);
681
682 int sent = -1;
683 bool should_retry = true;
684 int remaining_tries = MAX_WRITE_RETRIES;
685 while ((sent < 0) && should_retry)
686 {
687 sent = SSL_write(ssl, buffer, length);
688 if (sent <= 0)
689 {
690 if ((SSL_get_shutdown(ssl) & SSL_RECEIVED_SHUTDOWN) != 0)
691 {
692 Log(LOG_LEVEL_ERR,
693 "Remote peer terminated TLS session (SSL_write)");
694 return 0;
695 }
696
697 /* else */
698 int code = TLSLogError(ssl, LOG_LEVEL_VERBOSE, "SSL write failed", sent);
699 /* If renegotiation happens, SSL_ERROR_WANT_READ or
700 * SSL_ERROR_WANT_WRITE can be reported. See man:SSL_write(3).*/
701 should_retry = ((remaining_tries > 0) &&
702 ((code == SSL_ERROR_WANT_READ) || (code == SSL_ERROR_WANT_WRITE)));
703 }
704 if ((sent < 0) && should_retry)
705 {
706 sleep(1);
707 remaining_tries--;
708 }
709 }
710 if (sent < 0)
711 {
712 TLSLogError(ssl, LOG_LEVEL_ERR, "SSL_write", sent);
713 return -1;
714 }
715
716 return sent;
717 }
718
719 /**
720 * @brief Receives at most #length bytes of data from the SSL session
721 * and stores it in the buffer.
722 * @param ssl SSL information.
723 * @param buffer Buffer, of size at least #toget + 1 to store received data.
724 * @param toget Length of the data to receive, must be < CF_BUFSIZE.
725 *
726 * @return The length of the received data, which should be equal or less
727 * than the requested amount.
728 * -1 in case of timeout or error - SSL session is unusable
729 * 0 if connection was closed
730 *
731 * @note Use only for *blocking* sockets. Set
732 * SSL_CTX_set_mode(SSL_MODE_AUTO_RETRY) to make sure that either
733 * operation completed or an error occurred.
734 * @note Still, it may happen for #retval to be less than #toget, if the
735 * opposite side completed a TLSSend() with number smaller than #toget.
736 */
TLSRecv(SSL * ssl,char * buffer,int toget)737 int TLSRecv(SSL *ssl, char *buffer, int toget)
738 {
739 assert(toget > 0);
740 assert(toget < CF_BUFSIZE);
741 assert_SSLIsBlocking(ssl);
742
743 int received = -1;
744 bool should_retry = true;
745 int remaining_tries = MAX_READ_RETRIES;
746 while ((received < 0) && should_retry)
747 {
748 received = SSL_read(ssl, buffer, toget);
749 if (received < 0)
750 {
751 int code = TLSLogError(ssl, LOG_LEVEL_VERBOSE, "SSL read failed", received);
752 /* SSL_read() might get an internal recv() timeout, since we've set
753 * SO_RCVTIMEO. In that case SSL_read() returns SSL_ERROR_WANT_READ.
754 * Also, if renegotiation happens, SSL_ERROR_WANT_READ or
755 * SSL_ERROR_WANT_WRITE can be reported. See man:SSL_read(3).*/
756 should_retry = ((remaining_tries > 0) &&
757 ((code == SSL_ERROR_WANT_READ) || (code == SSL_ERROR_WANT_WRITE)));
758
759 }
760 if ((received < 0) && should_retry)
761 {
762 sleep(1);
763 remaining_tries--;
764 }
765 }
766
767 if (received < 0)
768 {
769 int errcode = TLSLogError(ssl, LOG_LEVEL_ERR, "SSL read after retries", received);
770 /* if all the retries didn't help, let's at least make sure proper
771 * cleanup is done */
772 if ((errcode == SSL_ERROR_WANT_READ) || (errcode == SSL_ERROR_WANT_WRITE))
773 {
774 /* Make sure that the peer will send us no more data. */
775 SSL_shutdown(ssl);
776 shutdown(SSL_get_fd(ssl), SHUT_RDWR);
777
778 /* Empty possible SSL_read() buffers. */
779 int ret = 1;
780 int bytes_still_buffered = SSL_pending(ssl);
781 while (bytes_still_buffered > 0 && ret > 0)
782 {
783 char tmpbuf[bytes_still_buffered];
784 ret = SSL_read(ssl, tmpbuf, bytes_still_buffered);
785 bytes_still_buffered -= ret;
786 }
787 }
788
789 return -1;
790 }
791 else if (received == 0)
792 {
793 if ((SSL_get_shutdown(ssl) & SSL_RECEIVED_SHUTDOWN) != 0)
794 {
795 Log(LOG_LEVEL_VERBOSE,
796 "Remote peer terminated TLS session (SSL_read)");
797 }
798 else
799 {
800 TLSLogError(ssl, LOG_LEVEL_ERR,
801 "Connection unexpectedly closed (SSL_read)",
802 received);
803 }
804 }
805
806 assert(received < CF_BUFSIZE);
807 buffer[received] = '\0';
808
809 return received;
810 }
811
812 /**
813 * @brief Repeat receiving until last byte received is '\n'.
814 *
815 * @param #buf on return will contain all received lines, and '\0' will be
816 * appended to it.
817 * @return Return value is #buf 's length (excluding manually appended '\0')
818 * or -1 in case of error.
819 *
820 * @note This function is intended for line-oriented communication, this means
821 * the peer sends us one line (or a bunch of lines) and waits for reply,
822 * so that '\n' is the last character in the underlying SSL_read().
823 */
TLSRecvLines(SSL * ssl,char * buf,size_t buf_size)824 int TLSRecvLines(SSL *ssl, char *buf, size_t buf_size)
825 {
826 int ret;
827 size_t got = 0;
828 buf_size -= 1; /* Reserve one space for terminating '\0' */
829
830 /* Repeat until we receive end of line. */
831 do
832 {
833 buf[got] = '\0';
834 ret = TLSRecv(ssl, &buf[got], buf_size - got);
835 if (ret <= 0)
836 {
837 Log(LOG_LEVEL_ERR,
838 "Connection was hung up while receiving line: %s",
839 buf);
840 return -1;
841 }
842 got += ret;
843 } while ((buf[got-1] != '\n') && (got < buf_size));
844 assert(got <= buf_size);
845
846 /* Append '\0', there is room because buf_size has been decremented. */
847 buf[got] = '\0';
848
849 if ((got == buf_size) && (buf[got-1] != '\n'))
850 {
851 Log(LOG_LEVEL_ERR,
852 "Received line too long, hanging up! Length %zu, line: %s",
853 got, buf);
854 return -1;
855 }
856
857 LogRaw(LOG_LEVEL_DEBUG, "TLSRecvLines(): ", buf, got);
858
859 return (got <= INT_MAX) ? (int) got : -1;
860 }
861
862 /**
863 * Set safe OpenSSL defaults commonly used by both clients and servers.
864 *
865 * @param min_version the minimum acceptable TLS version for incoming or
866 * outgoing connections (depending on ssl_ctx), for example
867 * "1", "1.1", "1.2".
868 */
TLSSetDefaultOptions(SSL_CTX * ssl_ctx,const char * min_version)869 void TLSSetDefaultOptions(SSL_CTX *ssl_ctx, const char *min_version)
870 {
871 #if HAVE_DECL_SSL_CTX_CLEAR_OPTIONS
872 /* Clear all flags, we do not want compatibility tradeoffs like
873 * SSL_OP_LEGACY_SERVER_CONNECT. */
874 SSL_CTX_clear_options(ssl_ctx, SSL_CTX_get_options(ssl_ctx));
875 #else
876 /* According to OpenSSL code v.0.9.8m, the first option to be added
877 * by default (SSL_OP_LEGACY_SERVER_CONNECT) was added at the same
878 * time SSL_CTX_clear_options appeared. Therefore, it is OK not to
879 * clear options if they are not set.
880 * If this assertion is proven to be false, output a clear warning
881 * to let the user know what happens. */
882 if (SSL_CTX_get_options(ssl_ctx) != 0)
883 {
884 Log(LOG_LEVEL_WARNING,
885 "This version of CFEngine was compiled against OpenSSL < 0.9.8m, "
886 "using it with a later OpenSSL version is insecure. "
887 "The current version uses compatibility workarounds that may allow "
888 "CVE-2009-3555 exploitation.");
889 Log(LOG_LEVEL_WARNING, "Please update your CFEngine package or "
890 "compile it against your current OpenSSL version.");
891 }
892 #endif
893
894 /* In any case use only TLS v1 or later. */
895 long options = SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3;
896
897 assert(TLS_LOWEST_RECOMMENDED >= TLS_LOWEST_REQUIRED);
898 enum tls_version min_tls_version = TLS_LOWEST_RECOMMENDED;
899 if (!NULL_OR_EMPTY(min_version))
900 {
901 bool found = false;
902 for (enum tls_version v = TLS_1_0; !found && v <= TLS_LAST; v++)
903 {
904 if (StringEqual(min_version, tls_version_strings[v]))
905 {
906 found = true;
907 if (v < TLS_LOWEST_REQUIRED)
908 {
909 Log(LOG_LEVEL_WARNING, "Minimum requested TLS version is %s,"
910 " but minimum version required by CFEngine is %s."
911 " Using the minimum required version.",
912 min_version, tls_version_strings[TLS_LOWEST_REQUIRED]);
913 min_tls_version = TLS_LOWEST_REQUIRED;
914 }
915 else if (v < TLS_LOWEST_RECOMMENDED)
916 {
917 Log(LOG_LEVEL_WARNING, "Minimum requested TLS version is %s,"
918 " but minimum version recommended by CFEngine is %s.",
919 min_version, tls_version_strings[TLS_LOWEST_RECOMMENDED]);
920 min_tls_version = v;
921 }
922 else if (v > TLS_HIGHEST_SUPPORTED)
923 {
924 Log(LOG_LEVEL_WARNING, "Minimum requested TLS version is %s,"
925 " but maximum version supported by OpenSSL is %s."
926 " Using the maximum supported version.",
927 min_version, tls_version_strings[TLS_HIGHEST_SUPPORTED]);
928 min_tls_version = TLS_HIGHEST_SUPPORTED;
929 }
930 else
931 {
932 min_tls_version = v;
933 }
934 }
935 }
936 if (!found)
937 {
938 Log(LOG_LEVEL_WARNING,
939 "Unrecognized requested minimum TLS version '%s',"
940 " using the minimum required version %s.",
941 min_version, tls_version_strings[TLS_LOWEST_REQUIRED]);
942 min_tls_version = TLS_LOWEST_REQUIRED;
943 }
944 }
945
946 Log(LOG_LEVEL_VERBOSE,
947 "Setting minimum acceptable TLS version: %s", tls_version_strings[min_tls_version]);
948
949 /* disable all the lower versions than the minimum requested/determined */
950 for (enum tls_version v = TLS_1_0; v < min_tls_version; v++)
951 {
952 options |= tls_disable_flags[v];
953 }
954
955 /* No session resumption or renegotiation for now. */
956 options |= SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION;
957
958 #ifdef SSL_OP_NO_TICKET
959 /* Disable another way of resumption, session tickets (RFC 5077). */
960 options |= SSL_OP_NO_TICKET;
961 #endif
962
963 SSL_CTX_set_options(ssl_ctx, options);
964
965
966 /* Disable both server-side and client-side session caching, to
967 complement the previous options. Safe for now, might enable for
968 performance in the future. */
969 SSL_CTX_set_session_cache_mode(ssl_ctx, SSL_SESS_CACHE_OFF);
970
971
972 /* Never bother with retransmissions, SSL_write() should
973 * always either write the whole amount or fail. */
974 SSL_CTX_set_mode(ssl_ctx, SSL_MODE_AUTO_RETRY);
975
976 /* Set options to always request a certificate from the peer,
977 either we are client or server. */
978 SSL_CTX_set_verify(ssl_ctx,
979 SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
980 NULL);
981 /* Always accept that certificate, we do proper checking after TLS
982 * connection is established since OpenSSL can't pass a connection
983 * specific pointer to the callback (so we would have to lock). */
984 SSL_CTX_set_cert_verify_callback(ssl_ctx, TLSVerifyCallback, NULL);
985 }
986
TLSSetCipherList(SSL_CTX * ssl_ctx,const char * cipher_list)987 bool TLSSetCipherList(SSL_CTX *ssl_ctx, const char *cipher_list)
988 {
989 assert(ssl_ctx);
990
991 if (cipher_list == NULL)
992 {
993 Log(LOG_LEVEL_VERBOSE, "Using the OpenSSL's default cipher list");
994 /* nothing more to do */
995 return true;
996 }
997
998 Log(LOG_LEVEL_VERBOSE, "Setting cipher list for TLS connections to: %s",
999 cipher_list);
1000
1001 const size_t max_len = strlen(cipher_list) + 1; /* NUL byte */
1002 size_t n_specs = StringCountTokens(cipher_list, max_len, ":");
1003
1004 /* TLS 1.3 defines cipher suites, they start with "TLS_" */
1005 char ciphers[max_len];
1006 size_t ciphers_len = 0;
1007
1008 char cipher_suites[max_len];
1009 size_t cipher_suites_len = 0;
1010
1011 for (size_t i = 0; i < n_specs; i++)
1012 {
1013 StringRef spec_ref = StringGetToken(cipher_list, max_len, i, ":");
1014 if (StringStartsWith(spec_ref.data, "TLS_"))
1015 {
1016 StrCat(cipher_suites, max_len, &cipher_suites_len, spec_ref.data, spec_ref.len + 1);
1017 }
1018 else
1019 {
1020 StrCat(ciphers, max_len, &ciphers_len, spec_ref.data, spec_ref.len + 1);
1021 }
1022 }
1023
1024 if (ciphers_len != 0) /* TLS <= 1.2 ciphers */
1025 {
1026 int ret = SSL_CTX_set_cipher_list(ssl_ctx, ciphers);
1027 if (ret != 1)
1028 {
1029 Log(LOG_LEVEL_ERR, "No valid ciphers in the cipher list: %s", cipher_list);
1030 return false;
1031 }
1032 }
1033
1034 #ifdef HAVE_TLS_1_3
1035 if (cipher_suites_len != 0) /* TLS >= 1.3 ciphers */
1036 {
1037 int ret = SSL_CTX_set_ciphersuites(ssl_ctx, cipher_suites);
1038 if (ret != 1)
1039 {
1040 Log(LOG_LEVEL_ERR, "No valid cipher suites in the list: %s", cipher_list);
1041 return false;
1042 }
1043 }
1044 else
1045 {
1046 /* Allowed ciphers specified, but no TLS 1.3 ciphersuites among them.
1047 Let's disable TLS 1.3 because otherwise OpenSSL uses the default
1048 ciphersuites for TLS 1.3 and thus effectively extends the specified
1049 list of allowed ciphers behind our back. */
1050 Log(LOG_LEVEL_WARNING,
1051 "Disabling TLS 1.3 because no TLS 1.3 ciphersuites specified in allowed ciphers: '%s'",
1052 cipher_list);
1053 SSL_CTX_set_options(ssl_ctx, SSL_OP_NO_TLSv1_3);
1054 }
1055 #else
1056 if (cipher_suites_len != 0)
1057 {
1058 Log(LOG_LEVEL_WARNING,
1059 "Ignoring requested TLS 1.3 ciphersuites '%s', TLS 1.3 not supported",
1060 cipher_suites);
1061 }
1062 #endif
1063
1064 return true;
1065 }
1066