1 /*
2  * Copyright (C) Tildeslash Ltd. All rights reserved.
3  *
4  * This program is free software: you can redistribute it and/or modify
5  * it under the terms of the GNU Affero General Public License version 3.
6  *
7  * This program is distributed in the hope that it will be useful,
8  * but WITHOUT ANY WARRANTY; without even the implied warranty of
9  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10  * GNU General Public License for more details.
11  *
12  * You should have received a copy of the GNU Affero General Public License
13  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
14  *
15  * In addition, as a special exception, the copyright holders give
16  * permission to link the code of portions of this program with the
17  * OpenSSL library under certain conditions as described in each
18  * individual source file, and distribute linked combinations
19  * including the two.
20  *
21  * You must obey the GNU Affero General Public License in all respects
22  * for all of the code used other than OpenSSL.
23  */
24 
25 
26 #include "config.h"
27 
28 
29 #ifdef HAVE_OPENSSL
30 
31 
32 #ifdef HAVE_STDIO_H
33 #include <stdio.h>
34 #endif
35 
36 #ifdef HAVE_MEMORY_H
37 #include <memory.h>
38 #endif
39 
40 #ifdef HAVE_SYS_TYPES_H
41 #include <sys/types.h>
42 #endif
43 
44 #ifdef HAVE_SYS_SOCKET_H
45 #include <sys/socket.h>
46 #endif
47 
48 #ifdef HAVE_NETINET_IN_H
49 #include <netinet/in.h>
50 #endif
51 
52 #ifdef HAVE_ARPA_INET_H
53 #include <arpa/inet.h>
54 #endif
55 
56 #ifdef HAVE_NETDB_H
57 #include <netdb.h>
58 #endif
59 
60 #ifdef HAVE_UNISTD_H
61 #include <unistd.h>
62 #endif
63 
64 #ifdef HAVE_ERRNO_H
65 #include <errno.h>
66 #endif
67 
68 #ifdef HAVE_STRING_H
69 #include <string.h>
70 #endif
71 
72 #include <openssl/crypto.h>
73 #include <openssl/x509.h>
74 #include <openssl/x509_vfy.h>
75 #include <openssl/pem.h>
76 #include <openssl/ssl.h>
77 #include <openssl/err.h>
78 #include <openssl/rand.h>
79 
80 #include "monit.h"
81 #include "Ssl.h"
82 #include "SslServer.h"
83 
84 // libmonit
85 #include "io/File.h"
86 #include "system/Net.h"
87 #include "system/Time.h"
88 #include "exceptions/AssertException.h"
89 #include "exceptions/IOException.h"
90 
91 
92 /**
93  *  SSL implementation
94  *
95  *  @file
96  */
97 //FIXME: refactor Ssl_connect(), Ssl_write() and Ssl_read() + SslServer_accept (and the whole network layer) to be really non-blocking
98 
99 
100 /* ------------------------------------------------------------- Definitions */
101 
102 
103 /**
104  * Number of random bytes to obtain
105  */
106 #define RANDOM_BYTES 1024
107 
108 
109 /**
110  * The PRIMARY random device selected for seeding the PRNG. We use a non-blocking pseudo random device, to generate pseudo entropy.
111  */
112 #define URANDOM_DEVICE "/dev/urandom"
113 
114 
115 /**
116  * If a non-blocking device is not found on the system a blocking entropy producer is tried instead.
117  */
118 #define RANDOM_DEVICE "/dev/random"
119 
120 
121 #define SSLERROR ERR_error_string(ERR_get_error(),NULL)
122 
123 
124 #define T Ssl_T
125 struct T {
126         bool accepted;
127         int socket;
128         SslOptions_T options;
129         SSL *handler;
130         SSL_CTX *ctx;
131         X509 *certificate;
132         char error[128];
133 };
134 
135 
136 struct SslServer_T {
137         int socket;
138         SSL_CTX *ctx;
139         SslOptions_T options;
140 };
141 
142 
143 #if (OPENSSL_VERSION_NUMBER < 0x10100000L) || defined(LIBRESSL_VERSION_NUMBER)
144 static Mutex_T *instanceMutexTable;
145 #endif
146 
147 
148 static int session_id_context = 1;
149 
150 
151 /* ----------------------------------------------------------------- Private */
152 
153 
_optionsVersion(int version)154 static Ssl_Version _optionsVersion(int version) {
155         return version != -1 ? version : Run.ssl.version != -1 ? Run.ssl.version : SSL_Auto;
156 }
157 
158 
_optionsVerify(short verify)159 static bool _optionsVerify(short verify) {
160         return verify != -1 ? verify : Run.ssl.verify != -1 ? Run.ssl.verify : false;
161 }
162 
163 
_optionsAllowSelfSigned(short allowSelfSigned)164 static bool _optionsAllowSelfSigned(short allowSelfSigned) {
165         return allowSelfSigned != -1 ? allowSelfSigned : Run.ssl.allowSelfSigned != -1 ? Run.ssl.allowSelfSigned : false;
166 }
167 
168 
_optionsCiphers(const char * ciphers)169 static const char *_optionsCiphers(const char *ciphers) {
170         return ciphers ? ciphers : Run.ssl.ciphers ? Run.ssl.ciphers: CIPHER_LIST;
171 }
172 
173 
_optionsCACertificateFile(const char * CACertificateFile)174 static const char *_optionsCACertificateFile(const char *CACertificateFile) {
175         return CACertificateFile ? CACertificateFile : Run.ssl.CACertificateFile ? Run.ssl.CACertificateFile: NULL;
176 }
177 
178 
_optionsCACertificatePath(const char * CACertificatePath)179 static const char *_optionsCACertificatePath(const char *CACertificatePath) {
180         return CACertificatePath ? CACertificatePath : Run.ssl.CACertificatePath ? Run.ssl.CACertificatePath: NULL;
181 }
182 
183 
_optionsServerPEMFile(const char * pemfile)184 static const char *_optionsServerPEMFile(const char *pemfile) {
185         return pemfile ? pemfile : Run.ssl.pemfile ? Run.ssl.pemfile: NULL;
186 }
187 
188 
_optionsServerPEMChain(const char * pemchain)189 static const char *_optionsServerPEMChain(const char *pemchain) {
190         return pemchain ? pemchain : Run.ssl.pemchain ? Run.ssl.pemchain: NULL;
191 }
192 
193 
_optionsServerPEMKey(const char * pemkey)194 static const char *_optionsServerPEMKey(const char *pemkey) {
195         return pemkey ? pemkey : Run.ssl.pemkey ? Run.ssl.pemkey: NULL;
196 }
197 
198 
_optionsClientPEMFile(const char * clientpemfile)199 static const char *_optionsClientPEMFile(const char *clientpemfile) {
200         return clientpemfile ? clientpemfile : Run.ssl.clientpemfile ? Run.ssl.clientpemfile: NULL;
201 }
202 
203 
_optionsChecksum(const char * checksum)204 static const char *_optionsChecksum(const char *checksum) {
205         return STR_DEF(checksum) ? checksum : STR_DEF(Run.ssl.checksum) ? Run.ssl.checksum : NULL;
206 }
207 
208 
_optionsChecksumType(Hash_Type checksumType)209 static Hash_Type _optionsChecksumType(Hash_Type checksumType) {
210         return checksumType ? checksumType : Run.ssl.checksumType ? Run.ssl.checksumType : Hash_Unknown;
211 }
212 
213 
_setVersion(SSL_CTX * ctx,SslOptions_T options)214 static bool _setVersion(SSL_CTX *ctx, SslOptions_T options) {
215         unsigned long versionMask = SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1;
216 #if defined HAVE_TLSV1_1
217         versionMask |= SSL_OP_NO_TLSv1_1;
218 #endif
219 #if defined HAVE_TLSV1_2
220         versionMask |= SSL_OP_NO_TLSv1_2;
221 #endif
222 #if defined HAVE_TLSV1_3
223         versionMask |= SSL_OP_NO_TLSv1_3;
224 #endif
225 
226         short versionAllowed = _optionsVersion(options->version);
227 
228         if (versionAllowed & SSL_V2) {
229 #if defined OPENSSL_NO_SSL2 || ! defined HAVE_SSLV2
230                 Log_error("SSL: SSLv2 not supported\n");
231                 return false;
232 #else
233                 if (Run.flags & Run_FipsEnabled) {
234                         Log_error("SSL: SSLv2 is not allowed in FIPS mode -- use TLS\n");
235                         return false;
236                 }
237                 versionMask &= ~SSL_OP_NO_SSLv2;
238 #endif
239         }
240 
241         if (versionAllowed & SSL_V3) {
242 #if defined OPENSSL_NO_SSL3
243                 Log_error("SSL: SSLv3 not supported\n");
244                 return false;
245 #else
246                 if (Run.flags & Run_FipsEnabled) {
247                         Log_error("SSL: SSLv3 is not allowed in FIPS mode -- use TLS\n");
248                         return false;
249                 }
250                 versionMask &= ~SSL_OP_NO_SSLv3;
251 #endif
252         }
253 
254         if (versionAllowed & SSL_TLSV1) {
255 #if defined OPENSSL_NO_TLS1_METHOD
256                 Log_error("SSL: TLSv1.0 not supported\n");
257                 return false;
258 #else
259                 versionMask &= ~SSL_OP_NO_TLSv1;
260 #endif
261         }
262 
263         if (versionAllowed & SSL_TLSV11) {
264 #if defined OPENSSL_NO_TLS1_1_METHOD || ! defined HAVE_TLSV1_1
265                 Log_error("SSL: TLSv1.1 not supported\n");
266                 return false;
267 #else
268                 versionMask &= ~SSL_OP_NO_TLSv1_1;
269 #endif
270         }
271 
272         if (versionAllowed & SSL_TLSV12) {
273 #if defined OPENSSL_NO_TLS1_2_METHOD || ! defined HAVE_TLSV1_2
274                 Log_error("SSL: TLSv1.2 not supported\n");
275                 return false;
276 #else
277                 versionMask &= ~SSL_OP_NO_TLSv1_2;
278 #endif
279         }
280 
281         if (versionAllowed & SSL_TLSV13) {
282 #if defined OPENSSL_NO_TLS1_3_METHOD || ! defined HAVE_TLSV1_3
283                 Log_error("SSL: TLSv1.3 not supported\n");
284                 return false;
285 #else
286                 versionMask &= ~SSL_OP_NO_TLSv1_3;
287 #endif
288         }
289 
290         if (versionAllowed == SSL_Auto) {
291                 // Enable TLS 1.2 and 1.3 protocols by default
292 #if ! defined OPENSSL_NO_TLS1_2_METHOD && defined HAVE_TLSV1_2
293                 versionMask &= ~SSL_OP_NO_TLSv1_2;
294 #endif
295 #if ! defined OPENSSL_NO_TLS1_3_METHOD && defined HAVE_TLSV1_3
296                 versionMask &= ~SSL_OP_NO_TLSv1_3;
297 #endif
298         }
299 
300         SSL_CTX_set_options(ctx, versionMask);
301         return true;
302 }
303 
304 
_retry(int socket,int * timeout,bool (* callback)(int socket,time_t milliseconds))305 static bool _retry(int socket, int *timeout, bool (*callback)(int socket, time_t milliseconds)) {
306         long long start = Time_milli();
307         if (callback(socket, *timeout)) {
308                 long long stop = Time_milli();
309                 if (stop >= start && (*timeout -= stop - start) > 0) // Reduce timeout with guard against backward clock jumps
310                         return true;
311         }
312         errno = ETIMEDOUT;
313         return false;
314 }
315 
316 
317 #if (OPENSSL_VERSION_NUMBER < 0x10100000L) || defined(LIBRESSL_VERSION_NUMBER)
_threadID(CRYPTO_THREADID * id)318 static void _threadID(CRYPTO_THREADID *id) {
319         CRYPTO_THREADID_set_numeric(id, (unsigned long)Thread_self());
320 }
321 
322 
_mutexLock(int mode,int n,const char * file,int line)323 static void _mutexLock(int mode, int n, __attribute__ ((unused)) const char *file, __attribute__ ((unused)) int line) {
324         if (mode & CRYPTO_LOCK)
325                 Mutex_lock(instanceMutexTable[n]);
326         else
327                 Mutex_unlock(instanceMutexTable[n]);
328 }
329 #endif
330 
331 
_checkChecksum(T C,X509_STORE_CTX * ctx,X509 * certificate)332 static int _checkChecksum(T C, X509_STORE_CTX *ctx, X509 *certificate) {
333         Hash_Type checksumType = _optionsChecksumType(C->options->checksumType);
334         const char *checksum = _optionsChecksum(C->options->checksum);
335         if (checksumType != Hash_Unknown && STR_DEF(checksum) && X509_STORE_CTX_get_error_depth(ctx) == 0) {
336                 const EVP_MD *hash = NULL;
337                 switch (checksumType) {
338                         case Hash_Md5:
339                                 if (Run.flags & Run_FipsEnabled) {
340                                         X509_STORE_CTX_set_error(ctx, X509_V_ERR_APPLICATION_VERIFICATION);
341                                         snprintf(C->error, sizeof(C->error), "SSL certificate MD5 checksum is not supported in FIPS mode, please use SHA1");
342                                         return 0;
343                                 } else {
344                                         hash = EVP_md5();
345                                 }
346                                 break;
347                         case Hash_Sha1:
348                                 hash = EVP_sha1();
349                                 break;
350                         default:
351                                 X509_STORE_CTX_set_error(ctx, X509_V_ERR_APPLICATION_VERIFICATION);
352                                 snprintf(C->error, sizeof(C->error), "Invalid SSL certificate checksum type (0x%x)", checksumType);
353                                 return 0;
354                 }
355                 unsigned int len, i = 0;
356                 unsigned char realChecksum[EVP_MAX_MD_SIZE];
357                 X509_digest(certificate, hash, realChecksum, &len);
358                 while ((i < len) && (checksum[2 * i] != '\0') && (checksum[2 * i + 1] != '\0')) {
359                         unsigned char c = (checksum[2 * i] > 57 ? checksum[2 * i] - 87 : checksum[2 * i] - 48) * 0x10 + (checksum[2 * i + 1] > 57 ? checksum[2 * i + 1] - 87 : checksum[2 * i + 1] - 48);
360                         if (c != realChecksum[i]) {
361                                 X509_STORE_CTX_set_error(ctx, X509_V_ERR_APPLICATION_VERIFICATION);
362                                 snprintf(C->error, sizeof(C->error), "SSL server certificate checksum failed");
363                                 return 0;
364                         }
365                         i++;
366                 }
367         }
368         return 1;
369 }
370 
371 
_saveAndCheckServerCertificates(T C,X509_STORE_CTX * ctx)372 static int _saveAndCheckServerCertificates(T C, X509_STORE_CTX *ctx) {
373         if ((C->certificate = X509_STORE_CTX_get_current_cert(ctx))) {
374                 return _checkChecksum(C, ctx, C->certificate);
375         }
376         X509_STORE_CTX_set_error(ctx, X509_V_ERR_APPLICATION_VERIFICATION);
377         snprintf(C->error, sizeof(C->error), "cannot get SSL server certificate");
378         return 0;
379 }
380 
381 
_verifyServerCertificates(int preverify_ok,X509_STORE_CTX * ctx)382 static int _verifyServerCertificates(int preverify_ok, X509_STORE_CTX *ctx) {
383         T C = SSL_get_app_data(X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx()));
384         if (! C) {
385                 Log_error("SSL: cannot get application data");
386                 return 0;
387         }
388         *C->error = 0;
389         if (! preverify_ok && _optionsVerify(C->options->verify)) {
390                 int error = X509_STORE_CTX_get_error(ctx);
391                 switch (error) {
392                         case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
393                                 if (_optionsAllowSelfSigned(C->options->allowSelfSigned)) {
394                                         X509_STORE_CTX_set_error(ctx, X509_V_OK);
395                                         return _saveAndCheckServerCertificates(C, ctx);
396                                 }
397                                 snprintf(C->error, sizeof(C->error), "self signed certificate is not allowed, please use a trusted certificate or use the 'selfsigned: allow' SSL option");
398                                 break;
399                         default:
400                                 break;
401                 }
402         } else {
403                 return _saveAndCheckServerCertificates(C, ctx);
404         }
405         return 0;
406 }
407 
408 
_verifyClientCertificates(int preverify_ok,X509_STORE_CTX * ctx)409 static int _verifyClientCertificates(int preverify_ok, X509_STORE_CTX *ctx) {
410         T C = SSL_get_app_data(X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx()));
411         if (! C) {
412                 Log_error("SSL: cannot get application data");
413                 return 0;
414         }
415         if (! preverify_ok) {
416                 int error = X509_STORE_CTX_get_error(ctx);
417                 switch (error) {
418                         case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
419                                 if (! (_optionsAllowSelfSigned(C->options->allowSelfSigned))) {
420                                         Log_error("SSL: self-signed certificate is not allowed\n");
421                                         return 0;
422                                 }
423                                 X509_STORE_CTX_set_error(ctx, X509_V_OK); // Reset error if we accept self-signed certificates
424                                 break;
425                         case X509_V_ERR_INVALID_PURPOSE:
426                                 break;
427                         default:
428                                 Log_error("SSL: invalid certificate -- %s\n", X509_verify_cert_error_string(error));
429                                 return 0;
430                 }
431         }
432 #if (OPENSSL_VERSION_NUMBER < 0x10100000L) || defined(LIBRESSL_VERSION_NUMBER)
433         X509_OBJECT found_cert;
434         if (X509_STORE_CTX_get_error_depth(ctx) == 0 && X509_STORE_get_by_subject(ctx, X509_LU_X509, X509_get_subject_name(X509_STORE_CTX_get_current_cert(ctx)), &found_cert) != 1) {
435 #else
436         X509_OBJECT *found_cert = X509_OBJECT_new();
437         if (X509_STORE_CTX_get_error_depth(ctx) == 0 && X509_STORE_CTX_get_by_subject(ctx, X509_LU_X509, X509_get_subject_name(X509_STORE_CTX_get_current_cert(ctx)), found_cert) != 1) {
438 #endif
439                 Log_error("SSL: no matching certificate found -- %s\n", SSLERROR);
440                 X509_STORE_CTX_set_error(ctx, X509_V_ERR_CERT_REJECTED);
441 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && ! defined(LIBRESSL_VERSION_NUMBER)
442                 X509_OBJECT_free(found_cert);
443 #endif
444                 return 0;
445         }
446 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && ! defined(LIBRESSL_VERSION_NUMBER)
447         X509_OBJECT_free(found_cert);
448 #endif
449         return 1;
450 }
451 
452 
453 static bool _setServerNameIdentification(T C, const char *hostname) {
454 #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
455         struct sockaddr_storage addr;
456         // If the name is set and we use TLS protocol, enable the SNI extension (provided the hostname value is not an IP address)
457         if (hostname && C->options->version != SSL_V2 && C->options->version != SSL_V3 && ! inet_pton(AF_INET, hostname, &(((struct sockaddr_in *)&addr)->sin_addr)) &&
458 #ifdef HAVE_IPV6
459                 ! inet_pton(AF_INET6, hostname, &(((struct sockaddr_in6 *)&addr)->sin6_addr)) &&
460 #endif
461                 ! SSL_set_tlsext_host_name(C->handler, hostname)) {
462                         DEBUG("SSL: unable to set the SNI extension to %s\n", hostname);
463                         return false;
464                 }
465 #endif
466         return true;
467 }
468 
469 
470 static bool _setClientCertificate(T C, const char *file) {
471         if (SSL_CTX_use_certificate_chain_file(C->ctx, file) != 1) {
472                 Log_error("SSL client certificate chain loading failed: %s\n", SSLERROR);
473                 return false;
474         }
475         if (SSL_CTX_use_PrivateKey_file(C->ctx, file, SSL_FILETYPE_PEM) != 1) {
476                 Log_error("SSL client private key loading failed: %s\n", SSLERROR);
477                 return false;
478         }
479         if (SSL_CTX_check_private_key(C->ctx) != 1) {
480                 Log_error("SSL client private key doesn't match the certificate: %s\n", SSLERROR);
481                 return false;
482         }
483         return true;
484 }
485 
486 
487 /* ------------------------------------------------------------------ Public */
488 
489 
490 void Ssl_start() {
491 #if (OPENSSL_VERSION_NUMBER < 0x10100000L) || defined(LIBRESSL_VERSION_NUMBER)
492         SSL_library_init();
493         SSL_load_error_strings();
494         int locks = CRYPTO_num_locks();
495         instanceMutexTable = CALLOC(locks, sizeof(Mutex_T));
496         for (int i = 0; i < locks; i++)
497                 Mutex_init(instanceMutexTable[i]);
498         CRYPTO_THREADID_set_callback(_threadID);
499         CRYPTO_set_locking_callback(_mutexLock);
500 #endif
501         if (File_exist(URANDOM_DEVICE))
502                 RAND_load_file(URANDOM_DEVICE, RANDOM_BYTES);
503         else if (File_exist(RANDOM_DEVICE))
504                 RAND_load_file(RANDOM_DEVICE, RANDOM_BYTES);
505         else
506                 THROW(AssertException, "SSL: cannot find %s nor %s on the system", URANDOM_DEVICE, RANDOM_DEVICE);
507 }
508 
509 
510 void Ssl_stop() {
511 #if (OPENSSL_VERSION_NUMBER < 0x10100000L) || defined(LIBRESSL_VERSION_NUMBER)
512         CRYPTO_THREADID_set_callback(NULL);
513         CRYPTO_set_locking_callback(NULL);
514         for (int i = 0; i < CRYPTO_num_locks(); i++)
515                 Mutex_destroy(instanceMutexTable[i]);
516         FREE(instanceMutexTable);
517         RAND_cleanup();
518         ERR_free_strings();
519 #endif
520         Ssl_threadCleanup();
521 }
522 
523 
524 void Ssl_threadCleanup() {
525 #if (OPENSSL_VERSION_NUMBER < 0x10100000L) || defined(LIBRESSL_VERSION_NUMBER)
526         ERR_remove_thread_state(NULL);
527 #endif
528 }
529 
530 
531 #ifdef OPENSSL_FIPS
532 void Ssl_setFipsMode(bool enabled) {
533         if (enabled && ! FIPS_mode() && ! FIPS_mode_set(1))
534                 THROW(AssertException, "SSL: cannot enter FIPS mode -- %s", SSLERROR);
535         else if (! enabled && FIPS_mode() && ! FIPS_mode_set(0))
536                 THROW(AssertException, "SSL: cannot exit FIPS mode -- %s", SSLERROR);
537 }
538 #endif
539 
540 
541 T Ssl_new(SslOptions_T options) {
542         ASSERT(options);
543         T C;
544         NEW(C);
545         C->options = options;
546 #if (OPENSSL_VERSION_NUMBER < 0x10100000L) || defined(LIBRESSL_VERSION_NUMBER)
547         const SSL_METHOD *method = SSLv23_client_method();
548 #else
549         const SSL_METHOD *method = TLS_client_method();
550 #endif
551         if (! method) {
552                 Log_error("SSL: client method initialization failed -- %s\n", SSLERROR);
553                 goto sslerror;
554         }
555         if (! (C->ctx = SSL_CTX_new(method))) {
556                 Log_error("SSL: client context initialization failed -- %s\n", SSLERROR);
557                 goto sslerror;
558         }
559         if (! _setVersion(C->ctx, options)) {
560                 goto sslerror;
561         }
562         SSL_CTX_set_default_verify_paths(C->ctx);
563         const char *CACertificateFile = _optionsCACertificateFile(options->CACertificateFile);
564         const char *CACertificatePath = _optionsCACertificatePath(options->CACertificatePath);
565         if (CACertificateFile || CACertificatePath) {
566                 if (! SSL_CTX_load_verify_locations(C->ctx, CACertificateFile, CACertificatePath)) {
567                         Log_error("SSL: CA certificates loading failed -- %s\n", SSLERROR);
568                         goto sslerror;
569                 }
570         }
571         const char *ClientPEMFile = _optionsClientPEMFile(options->clientpemfile);
572         if (ClientPEMFile && ! _setClientCertificate(C, ClientPEMFile))
573                 goto sslerror;
574 #ifdef SSL_OP_NO_COMPRESSION
575         SSL_CTX_set_options(C->ctx, SSL_OP_NO_COMPRESSION);
576 #endif
577         const char *ciphers = _optionsCiphers(options->ciphers);
578         if (SSL_CTX_set_cipher_list(C->ctx, ciphers) != 1) {
579                 Log_error("SSL: client cipher list [%s] error -- no valid ciphers\n", ciphers);
580                 goto sslerror;
581         }
582         if (! (C->handler = SSL_new(C->ctx))) {
583                 Log_error("SSL: cannot create client handler -- %s\n", SSLERROR);
584                 goto sslerror;
585         }
586         SSL_set_verify(C->handler, SSL_VERIFY_PEER, _verifyServerCertificates);
587         SSL_set_mode(C->handler, SSL_MODE_ENABLE_PARTIAL_WRITE | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
588         SSL_set_app_data(C->handler, C);
589         return C;
590 sslerror:
591         Ssl_free(&C);
592         return NULL;
593 }
594 
595 
596 void Ssl_free(T *C) {
597         ASSERT(C && *C);
598         if ((*C)->handler)
599                 SSL_free((*C)->handler);
600         if ((*C)->ctx && ! (*C)->accepted)
601                 SSL_CTX_free((*C)->ctx);
602         FREE(*C);
603 }
604 
605 
606 void Ssl_close(T C) {
607         ASSERT(C);
608         bool retry = false;
609         int timeout = Run.limits.networkTimeout;
610         do {
611                 int rv = SSL_shutdown(C->handler);
612                 if (rv == 0) {
613                         // close notify sent
614                         retry = _retry(C->socket, &timeout, Net_canRead);
615                         continue;
616                 } else if (rv == 1) {
617                         // shutdown finished
618                         break;
619                 } else if (rv < 0) {
620                         switch (SSL_get_error(C->handler, rv)) {
621                                 case SSL_ERROR_WANT_READ:
622                                         retry = _retry(C->socket, &timeout, Net_canRead);
623                                         break;
624                                 case SSL_ERROR_WANT_WRITE:
625                                         retry = _retry(C->socket, &timeout, Net_canWrite);
626                                         break;
627                                 default:
628                                         retry = false;
629                                         break;
630                         }
631                 }
632         } while (retry);
633         Net_shutdown(C->socket, SHUT_RDWR);
634         Net_close(C->socket);
635 }
636 
637 
638 void Ssl_connect(T C, int socket, int timeout, const char *name) {
639         ASSERT(C);
640         ASSERT(socket >= 0);
641         C->socket = socket;
642         SSL_set_connect_state(C->handler);
643         SSL_set_fd(C->handler, C->socket);
644         _setServerNameIdentification(C, name);
645         bool retry = false;
646         do {
647                 int rv = SSL_connect(C->handler);
648                 if (rv < 0) {
649                         switch (SSL_get_error(C->handler, rv)) {
650                                 case SSL_ERROR_NONE:
651                                         break;
652                                 case SSL_ERROR_WANT_READ:
653                                         retry = _retry(C->socket, &timeout, Net_canRead);
654                                         break;
655                                 case SSL_ERROR_WANT_WRITE:
656                                         retry = _retry(C->socket, &timeout, Net_canWrite);
657                                         break;
658                                 default:
659 					rv = (int)SSL_get_verify_result(C->handler);
660 					if (rv != X509_V_OK)
661                                                 THROW(IOException, "SSL server certificate verification error: %s", *C->error ? C->error : X509_verify_cert_error_string(rv));
662 					else
663                                                 THROW(IOException, "SSL connection error: %s", SSLERROR);
664                                         break;
665                         }
666                 } else {
667                         break;
668                 }
669         } while (retry);
670 }
671 
672 
673 int Ssl_write(T C, const void *b, int size, int timeout) {
674         ASSERT(C);
675         int n = 0;
676         if (size > 0) {
677                 bool retry = false;
678                 do {
679                         switch (SSL_get_error(C->handler, (n = SSL_write(C->handler, b, size)))) {
680                                 case SSL_ERROR_NONE:
681                                 case SSL_ERROR_ZERO_RETURN:
682                                         return n;
683                                 case SSL_ERROR_WANT_READ:
684                                         n = 0;
685                                         errno = EWOULDBLOCK;
686                                         retry = _retry(C->socket, &timeout, Net_canRead);
687                                         break;
688                                 case SSL_ERROR_WANT_WRITE:
689                                         n = 0;
690                                         errno = EWOULDBLOCK;
691                                         retry = _retry(C->socket, &timeout, Net_canWrite);
692                                         break;
693                                 case SSL_ERROR_SYSCALL:
694                                         {
695                                                 unsigned long error = ERR_get_error();
696                                                 if (error)
697                                                         Log_error("SSL: write error -- %s\n", ERR_error_string(error, NULL));
698                                                 else if (n == 0)
699                                                         Log_error("SSL: write error -- EOF\n");
700                                                 else if (n == -1)
701                                                         Log_error("SSL: write I/O error -- %s\n", STRERROR);
702                                         }
703                                         return -1;
704                                 default:
705                                         Log_error("SSL: write error -- %s\n", SSLERROR);
706                                         return -1;
707                         }
708                 } while (retry);
709         }
710         return n;
711 }
712 
713 
714 int Ssl_read(T C, void *b, int size, int timeout) {
715         ASSERT(C);
716         int n = 0;
717         if (size > 0) {
718                 bool retry = false;
719                 do {
720                         switch (SSL_get_error(C->handler, (n = SSL_read(C->handler, b, size)))) {
721                                 case SSL_ERROR_NONE:
722                                 case SSL_ERROR_ZERO_RETURN:
723                                         return n;
724                                 case SSL_ERROR_WANT_READ:
725                                         n = 0;
726                                         errno = EWOULDBLOCK;
727                                         retry = _retry(C->socket, &timeout, Net_canRead);
728                                         break;
729                                 case SSL_ERROR_WANT_WRITE:
730                                         n = 0;
731                                         errno = EWOULDBLOCK;
732                                         retry = _retry(C->socket, &timeout, Net_canWrite);
733                                         break;
734                                 case SSL_ERROR_SYSCALL:
735                                         {
736                                                 unsigned long error = ERR_get_error();
737                                                 if (error)
738                                                         Log_error("SSL: read error -- %s\n", ERR_error_string(error, NULL));
739                                                 else if (n == 0)
740                                                         Log_error("SSL: read error -- EOF\n");
741                                                 else if (n == -1)
742                                                         Log_error("SSL: read I/O error -- %s\n", STRERROR);
743                                         }
744                                         return -1;
745                                 default:
746                                         Log_error("SSL: read error -- %s\n", SSLERROR);
747                                         return -1;
748                         }
749                 } while (retry);
750         }
751         return n;
752 }
753 
754 
755 int Ssl_getCertificateValidDays(T C) {
756         if (C && C->certificate) {
757                 // Certificates which expired already are caught in preverify => we don't need to handle them here
758                 volatile int deltadays = 0;
759                 ASN1_TIME *nat = NULL;
760 #if (OPENSSL_VERSION_NUMBER < 0x10100000L) || defined(LIBRESSL_VERSION_NUMBER)
761                 nat = (ASN1_TIME  *)X509_get_notAfter(C->certificate);
762 #else
763                 nat = (ASN1_TIME *)X509_get0_notAfter(C->certificate);
764 #endif
765                 if (! nat) {
766                         THROW(IOException, "unable to get certificate notAfter field");
767                 }
768 #ifdef HAVE_ASN1_TIME_DIFF
769                 int deltaseconds;
770                 if (! ASN1_TIME_diff((int *)&deltadays, &deltaseconds, NULL, nat)) {
771                         THROW(IOException, "invalid time format in certificate's notAfter field");
772                 }
773 #else
774                 ASN1_GENERALIZEDTIME *t = ASN1_TIME_to_generalizedtime(nat, NULL);
775                 if (! t) {
776                         THROW(IOException, "invalid time format (in certificate's notAfter field)");
777                 }
778                 TRY
779                 {
780                         deltadays = (double)(Time_toTimestamp((const char *)t->data) - Time_now()) / 86400.;
781                 }
782                 ELSE
783                 {
784                         THROW(IOException, "invalid time format in certificate's notAfter field -- %s", t->data);
785                 }
786                 FINALLY
787                 {
788                         ASN1_STRING_free(t);
789                 }
790                 END_TRY;
791 #endif
792                 return deltadays > 0 ? deltadays : 0;
793         }
794         return -1;
795 }
796 
797 
798 char *Ssl_printOptions(SslOptions_T options, char *b, int size) {
799         ASSERT(b);
800         ASSERT(size > 0);
801         *b = 0;
802         if (options->flags) {
803                 int count = 0;
804                 if (options->version != -1) {
805                         int versions = 0;
806                         snprintf(b + strlen(b), size - strlen(b) - 1, "version: ");
807                         if (options->version & SSL_V2)
808                                 snprintf(b + strlen(b), size - strlen(b) - 1, "%sSSLv2", versions++ ? " " : "");
809                         if (options->version & SSL_V3)
810                                 snprintf(b + strlen(b), size - strlen(b) - 1, "%sSSLv3", versions++ ? " " : "");
811                         if (options->version & SSL_TLSV1)
812                                 snprintf(b + strlen(b), size - strlen(b) - 1, "%sTLSv1.0", versions++ ? " " : "");
813                         if (options->version & SSL_TLSV11)
814                                 snprintf(b + strlen(b), size - strlen(b) - 1, "%sTLSv1.1", versions++ ? " " : "");
815                         if (options->version & SSL_TLSV12)
816                                 snprintf(b + strlen(b), size - strlen(b) - 1, "%sTLSv1.2", versions++ ? " " : "");
817                         if (options->version & SSL_TLSV13)
818                                 snprintf(b + strlen(b), size - strlen(b) - 1, "%sTLSv1.3", versions++ ? " " : "");
819                         count++;
820                 }
821                 if (options->verify == true)
822                         snprintf(b + strlen(b), size - strlen(b) - 1, "%sverify: enable", count++ ? ", " : "");
823                 if (options->allowSelfSigned == true)
824                         snprintf(b + strlen(b), size - strlen(b) - 1, "%sselfsigned: allow", count++ ? ", " : "");
825                 if (options->pemfile)
826                         snprintf(b + strlen(b), size - strlen(b) - 1, "%spemfile: %s", count ++ ? ", " : "", options->pemfile);
827                 if (options->pemchain)
828                         snprintf(b + strlen(b), size - strlen(b) - 1, "%spemchain: %s", count ++ ? ", " : "", options->pemchain);
829                 if (options->pemkey)
830                         snprintf(b + strlen(b), size - strlen(b) - 1, "%spemkey: %s", count ++ ? ", " : "", options->pemkey);
831                 if (options->clientpemfile)
832                         snprintf(b + strlen(b), size - strlen(b) - 1, "%sclientpemfile: %s", count ++ ? ", " : "", options->clientpemfile);
833                 if (options->CACertificateFile)
834                         snprintf(b + strlen(b), size - strlen(b) - 1, "%sCACertificateFile: %s", count ++ ? ", " : "", options->CACertificateFile);
835                 if (options->CACertificatePath)
836                         snprintf(b + strlen(b), size - strlen(b) - 1, "%sCACertificatePath: %s", count ++ ? ", " : "", options->CACertificatePath);
837                 if (options->ciphers)
838                         snprintf(b + strlen(b), size - strlen(b) - 1, "%sciphers: \"%s\"", count ++ ? ", " : "", options->ciphers);
839         }
840         return b;
841 }
842 
843 
844 /* -------------------------------------------------------------- SSL Server */
845 
846 
847 SslServer_T SslServer_new(int socket, SslOptions_T options) {
848         ASSERT(socket >= 0);
849         ASSERT(options);
850         SslServer_T S;
851         NEW(S);
852         S->socket = socket;
853         S->options = options;
854 #if (OPENSSL_VERSION_NUMBER < 0x10100000L) || defined(LIBRESSL_VERSION_NUMBER)
855         const SSL_METHOD *method = SSLv23_server_method();
856 #else
857         const SSL_METHOD *method = TLS_server_method();
858 #endif
859         if (! method) {
860                 Log_error("SSL: server method initialization failed -- %s\n", SSLERROR);
861                 goto sslerror;
862         }
863         if (! (S->ctx = SSL_CTX_new(method))) {
864                 Log_error("SSL: server context initialization failed -- %s\n", SSLERROR);
865                 goto sslerror;
866         }
867         if (! _setVersion(S->ctx, options)) {
868                 goto sslerror;
869         }
870         if (SSL_CTX_set_session_id_context(S->ctx, (void *)&session_id_context, sizeof(session_id_context)) != 1) {
871                 Log_error("SSL: server session id context initialization failed -- %s\n", SSLERROR);
872                 goto sslerror;
873         }
874         const char *ciphers = _optionsCiphers(options->ciphers);
875         if (SSL_CTX_set_cipher_list(S->ctx, ciphers) != 1) {
876                 Log_error("SSL: server cipher list [%s] error -- no valid ciphers\n", ciphers);
877                 goto sslerror;
878         }
879         SSL_CTX_set_options(S->ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
880 #ifdef SSL_MODE_RELEASE_BUFFERS
881         SSL_CTX_set_mode(S->ctx, SSL_MODE_RELEASE_BUFFERS);
882 #endif
883 #ifdef SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
884         SSL_CTX_set_options(S->ctx, SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
885 #endif
886 #ifdef SSL_CTRL_SET_ECDH_AUTO
887         SSL_CTX_set_options(S->ctx, SSL_OP_SINGLE_ECDH_USE);
888         SSL_CTX_set_ecdh_auto(S->ctx, 1);
889 #elif defined HAVE_EC_KEY
890         SSL_CTX_set_options(S->ctx, SSL_OP_SINGLE_ECDH_USE);
891         EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
892         if (key) {
893                 SSL_CTX_set_tmp_ecdh(S->ctx, key);
894                 EC_KEY_free(key);
895         }
896 #endif
897         SSL_CTX_set_options(S->ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3);
898 #ifdef SSL_OP_NO_COMPRESSION
899         SSL_CTX_set_options(S->ctx, SSL_OP_NO_COMPRESSION);
900 #endif
901         SSL_CTX_set_session_cache_mode(S->ctx, SSL_SESS_CACHE_OFF);
902         const char *pemchain = _optionsServerPEMChain(options->pemchain);
903         const char *pemkey = _optionsServerPEMKey(options->pemkey);
904         const char *pemfile = _optionsServerPEMFile(options->pemfile);
905         if (SSL_CTX_use_certificate_chain_file(S->ctx, pemchain ? pemchain : pemfile) != 1) {
906                 Log_error("SSL: server certificate chain loading failed -- %s\n", SSLERROR);
907                 goto sslerror;
908         }
909         if (SSL_CTX_use_PrivateKey_file(S->ctx, pemkey ? pemkey : pemfile, SSL_FILETYPE_PEM) != 1) {
910                 Log_error("SSL: server private key loading failed -- %s\n", SSLERROR);
911                 goto sslerror;
912         }
913         if (SSL_CTX_check_private_key(S->ctx) != 1) {
914                 Log_error("SSL: server private key do not match the certificate -- %s\n", SSLERROR);
915                 goto sslerror;
916         }
917         const char *clientpemfile = _optionsClientPEMFile(options->clientpemfile);
918         if (clientpemfile) {
919                 struct stat sb;
920                 if (stat(clientpemfile, &sb) == -1) {
921                         Log_error("SSL: client PEM file %s error -- %s\n", clientpemfile, STRERROR);
922                         goto sslerror;
923                 }
924                 if (! S_ISREG(sb.st_mode)) {
925                         Log_error("SSL: client PEM file %s is not a file\n", clientpemfile);
926                         goto sslerror;
927                 }
928                 if (! SSL_CTX_load_verify_locations(S->ctx, clientpemfile, NULL)) {
929                         Log_error("SSL: client PEM file CA certificates %s loading failed -- %s\n", clientpemfile, SSLERROR);
930                         goto sslerror;
931                 }
932                 SSL_CTX_set_client_CA_list(S->ctx, SSL_load_client_CA_file(clientpemfile));
933                 if (! SSL_CTX_load_verify_locations(S->ctx, pemfile, NULL)) {
934                         Log_error("SSL: server certificate CA certificates %s loading failed -- %s\n", pemfile, SSLERROR);
935                         goto sslerror;
936                 }
937                 SSL_CTX_set_verify(S->ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, _verifyClientCertificates);
938         } else {
939                 SSL_CTX_set_verify(S->ctx, SSL_VERIFY_NONE, NULL);
940         }
941         return S;
942 sslerror:
943         SslServer_free(&S);
944         return NULL;
945 }
946 
947 
948 void SslServer_free(SslServer_T *S) {
949         ASSERT(S && *S);
950         if ((*S)->ctx)
951                 SSL_CTX_free((*S)->ctx);
952         FREE(*S);
953 }
954 
955 
956 T SslServer_newConnection(SslServer_T S) {
957         ASSERT(S);
958         T C;
959         NEW(C);
960         C->accepted = true;
961         C->ctx = S->ctx;
962         if (! (C->handler = SSL_new(C->ctx))) {
963                 Log_error("SSL: server cannot create handler -- %s\n", SSLERROR);
964                 Ssl_free(&C);
965                 return NULL;
966         }
967         SSL_set_mode(C->handler, SSL_MODE_ENABLE_PARTIAL_WRITE | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
968         C->options = S->options;
969         return C;
970 }
971 
972 
973 void SslServer_freeConnection(SslServer_T S, T *C) {
974         ASSERT(S);
975         ASSERT(C && *C);
976         Ssl_close(*C);
977         Ssl_free(C);
978 }
979 
980 
981 bool SslServer_accept(T C, int socket, int timeout) {
982         ASSERT(C);
983         ASSERT(socket >= 0);
984         C->socket = socket;
985         SSL_set_accept_state(C->handler);
986         SSL_set_fd(C->handler, C->socket);
987         bool retry = false;
988         do {
989                 int rv = SSL_accept(C->handler);
990                 if (rv < 0) {
991                         switch (SSL_get_error(C->handler, rv)) {
992                                 case SSL_ERROR_NONE:
993                                         break;
994                                 case SSL_ERROR_WANT_READ:
995                                         retry = _retry(C->socket, &timeout, Net_canRead);
996                                         break;
997                                 case SSL_ERROR_WANT_WRITE:
998                                         retry = _retry(C->socket, &timeout, Net_canWrite);
999                                         break;
1000                                 default:
1001                                         rv = (int)SSL_get_verify_result(C->handler);
1002                                         if (rv != X509_V_OK)
1003                                                 Log_error("SSL client certificate verification error: %s\n", *C->error ? C->error : X509_verify_cert_error_string(rv));
1004                                         else
1005                                                 Log_error("SSL accept error: %s\n", SSLERROR);
1006                                         return false;
1007                         }
1008                 } else {
1009                         break;
1010                 }
1011         } while (retry);
1012         return true;
1013 }
1014 
1015 #endif
1016