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