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