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