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.
8 #include "../../sysdep.h"
10 #include <openssl/ssl.h>
11 #include <openssl/err.h>
12 #include <openssl/rand.h>
20 #ifdef HAVE_SYS_SELECT_H
21 #include <sys/select.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"
33 SSL_CTX *ssl_ctx = NULL; // This SSL context is used for all sessions.
34 char *ssl_cipher_list = CIT_CIPHERS;
36 // If a private key does not exist, generate one now.
37 void generate_key(char *keyfilename) {
42 unsigned long e = RSA_F4;
45 if (access(keyfilename, R_OK) == 0) { // Already have one.
46 syslog(LOG_INFO, "crypto: %s exists and is readable", keyfilename);
50 syslog(LOG_INFO, "crypto: generating RSA key pair");
54 ret = BN_set_word(bne,e);
60 ret = RSA_generate_key_ex(rsa, bits, bne, NULL);
66 fp = fopen(keyfilename, "w");
68 chmod(keyfilename, 0600);
69 if (PEM_write_RSAPrivateKey(fp, // the file
72 NULL, // no passphrase
77 syslog(LOG_ERR, "crypto: cannot write key: %s", ERR_reason_error_string(ERR_get_error()));
83 // free the memory we used
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;
99 if (access(certfilename, R_OK) == 0) { // already have one.
100 syslog(LOG_INFO, "crypto: %s exists and is readable", certfilename);
104 syslog(LOG_INFO, "crypto: generating a self-signed certificate");
106 // Read in our private key.
107 fp = fopen(keyfilename, "r");
109 private_key = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
114 syslog(LOG_ERR, "crypto: cannot read the private key");
118 // Create a public key from the private key
119 public_key = EVP_PKEY_new();
121 syslog(LOG_ERR, "crypto: cannot allocate public key");
122 RSA_free(private_key);
125 EVP_PKEY_assign_RSA(public_key, private_key);
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);
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);
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);
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);
160 // Generate the self-signed certificate
161 certificate = X509_new();
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);
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
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);
187 // Write the certificate to disk
188 fp = fopen(certfilename, "w");
190 chmod(certfilename, 0600);
191 PEM_write_X509(fp, certificate);
195 syslog(LOG_ERR, "crypto: %s: %m", certfilename);
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
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) {
208 SSL_CTX *old_ctx = NULL;
209 SSL_CTX *new_ctx = NULL;
211 const SSL_METHOD *method = SSLv23_server_method();
213 syslog(LOG_ERR, "crypto: SSLv23_server_method() failed: %s", ERR_reason_error_string(ERR_get_error()));
217 new_ctx = SSL_CTX_new(method);
219 syslog(LOG_ERR, "crypto: SSL_CTX_new failed: %s", ERR_reason_error_string(ERR_get_error()));
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()));
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()));
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()));
241 ssl_ctx = new_ctx; // All future binds will use the new certificate
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);
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;
254 struct stat certstat;
256 if (stat(file_crpt_file_key, &keystat) != 0) {
257 syslog(LOG_ERR, "%s: %s", file_crpt_file_key, strerror(errno));
260 if (stat(file_crpt_file_cer, &certstat) != 0) {
261 syslog(LOG_ERR, "%s: %s", file_crpt_file_cer, strerror(errno));
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;
274 // Initialize the TLS subsystem.
275 void init_ssl(void) {
277 // Initialize the OpenSSL library
279 SSL_load_error_strings();
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.
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);
294 // client_write_ssl() Send binary data to the client encrypted.
295 void client_write_ssl(const char *buf, int nbytes) {
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()));
309 SSL_write(CC->ssl, &buf[nbytes - nremain], nremain);
313 errval = SSL_get_error(CC->ssl, retval);
314 if (errval == SSL_ERROR_WANT_READ || errval == SSL_ERROR_WANT_WRITE) {
318 syslog(LOG_DEBUG, "crypto: SSL_write got error %ld, ret %d", errval, retval);
320 syslog(LOG_DEBUG, "crypto: errno is %d", errno);
323 client_write(&buf[nbytes - nremain], nremain);
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.
338 if (pssl == NULL) return(-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");
346 rlen = SSL_read(pssl, sbuf, sizeof(sbuf));
350 errval = SSL_get_error(pssl, rlen);
351 if (errval == SSL_ERROR_WANT_READ || errval == SSL_ERROR_WANT_WRITE) {
355 syslog(LOG_DEBUG, "crypto: SSL_read got error %ld", errval);
359 StrBufAppendBufPlain(buf, sbuf, rlen, 0);
366 int client_readline_sslbuffer(StrBuf *Line, StrBuf *IOBuf, const char **Pos, int timeout) {
367 const char *pos = NULL;
370 int nSuccessLess = 0;
371 const char *pch = NULL;
373 if ((Line == NULL) || (Pos == NULL) || (IOBuf == NULL)) {
381 if ((StrLength(IOBuf) > 0) && (pos != NULL) && (pos < ChrPtr(IOBuf) + StrLength(IOBuf))) {
383 pch = strchr(pch, '\n');
386 StrBufAppendBufPlain(Line, pos, StrLength(IOBuf) - (pos - ChrPtr(IOBuf)), 0);
392 if ((pch > ChrPtr(IOBuf)) && (*(pch - 1) == '\r')) {
395 StrBufAppendBufPlain(Line, pos, (pch - pos - n), 0);
397 if (StrLength(IOBuf) <= (pch - ChrPtr(IOBuf) + 1)) {
404 return StrLength(Line);
409 while ((nSuccessLess < timeout) && (pLF == NULL) && (CC->ssl != NULL)) {
411 rlen = client_read_sslbuffer(IOBuf, timeout);
416 pLF = strchr(ChrPtr(IOBuf), '\n');
423 if (len > 0 && (*(pLF - 1) == '\r') )
425 StrBufAppendBufPlain(Line, pos, len, 0);
426 if (pLF + 1 >= ChrPtr(IOBuf) + StrLength(IOBuf)) {
432 return StrLength(Line);
438 int client_read_sslblob(StrBuf *Target, long bytes, int timeout) {
443 baselen = StrLength(Target);
445 if (StrLength(CC->RecvBuf.Buf) > 0) {
450 if (CC->RecvBuf.ReadWritePointer == NULL) {
451 CC->RecvBuf.ReadWritePointer = ChrPtr(CC->RecvBuf.Buf);
453 pchs = ChrPtr(CC->RecvBuf.Buf);
454 TotalLen = StrLength(CC->RecvBuf.Buf);
455 RemainLen = TotalLen - (pchs - CC->RecvBuf.ReadWritePointer);
456 if (RemainLen > bytes) {
460 StrBufAppendBufPlain(Target, CC->RecvBuf.ReadWritePointer, RemainLen, 0);
461 CC->RecvBuf.ReadWritePointer += RemainLen;
463 if ((ChrPtr(CC->RecvBuf.Buf) + StrLength(CC->RecvBuf.Buf)) <= CC->RecvBuf.ReadWritePointer) {
464 CC->RecvBuf.ReadWritePointer = NULL;
465 FlushStrBuf(CC->RecvBuf.Buf);
469 if (StrLength(Target) >= bytes + baselen) {
473 CC->RecvBuf.ReadWritePointer = NULL;
475 while ((StrLength(Target) < bytes + baselen) && (retval >= 0)) {
476 retval = client_read_sslbuffer(CC->RecvBuf.Buf, timeout);
478 RemainRead = bytes - (StrLength (Target) - baselen);
479 if (RemainRead < StrLength(CC->RecvBuf.Buf)) {
480 StrBufAppendBufPlain(
482 ChrPtr(CC->RecvBuf.Buf),
484 CC->RecvBuf.ReadWritePointer = ChrPtr(CC->RecvBuf.Buf) + RemainRead;
487 StrBufAppendBuf(Target, CC->RecvBuf.Buf, 0);
488 FlushStrBuf(CC->RecvBuf.Buf);
491 FlushStrBuf(CC->RecvBuf.Buf);
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;
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);
515 syslog(LOG_ERR, "crypto: SSL failed: ../../context.has not been initialized");
516 if (nosup_response != NULL) {
517 cprintf("%s", nosup_response);
522 update_key_and_cert_if_needed(); // did someone update the key or cert? if so, re-bind them
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);
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()));
535 if (error_response != NULL) {
536 cprintf("%s", error_response);
540 if (ok_response != NULL) {
541 cprintf("%s", ok_response);
543 retval = SSL_accept(CC->ssl);
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()));
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)),
559 CC->redirect_ssl = 1;
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];
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);
575 CtdlStartTLS(ok_response, nosup_response, error_response);
579 // cmd_gtls() returns status info about the TLS connection
580 void cmd_gtls(char *params) {
583 if (!CC->ssl || !CC->redirect_ssl) {
584 cprintf("%d Session is not encrypted.\n", ERROR);
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)),
595 // endtls() shuts down the TLS connection
598 CC->redirect_ssl = 0;
602 syslog(LOG_INFO, "crypto: ending TLS on this session");
603 SSL_shutdown(CC->ssl);
606 CC->redirect_ssl = 0;