ee03fdaef91357e815791b9ffb43ef1962ab29e6
[citadel.git] / citadel / modules / crypto / serv_crypto.c
1 // Copyright (c) 1987-2022 by the citadel.org team
2 //
3 // This program is open source software; you can redistribute it and/or modify
4 // it under the terms of the GNU General Public License version 3.
5 //
6 // This program is distributed in the hope that it will be useful,
7 // but WITHOUT ANY WARRANTY; without even the implied warranty of
8 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
9 // GNU General Public License for more details.
10
11 #include <string.h>
12 #include <unistd.h>
13 #include <sys/stat.h>
14 #include <sys/types.h>
15 #include "sysdep.h"
16
17 #ifdef HAVE_OPENSSL
18 #include <openssl/ssl.h>
19 #include <openssl/err.h>
20 #include <openssl/rand.h>
21 #endif
22
23 #include <time.h>
24
25 #ifdef HAVE_PTHREAD_H
26 #include <pthread.h>
27 #endif
28
29 #ifdef HAVE_SYS_SELECT_H
30 #include <sys/select.h>
31 #endif
32
33 #include <stdio.h>
34 #include <libcitadel.h>
35 #include "server.h"
36 #include "serv_crypto.h"
37 #include "sysdep_decls.h"
38 #include "citadel.h"
39 #include "config.h"
40 #include "ctdl_module.h"
41
42 #ifdef HAVE_OPENSSL
43
44 SSL_CTX *ssl_ctx = NULL;                // This SSL context is used for all sessions.
45 char *ssl_cipher_list = CIT_CIPHERS;
46
47 // If a private key does not exist, generate one now.
48 void generate_key(char *keyfilename) {
49         int ret = 0;
50         RSA *rsa = NULL;
51         BIGNUM *bne = NULL;
52         int bits = 2048;
53         unsigned long e = RSA_F4;
54         FILE *fp;
55
56         if (access(keyfilename, R_OK) == 0) {   // Already have one.
57                 return;
58         }
59
60         syslog(LOG_INFO, "crypto: generating RSA key pair");
61  
62         // generate rsa key
63         bne = BN_new();
64         ret = BN_set_word(bne,e);
65         if (ret != 1) {
66                 goto free_all;
67         }
68  
69         rsa = RSA_new();
70         ret = RSA_generate_key_ex(rsa, bits, bne, NULL);
71         if (ret != 1) {
72                 goto free_all;
73         }
74
75         // write the key file
76         fp = fopen(keyfilename, "w");
77         if (fp != NULL) {
78                 chmod(keyfilename, 0600);
79                 if (PEM_write_RSAPrivateKey(fp, // the file
80                                         rsa,    // the key
81                                         NULL,   // no enc
82                                         NULL,   // no passphrase
83                                         0,      // no passphrase
84                                         NULL,   // no callback
85                                         NULL    // no callback
86                 ) != 1) {
87                         syslog(LOG_ERR, "crypto: cannot write key: %s", ERR_reason_error_string(ERR_get_error()));
88                         unlink(keyfilename);
89                 }
90                 fclose(fp);
91         }
92
93         // free the memory we used
94 free_all:
95         RSA_free(rsa);
96         BN_free(bne);
97 }
98
99
100 // If a certificate does not exist, generate a self-signed one now.
101 void generate_certificate(char *keyfilename, char *certfilename) {
102         RSA *private_key = NULL;
103         EVP_PKEY *public_key = NULL;
104         X509_REQ *certificate_signing_request = NULL;
105         X509_NAME *name = NULL;
106         X509 *certificate = NULL;
107         FILE *fp;
108
109         if (access(certfilename, R_OK) == 0) {                  // already have one.
110                 return;
111         }
112
113         syslog(LOG_INFO, "crypto: generating a self-signed certificate");
114
115         // Read in our private key.
116         fp = fopen(keyfilename, "r");
117         if (fp) {
118                 private_key = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
119                 fclose(fp);
120         }
121
122         if (!private_key) {
123                 syslog(LOG_ERR, "crypto: cannot read the private key");
124                 return;
125         }
126
127         // Create a public key from the private key
128         public_key = EVP_PKEY_new();
129         if (!public_key) {
130                 syslog(LOG_ERR, "crypto: cannot allocate public key");
131                 RSA_free(private_key);
132                 return;
133         }
134         EVP_PKEY_assign_RSA(public_key, private_key);
135
136         // Create a certificate signing request
137         certificate_signing_request = X509_REQ_new();
138         if (!certificate_signing_request) {
139                 syslog(LOG_ERR, "crypto: cannot allocate certificate signing request");
140                 RSA_free(private_key);
141                 EVP_PKEY_free(public_key);
142                 return;
143         }
144
145         // Assign the public key to the certificate signing request
146         X509_REQ_set_pubkey(certificate_signing_request, public_key);
147         X509_REQ_set_version(certificate_signing_request, 0L);
148
149         // Tell it who we are
150         name = X509_REQ_get_subject_name(certificate_signing_request);
151         X509_NAME_add_entry_by_txt(name, "C", MBSTRING_ASC, (unsigned const char *)"ZZ", -1, -1, 0);
152         X509_NAME_add_entry_by_txt(name, "ST", MBSTRING_ASC, (unsigned const char *)"The World", -1, -1, 0);
153         X509_NAME_add_entry_by_txt(name, "L", MBSTRING_ASC, (unsigned const char *)"My Location", -1, -1, 0);
154         X509_NAME_add_entry_by_txt(name, "O", MBSTRING_ASC, (unsigned const char *)"Generic certificate", -1, -1, 0);
155         X509_NAME_add_entry_by_txt(name, "OU", MBSTRING_ASC, (unsigned const char *)"Citadel server", -1, -1, 0);
156         X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC, (unsigned const char *)"*", -1, -1, 0);
157         X509_REQ_set_subject_name(certificate_signing_request, name);
158
159         // Sign the CSR
160         if (!X509_REQ_sign(certificate_signing_request, public_key, EVP_md5())) {
161                 syslog(LOG_ERR, "crypto: X509_REQ_sign(): error");
162                 X509_REQ_free(certificate_signing_request);
163                 RSA_free(private_key);
164                 EVP_PKEY_free(public_key);
165                 return;
166         }
167
168         // Generate the self-signed certificate
169         certificate = X509_new();
170         if (!certificate) {
171                 syslog(LOG_ERR, "crypto: cannot allocate X.509 certificate");
172                 X509_REQ_free(certificate_signing_request);
173                 RSA_free(private_key);
174                 EVP_PKEY_free(public_key);
175                 return;
176         }
177
178         ASN1_INTEGER_set(X509_get_serialNumber(certificate), 0);
179         X509_set_issuer_name(certificate, X509_REQ_get_subject_name(certificate_signing_request));
180         X509_set_subject_name(certificate, X509_REQ_get_subject_name(certificate_signing_request));
181         X509_gmtime_adj(X509_get_notBefore(certificate), 0);
182         X509_gmtime_adj(X509_get_notAfter(certificate), (long)60*60*24*SIGN_DAYS);
183         X509_set_pubkey(certificate, public_key);
184         X509_REQ_free(certificate_signing_request);             // We're done with the CSR; free it
185
186         // Finally, sign the certificate with our private key.
187         if (!X509_sign(certificate, public_key, EVP_md5())) {
188                 syslog(LOG_ERR, "crypto: X509_sign() error");
189                 X509_free(certificate);
190                 RSA_free(private_key);
191                 EVP_PKEY_free(public_key);
192                 return;
193         }
194
195         // Write the certificate to disk
196         fp = fopen(certfilename, "w");
197         if (fp != NULL) {
198                 chmod(certfilename, 0600);
199                 PEM_write_X509(fp, certificate);
200                 fclose(fp);
201         }
202         else {
203                 syslog(LOG_ERR, "crypto: %s: %m", certfilename);
204         }
205
206         X509_free(certificate);
207         EVP_PKEY_free(public_key);
208         // RSA_free(private_key);                               // private_key is freed by EVP_PKEY_free() above
209 }
210
211
212 // Set the private key and certificate chain for the global SSL Context.
213 // This is called during initialization, and can be called again later if the certificate changes.
214 void bind_to_key_and_certificate(void) {
215
216         SSL_CTX *old_ctx = NULL;
217         SSL_CTX *new_ctx = NULL;
218
219         if (!(new_ctx = SSL_CTX_new(TLS_server_method()))) {
220                 syslog(LOG_ERR, "crypto: SSL_CTX_new failed: %s", ERR_reason_error_string(ERR_get_error()));
221                 return;
222         }
223
224         if (!(SSL_CTX_set_cipher_list(new_ctx, ssl_cipher_list))) {
225                 syslog(LOG_ERR, "crypto: SSL_CTX_set_cipher_list failed: %s", ERR_reason_error_string(ERR_get_error()));
226                 return;
227         }
228
229         syslog(LOG_DEBUG, "crypto: using certificate chain %s", file_crpt_file_cer);
230         SSL_CTX_use_certificate_chain_file(new_ctx, file_crpt_file_cer);
231
232         syslog(LOG_DEBUG, "crypto: using private key %s", file_crpt_file_key);
233         SSL_CTX_use_PrivateKey_file(new_ctx, file_crpt_file_key, SSL_FILETYPE_PEM);
234
235         old_ctx = ssl_ctx;
236         ssl_ctx = new_ctx;              // All future binds will use the new certificate
237
238         if (old_ctx != NULL) {
239                 sleep(1);               // Hopefully wait until all in-progress binds to the old certificate have completed
240                 SSL_CTX_free(old_ctx);
241         }
242 }
243
244
245 // Check the modification time of the key and certificate files.  Reload if either one changed.
246 void update_key_and_cert_if_needed(void) {
247         static time_t previous_mtime = 0;
248         struct stat keystat;
249         struct stat certstat;
250
251         if (stat(file_crpt_file_key, &keystat) != 0) {
252                 syslog(LOG_ERR, "%s: %s", file_crpt_file_key, strerror(errno));
253                 return;
254         }
255         if (stat(file_crpt_file_cer, &certstat) != 0) {
256                 syslog(LOG_ERR, "%s: %s", file_crpt_file_cer, strerror(errno));
257                 return;
258         }
259
260         if ((keystat.st_mtime + certstat.st_mtime) != previous_mtime) {
261                 begin_critical_section(S_OPENSSL);
262                 bind_to_key_and_certificate();
263                 end_critical_section(S_OPENSSL);
264                 previous_mtime = keystat.st_mtime + certstat.st_mtime;
265         }
266 }
267
268
269 // Initialize the TLS subsystem.
270 void init_ssl(void) {
271
272         // Initialize the OpenSSL library
273         SSL_load_error_strings();
274         ERR_load_crypto_strings();
275         OpenSSL_add_all_algorithms();
276         SSL_library_init();
277
278         // Load (or generate) a key and certificate
279         mkdir(ctdl_key_dir, 0700);                                      // If the keys directory does not exist, create it
280         generate_key(file_crpt_file_key);                               // If a private key does not exist, create it
281         generate_certificate(file_crpt_file_key, file_crpt_file_cer);   // If a certificate does not exist, create it
282         bind_to_key_and_certificate();                                  // Load key and cert from disk, and bind to them.
283
284         // Register some Citadel protocol commands for dealing with encrypted sessions
285         CtdlRegisterProtoHook(cmd_stls, "STLS", "Start TLS session");
286         CtdlRegisterProtoHook(cmd_gtls, "GTLS", "Get TLS session status");
287         CtdlRegisterSessionHook(endtls, EVT_STOP, PRIO_STOP + 10);
288 }
289
290
291 // client_write_ssl() Send binary data to the client encrypted.
292 void client_write_ssl(const char *buf, int nbytes) {
293         int retval;
294         int nremain;
295         char junk[1];
296
297         nremain = nbytes;
298
299         while (nremain > 0) {
300                 if (SSL_want_write(CC->ssl)) {
301                         if ((SSL_read(CC->ssl, junk, 0)) < 1) {
302                                 syslog(LOG_DEBUG, "crypto: SSL_read in client_write: %s", ERR_reason_error_string(ERR_get_error()));
303                         }
304                 }
305                 retval =
306                     SSL_write(CC->ssl, &buf[nbytes - nremain], nremain);
307                 if (retval < 1) {
308                         long errval;
309
310                         errval = SSL_get_error(CC->ssl, retval);
311                         if (errval == SSL_ERROR_WANT_READ || errval == SSL_ERROR_WANT_WRITE) {
312                                 sleep(1);
313                                 continue;
314                         }
315                         syslog(LOG_DEBUG, "crypto: SSL_write got error %ld, ret %d", errval, retval);
316                         if (retval == -1) {
317                                 syslog(LOG_DEBUG, "crypto: errno is %d", errno);
318                         }
319                         endtls();
320                         client_write(&buf[nbytes - nremain], nremain);
321                         return;
322                 }
323                 nremain -= retval;
324         }
325 }
326
327
328 // read data from the encrypted layer.
329 int client_read_sslbuffer(StrBuf *buf, int timeout) {
330         char sbuf[16384];       // OpenSSL communicates in 16k blocks, so let's speak its native tongue.
331         int rlen;
332         char junk[1];
333         SSL *pssl = CC->ssl;
334
335         if (pssl == NULL) return(-1);
336
337         while (1) {
338                 if (SSL_want_read(pssl)) {
339                         if ((SSL_write(pssl, junk, 0)) < 1) {
340                                 syslog(LOG_DEBUG, "crypto: SSL_write in client_read");
341                         }
342                 }
343                 rlen = SSL_read(pssl, sbuf, sizeof(sbuf));
344                 if (rlen < 1) {
345                         long errval;
346
347                         errval = SSL_get_error(pssl, rlen);
348                         if (errval == SSL_ERROR_WANT_READ || errval == SSL_ERROR_WANT_WRITE) {
349                                 sleep(1);
350                                 continue;
351                         }
352                         syslog(LOG_DEBUG, "crypto: SSL_read got error %ld", errval);
353                         endtls();
354                         return (-1);
355                 }
356                 StrBufAppendBufPlain(buf, sbuf, rlen, 0);
357                 return rlen;
358         }
359         return (0);
360 }
361
362
363 int client_readline_sslbuffer(StrBuf *Line, StrBuf *IOBuf, const char **Pos, int timeout) {
364         const char *pos = NULL;
365         const char *pLF;
366         int len, rlen;
367         int nSuccessLess = 0;
368         const char *pch = NULL;
369         
370         if ((Line == NULL) || (Pos == NULL) || (IOBuf == NULL)) {
371                 if (Pos != NULL) {
372                         *Pos = NULL;
373                 }
374                 return -1;
375         }
376
377         pos = *Pos;
378         if ((StrLength(IOBuf) > 0) && (pos != NULL) && (pos < ChrPtr(IOBuf) + StrLength(IOBuf))) {
379                 pch = pos;
380                 pch = strchr(pch, '\n');
381                 
382                 if (pch == NULL) {
383                         StrBufAppendBufPlain(Line, pos, StrLength(IOBuf) - (pos - ChrPtr(IOBuf)), 0);
384                         FlushStrBuf(IOBuf);
385                         *Pos = NULL;
386                 }
387                 else {
388                         int n = 0;
389                         if ((pch > ChrPtr(IOBuf)) && (*(pch - 1) == '\r')) {
390                                 n = 1;
391                         }
392                         StrBufAppendBufPlain(Line, pos, (pch - pos - n), 0);
393
394                         if (StrLength(IOBuf) <= (pch - ChrPtr(IOBuf) + 1)) {
395                                 FlushStrBuf(IOBuf);
396                                 *Pos = NULL;
397                         }
398                         else {
399                                 *Pos = pch + 1;
400                         }
401                         return StrLength(Line);
402                 }
403         }
404
405         pLF = NULL;
406         while ((nSuccessLess < timeout) && (pLF == NULL) && (CC->ssl != NULL)) {
407
408                 rlen = client_read_sslbuffer(IOBuf, timeout);
409                 if (rlen < 1) {
410                         return -1;
411                 }
412                 else if (rlen > 0) {
413                         pLF = strchr(ChrPtr(IOBuf), '\n');
414                 }
415         }
416         *Pos = NULL;
417         if (pLF != NULL) {
418                 pos = ChrPtr(IOBuf);
419                 len = pLF - pos;
420                 if (len > 0 && (*(pLF - 1) == '\r') )
421                         len --;
422                 StrBufAppendBufPlain(Line, pos, len, 0);
423                 if (pLF + 1 >= ChrPtr(IOBuf) + StrLength(IOBuf)) {
424                         FlushStrBuf(IOBuf);
425                 }
426                 else  {
427                         *Pos = pLF + 1;
428                 }
429                 return StrLength(Line);
430         }
431         return -1;
432 }
433
434
435 int client_read_sslblob(StrBuf *Target, long bytes, int timeout) {
436         long baselen;
437         long RemainRead;
438         int retval = 0;
439
440         baselen = StrLength(Target);
441
442         if (StrLength(CC->RecvBuf.Buf) > 0) {
443                 long RemainLen;
444                 long TotalLen;
445                 const char *pchs;
446
447                 if (CC->RecvBuf.ReadWritePointer == NULL) {
448                         CC->RecvBuf.ReadWritePointer = ChrPtr(CC->RecvBuf.Buf);
449                 }
450                 pchs = ChrPtr(CC->RecvBuf.Buf);
451                 TotalLen = StrLength(CC->RecvBuf.Buf);
452                 RemainLen = TotalLen - (pchs - CC->RecvBuf.ReadWritePointer);
453                 if (RemainLen > bytes) {
454                         RemainLen = bytes;
455                 }
456                 if (RemainLen > 0) {
457                         StrBufAppendBufPlain(Target, CC->RecvBuf.ReadWritePointer, RemainLen, 0);
458                         CC->RecvBuf.ReadWritePointer += RemainLen;
459                 }
460                 if ((ChrPtr(CC->RecvBuf.Buf) + StrLength(CC->RecvBuf.Buf)) <= CC->RecvBuf.ReadWritePointer) {
461                         CC->RecvBuf.ReadWritePointer = NULL;
462                         FlushStrBuf(CC->RecvBuf.Buf);
463                 }
464         }
465
466         if (StrLength(Target) >= bytes + baselen) {
467                 return 1;
468         }
469
470         CC->RecvBuf.ReadWritePointer = NULL;
471
472         while ((StrLength(Target) < bytes + baselen) && (retval >= 0)) {
473                 retval = client_read_sslbuffer(CC->RecvBuf.Buf, timeout);
474                 if (retval >= 0) {
475                         RemainRead = bytes - (StrLength (Target) - baselen);
476                         if (RemainRead < StrLength(CC->RecvBuf.Buf)) {
477                                 StrBufAppendBufPlain(
478                                         Target, 
479                                         ChrPtr(CC->RecvBuf.Buf), 
480                                         RemainRead, 0);
481                                 CC->RecvBuf.ReadWritePointer = ChrPtr(CC->RecvBuf.Buf) + RemainRead;
482                                 break;
483                         }
484                         StrBufAppendBuf(Target, CC->RecvBuf.Buf, 0);
485                         FlushStrBuf(CC->RecvBuf.Buf);
486                 }
487                 else {
488                         FlushStrBuf(CC->RecvBuf.Buf);
489                         return -1;
490         
491                 }
492         }
493         return 1;
494 }
495
496
497 // CtdlStartTLS() starts TLS encryption for the current session.  It
498 // must be supplied with pre-generated strings for responses of "ok," "no
499 // support for TLS," and "error" so that we can use this in any protocol.
500 void CtdlStartTLS(char *ok_response, char *nosup_response, char *error_response) {
501         int retval, bits, alg_bits;
502
503         if (CC->redirect_ssl) {
504                 syslog(LOG_ERR, "crypto: attempt to begin SSL on an already encrypted connection");
505                 if (error_response != NULL) {
506                         cprintf("%s", error_response);
507                 }
508                 return;
509         }
510
511         if (!ssl_ctx) {
512                 syslog(LOG_ERR, "crypto: SSL failed: context has not been initialized");
513                 if (nosup_response != NULL) {
514                         cprintf("%s", nosup_response);
515                 }
516                 return;
517         }
518
519         update_key_and_cert_if_needed();                // did someone update the key or cert?  if so, re-bind them
520
521         if (!(CC->ssl = SSL_new(ssl_ctx))) {
522                 syslog(LOG_ERR, "crypto: SSL_new failed: %s", ERR_reason_error_string(ERR_get_error()));
523                 if (error_response != NULL) {
524                         cprintf("%s", error_response);
525                 }
526                 return;
527         }
528         if (!(SSL_set_fd(CC->ssl, CC->client_socket))) {
529                 syslog(LOG_ERR, "crypto: SSL_set_fd failed: %s", ERR_reason_error_string(ERR_get_error()));
530                 SSL_free(CC->ssl);
531                 CC->ssl = NULL;
532                 if (error_response != NULL) {
533                         cprintf("%s", error_response);
534                 }
535                 return;
536         }
537         if (ok_response != NULL) {
538                 cprintf("%s", ok_response);
539         }
540         retval = SSL_accept(CC->ssl);
541         if (retval < 1) {
542                 // Can't notify the client of an error here; they will
543                 // discover the problem at the SSL layer and should
544                 // revert to unencrypted communications.
545                 syslog(LOG_ERR, "crypto: SSL_accept failed: %s", ERR_reason_error_string(ERR_get_error()));
546                 SSL_free(CC->ssl);
547                 CC->ssl = NULL;
548                 return;
549         }
550         bits = SSL_CIPHER_get_bits(SSL_get_current_cipher(CC->ssl), &alg_bits);
551         syslog(LOG_INFO, "crypto: TLS using %s on %s (%d of %d bits)",
552                 SSL_CIPHER_get_name(SSL_get_current_cipher(CC->ssl)),
553                 SSL_CIPHER_get_version(SSL_get_current_cipher(CC->ssl)),
554                 bits, alg_bits
555         );
556         CC->redirect_ssl = 1;
557 }
558
559
560 // cmd_stls() starts TLS encryption for the current session
561 void cmd_stls(char *params) {
562         char ok_response[SIZ];
563         char nosup_response[SIZ];
564         char error_response[SIZ];
565
566         unbuffer_output();
567
568         sprintf(ok_response, "%d Begin TLS negotiation now\n", CIT_OK);
569         sprintf(nosup_response, "%d TLS not supported here\n", ERROR + CMD_NOT_SUPPORTED);
570         sprintf(error_response, "%d TLS negotiation error\n", ERROR + INTERNAL_ERROR);
571
572         CtdlStartTLS(ok_response, nosup_response, error_response);
573 }
574
575
576 // cmd_gtls() returns status info about the TLS connection
577 void cmd_gtls(char *params) {
578         int bits, alg_bits;
579
580         if (!CC->ssl || !CC->redirect_ssl) {
581                 cprintf("%d Session is not encrypted.\n", ERROR);
582                 return;
583         }
584         bits = SSL_CIPHER_get_bits(SSL_get_current_cipher(CC->ssl), &alg_bits);
585         cprintf("%d %s|%s|%d|%d\n", CIT_OK,
586                 SSL_CIPHER_get_version(SSL_get_current_cipher(CC->ssl)),
587                 SSL_CIPHER_get_name(SSL_get_current_cipher(CC->ssl)),
588                 alg_bits, bits);
589 }
590
591
592 // endtls() shuts down the TLS connection
593 void endtls(void) {
594         if (!CC->ssl) {
595                 CC->redirect_ssl = 0;
596                 return;
597         }
598
599         syslog(LOG_INFO, "crypto: ending TLS on this session");
600         SSL_shutdown(CC->ssl);
601         SSL_free(CC->ssl);
602         CC->ssl = NULL;
603         CC->redirect_ssl = 0;
604 }
605
606 #endif  // HAVE_OPENSSL