1 // Copyright (c) 1987-2022 by the citadel.org team
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.
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.
14 #include <sys/types.h>
18 #include <openssl/ssl.h>
19 #include <openssl/err.h>
20 #include <openssl/rand.h>
29 #ifdef HAVE_SYS_SELECT_H
30 #include <sys/select.h>
34 #include <libcitadel.h>
36 #include "serv_crypto.h"
37 #include "sysdep_decls.h"
40 #include "ctdl_module.h"
44 SSL_CTX *ssl_ctx = NULL; // This SSL context is used for all sessions.
47 // If a private key does not exist, generate one now.
48 void generate_key(char *keyfilename) {
53 unsigned long e = RSA_F4;
56 if (access(keyfilename, R_OK) == 0) { // Already have one.
60 syslog(LOG_INFO, "crypto: generating RSA key pair");
64 ret = BN_set_word(bne,e);
70 ret = RSA_generate_key_ex(rsa, bits, bne, NULL);
76 fp = fopen(keyfilename, "w");
78 chmod(keyfilename, 0600);
79 if (PEM_write_RSAPrivateKey(fp, // the file
82 NULL, // no passphrase
87 syslog(LOG_ERR, "crypto: cannot write key: %s", ERR_reason_error_string(ERR_get_error()));
93 // free the memory we used
100 // If a certificate does not exist, generate a self-signed one now.
101 void generate_certificate(char *keyfilename, char *certfilename) {
102 RSA *private_key = NULL;
103 EVP_PKEY *public_key = NULL;
104 X509_REQ *certificate_signing_request = NULL;
105 X509_NAME *name = NULL;
106 X509 *certificate = NULL;
109 if (access(certfilename, R_OK) == 0) { // already have one.
113 syslog(LOG_INFO, "crypto: generating a self-signed certificate");
115 // Read in our private key.
116 fp = fopen(keyfilename, "r");
118 private_key = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
123 syslog(LOG_ERR, "crypto: cannot read the private key");
127 // Create a public key from the private key
128 public_key = EVP_PKEY_new();
130 syslog(LOG_ERR, "crypto: cannot allocate public key");
131 RSA_free(private_key);
134 EVP_PKEY_assign_RSA(public_key, private_key);
136 // Create a certificate signing request
137 certificate_signing_request = X509_REQ_new();
138 if (!certificate_signing_request) {
139 syslog(LOG_ERR, "crypto: cannot allocate certificate signing request");
140 RSA_free(private_key);
141 EVP_PKEY_free(public_key);
145 // Assign the public key to the certificate signing request
146 X509_REQ_set_pubkey(certificate_signing_request, public_key);
147 X509_REQ_set_version(certificate_signing_request, 0L);
149 // Tell it who we are
150 name = X509_REQ_get_subject_name(certificate_signing_request);
151 X509_NAME_add_entry_by_txt(name, "C", MBSTRING_ASC, (unsigned const char *)"ZZ", -1, -1, 0);
152 X509_NAME_add_entry_by_txt(name, "ST", MBSTRING_ASC, (unsigned const char *)"The World", -1, -1, 0);
153 X509_NAME_add_entry_by_txt(name, "L", MBSTRING_ASC, (unsigned const char *)"My Location", -1, -1, 0);
154 X509_NAME_add_entry_by_txt(name, "O", MBSTRING_ASC, (unsigned const char *)"Generic certificate", -1, -1, 0);
155 X509_NAME_add_entry_by_txt(name, "OU", MBSTRING_ASC, (unsigned const char *)"Citadel server", -1, -1, 0);
156 X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC, (unsigned const char *)"*", -1, -1, 0);
157 X509_REQ_set_subject_name(certificate_signing_request, name);
160 if (!X509_REQ_sign(certificate_signing_request, public_key, EVP_md5())) {
161 syslog(LOG_ERR, "crypto: X509_REQ_sign(): error");
162 X509_REQ_free(certificate_signing_request);
163 RSA_free(private_key);
164 EVP_PKEY_free(public_key);
168 // Generate the self-signed certificate
169 certificate = X509_new();
171 syslog(LOG_ERR, "crypto: cannot allocate X.509 certificate");
172 X509_REQ_free(certificate_signing_request);
173 RSA_free(private_key);
174 EVP_PKEY_free(public_key);
178 ASN1_INTEGER_set(X509_get_serialNumber(certificate), 0);
179 X509_set_issuer_name(certificate, X509_REQ_get_subject_name(certificate_signing_request));
180 X509_set_subject_name(certificate, X509_REQ_get_subject_name(certificate_signing_request));
181 X509_gmtime_adj(X509_get_notBefore(certificate), 0);
182 X509_gmtime_adj(X509_get_notAfter(certificate), (long)60*60*24*SIGN_DAYS);
183 X509_set_pubkey(certificate, public_key);
184 X509_REQ_free(certificate_signing_request); // We're done with the CSR; free it
186 // Finally, sign the certificate with our private key.
187 if (!X509_sign(certificate, public_key, EVP_md5())) {
188 syslog(LOG_ERR, "crypto: X509_sign() error");
189 X509_free(certificate);
190 RSA_free(private_key);
191 EVP_PKEY_free(public_key);
195 // Write the certificate to disk
196 fp = fopen(certfilename, "w");
198 chmod(certfilename, 0600);
199 PEM_write_X509(fp, certificate);
203 syslog(LOG_ERR, "crypto: %s: %m", certfilename);
206 X509_free(certificate);
207 EVP_PKEY_free(public_key);
208 // RSA_free(private_key); // private_key is freed by EVP_PKEY_free() above
212 // Set the private key and certificate chain for the global SSL Context.
213 // This is called during initialization, and can be called again later if the certificate changes.
214 void bind_to_key_and_certificate(void) {
216 SSL_CTX *old_ctx, *new_ctx;
218 if (!(new_ctx = SSL_CTX_new(TLS_server_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, CIT_CIPHERS))) {
224 syslog(LOG_ERR, "crypto: No ciphers available");
225 SSL_CTX_free(new_ctx);
230 syslog(LOG_DEBUG, "crypto: using certificate chain %s", file_crpt_file_cer);
231 SSL_CTX_use_certificate_chain_file(new_ctx, file_crpt_file_cer);
233 syslog(LOG_DEBUG, "crypto: using private key %s", file_crpt_file_key);
234 SSL_CTX_use_PrivateKey_file(new_ctx, file_crpt_file_key, SSL_FILETYPE_PEM);
235 if ( !SSL_CTX_check_private_key(new_ctx) ) {
236 syslog(LOG_ERR, "crypto: cannot install certificate: %s", ERR_reason_error_string(ERR_get_error()));
240 ssl_ctx = new_ctx; // All future binds will use the new certificate
242 sleep(1); // Hopefully wait until all in-progress binds to the old certificate have completed
243 SSL_CTX_free(old_ctx);
247 // Check the modification time of the key and certificate files. Reload if either one changed.
248 void update_key_and_cert_if_needed(void) {
249 static time_t previous_mtime = 0;
251 struct stat certstat;
253 if (stat(file_crpt_file_key, &keystat) != 0) {
254 syslog(LOG_ERR, "%s: %s", file_crpt_file_key, strerror(errno));
257 if (stat(file_crpt_file_cer, &certstat) != 0) {
258 syslog(LOG_ERR, "%s: %s", file_crpt_file_cer, strerror(errno));
262 if ((keystat.st_mtime + certstat.st_mtime) != previous_mtime) {
263 bind_to_key_and_certificate();
264 previous_mtime = keystat.st_mtime + certstat.st_mtime;
269 // Initialize the SSL/TLS subsystem.
270 void init_ssl(void) {
271 SSL_library_init(); // Initialize SSL transport layer
272 SSL_load_error_strings();
274 mkdir(ctdl_key_dir, 0700); // If the keys directory does not exist, create it
275 generate_key(file_crpt_file_key); // If a private key does not exist, create it
276 generate_certificate(file_crpt_file_key, file_crpt_file_cer); // If a certificate does not exist, create it
277 bind_to_key_and_certificate(); // Load key and cert from disk, and bind to them.
279 // Finally let the server know we're here
280 CtdlRegisterProtoHook(cmd_stls, "STLS", "Start SSL/TLS session");
281 CtdlRegisterProtoHook(cmd_gtls, "GTLS", "Get SSL/TLS session status");
282 CtdlRegisterSessionHook(endtls, EVT_STOP, PRIO_STOP + 10);
286 // client_write_ssl() Send binary data to the client encrypted.
287 void client_write_ssl(const char *buf, int nbytes) {
294 while (nremain > 0) {
295 if (SSL_want_write(CC->ssl)) {
296 if ((SSL_read(CC->ssl, junk, 0)) < 1) {
297 syslog(LOG_DEBUG, "crypto: SSL_read in client_write: %s", ERR_reason_error_string(ERR_get_error()));
301 SSL_write(CC->ssl, &buf[nbytes - nremain], nremain);
305 errval = SSL_get_error(CC->ssl, retval);
306 if (errval == SSL_ERROR_WANT_READ ||
307 errval == SSL_ERROR_WANT_WRITE) {
311 syslog(LOG_DEBUG, "crypto: SSL_write got error %ld, ret %d", errval, retval);
313 syslog(LOG_DEBUG, "crypto: errno is %d", errno);
316 client_write(&buf[nbytes - nremain], nremain);
324 // read data from the encrypted layer.
325 int client_read_sslbuffer(StrBuf *buf, int timeout) {
326 char sbuf[16384]; // OpenSSL communicates in 16k blocks, so let's speak its native tongue.
331 if (pssl == NULL) return(-1);
334 if (SSL_want_read(pssl)) {
335 if ((SSL_write(pssl, junk, 0)) < 1) {
336 syslog(LOG_DEBUG, "crypto: SSL_write in client_read");
339 rlen = SSL_read(pssl, sbuf, sizeof(sbuf));
343 errval = SSL_get_error(pssl, rlen);
344 if (errval == SSL_ERROR_WANT_READ || errval == SSL_ERROR_WANT_WRITE) {
348 syslog(LOG_DEBUG, "crypto: SSL_read got error %ld", errval);
352 StrBufAppendBufPlain(buf, sbuf, rlen, 0);
359 int client_readline_sslbuffer(StrBuf *Line, StrBuf *IOBuf, const char **Pos, int timeout) {
360 const char *pos = NULL;
363 int nSuccessLess = 0;
364 const char *pch = NULL;
366 if ((Line == NULL) || (Pos == NULL) || (IOBuf == NULL)) {
374 if ((StrLength(IOBuf) > 0) && (pos != NULL) && (pos < ChrPtr(IOBuf) + StrLength(IOBuf))) {
376 pch = strchr(pch, '\n');
379 StrBufAppendBufPlain(Line, pos, StrLength(IOBuf) - (pos - ChrPtr(IOBuf)), 0);
385 if ((pch > ChrPtr(IOBuf)) &&
386 (*(pch - 1) == '\r')) {
389 StrBufAppendBufPlain(Line, pos,
392 if (StrLength(IOBuf) <= (pch - ChrPtr(IOBuf) + 1)) {
398 return StrLength(Line);
403 while ((nSuccessLess < timeout) &&
407 rlen = client_read_sslbuffer(IOBuf, timeout);
412 pLF = strchr(ChrPtr(IOBuf), '\n');
419 if (len > 0 && (*(pLF - 1) == '\r') )
421 StrBufAppendBufPlain(Line, pos, len, 0);
422 if (pLF + 1 >= ChrPtr(IOBuf) + StrLength(IOBuf))
428 return StrLength(Line);
434 int client_read_sslblob(StrBuf *Target, long bytes, int timeout) {
439 baselen = StrLength(Target);
441 if (StrLength(CC->RecvBuf.Buf) > 0) {
446 if (CC->RecvBuf.ReadWritePointer == NULL) {
447 CC->RecvBuf.ReadWritePointer = ChrPtr(CC->RecvBuf.Buf);
449 pchs = ChrPtr(CC->RecvBuf.Buf);
450 TotalLen = StrLength(CC->RecvBuf.Buf);
451 RemainLen = TotalLen - (pchs - CC->RecvBuf.ReadWritePointer);
452 if (RemainLen > bytes) {
456 StrBufAppendBufPlain(Target, CC->RecvBuf.ReadWritePointer, RemainLen, 0);
457 CC->RecvBuf.ReadWritePointer += RemainLen;
459 if ((ChrPtr(CC->RecvBuf.Buf) + StrLength(CC->RecvBuf.Buf)) <= CC->RecvBuf.ReadWritePointer) {
460 CC->RecvBuf.ReadWritePointer = NULL;
461 FlushStrBuf(CC->RecvBuf.Buf);
465 if (StrLength(Target) >= bytes + baselen) {
469 CC->RecvBuf.ReadWritePointer = NULL;
471 while ((StrLength(Target) < bytes + baselen) && (retval >= 0)) {
472 retval = client_read_sslbuffer(CC->RecvBuf.Buf, timeout);
474 RemainRead = bytes - (StrLength (Target) - baselen);
475 if (RemainRead < StrLength(CC->RecvBuf.Buf)) {
476 StrBufAppendBufPlain(
478 ChrPtr(CC->RecvBuf.Buf),
480 CC->RecvBuf.ReadWritePointer = ChrPtr(CC->RecvBuf.Buf) + RemainRead;
483 StrBufAppendBuf(Target, CC->RecvBuf.Buf, 0); // todo: Buf > bytes?
484 FlushStrBuf(CC->RecvBuf.Buf);
487 FlushStrBuf(CC->RecvBuf.Buf);
496 // CtdlStartTLS() starts SSL/TLS encryption for the current session. It
497 // must be supplied with pre-generated strings for responses of "ok," "no
498 // support for TLS," and "error" so that we can use this in any protocol.
499 void CtdlStartTLS(char *ok_response, char *nosup_response, char *error_response) {
500 int retval, bits, alg_bits;
502 if (CC->redirect_ssl) {
503 syslog(LOG_ERR, "crypto: attempt to begin SSL on an already encrypted connection");
504 if (error_response != NULL) {
505 cprintf("%s", error_response);
511 syslog(LOG_ERR, "crypto: SSL failed: context has not been initialized");
512 if (nosup_response != NULL) {
513 cprintf("%s", nosup_response);
518 update_key_and_cert_if_needed(); // did someone update the key or cert? if so, re-bind them
520 if (!(CC->ssl = SSL_new(ssl_ctx))) {
521 syslog(LOG_ERR, "crypto: SSL_new failed: %s", ERR_reason_error_string(ERR_get_error()));
522 if (error_response != NULL) {
523 cprintf("%s", error_response);
527 if (!(SSL_set_fd(CC->ssl, CC->client_socket))) {
528 syslog(LOG_ERR, "crypto: SSL_set_fd failed: %s", ERR_reason_error_string(ERR_get_error()));
531 if (error_response != NULL) {
532 cprintf("%s", error_response);
536 if (ok_response != NULL) {
537 cprintf("%s", ok_response);
539 retval = SSL_accept(CC->ssl);
541 // Can't notify the client of an error here; they will
542 // discover the problem at the SSL layer and should
543 // revert to unencrypted communications.
545 char error_string[128];
547 errval = SSL_get_error(CC->ssl, retval);
548 syslog(LOG_ERR, "crypto: SSL_accept failed: retval=%d, errval=%ld, err=%s",
551 ERR_error_string(errval, error_string)
557 bits = SSL_CIPHER_get_bits(SSL_get_current_cipher(CC->ssl), &alg_bits);
558 syslog(LOG_INFO, "crypto: SSL/TLS using %s on %s (%d of %d bits)",
559 SSL_CIPHER_get_name(SSL_get_current_cipher(CC->ssl)),
560 SSL_CIPHER_get_version(SSL_get_current_cipher(CC->ssl)),
563 CC->redirect_ssl = 1;
567 // cmd_stls() starts SSL/TLS encryption for the current session
568 void cmd_stls(char *params) {
569 char ok_response[SIZ];
570 char nosup_response[SIZ];
571 char error_response[SIZ];
575 sprintf(ok_response, "%d Begin TLS negotiation now\n", CIT_OK);
576 sprintf(nosup_response, "%d TLS not supported here\n", ERROR + CMD_NOT_SUPPORTED);
577 sprintf(error_response, "%d TLS negotiation error\n", ERROR + INTERNAL_ERROR);
579 CtdlStartTLS(ok_response, nosup_response, error_response);
583 // cmd_gtls() returns status info about the TLS connection
584 void cmd_gtls(char *params) {
587 if (!CC->ssl || !CC->redirect_ssl) {
588 cprintf("%d Session is not encrypted.\n", ERROR);
592 SSL_CIPHER_get_bits(SSL_get_current_cipher(CC->ssl),
594 cprintf("%d %s|%s|%d|%d\n", CIT_OK,
595 SSL_CIPHER_get_version(SSL_get_current_cipher(CC->ssl)),
596 SSL_CIPHER_get_name(SSL_get_current_cipher(CC->ssl)),
601 // endtls() shuts down the TLS connection
603 // WARNING: This may make your session vulnerable to a known plaintext
604 // attack in the current implmentation.
607 CC->redirect_ssl = 0;
611 syslog(LOG_INFO, "crypto: ending SSL/TLS");
612 SSL_shutdown(CC->ssl);
615 CC->redirect_ssl = 0;
618 #endif // HAVE_OPENSSL