1 // Copyright (c) 1987-2021 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"
42 #include "ctdl_module.h"
45 SSL_CTX *ssl_ctx; /* SSL context */
46 pthread_mutex_t **SSLCritters; /* Things needing locking */
49 static unsigned long id_callback(void) {
50 return (unsigned long) pthread_self();
54 void destruct_ssl(void) {
56 for (a = 0; a < CRYPTO_num_locks(); a++)
62 void generate_key(char *keyfilename) {
67 unsigned long e = RSA_F4;
70 if (access(keyfilename, R_OK) == 0) {
74 syslog(LOG_INFO, "crypto: generating RSA key pair");
78 ret = BN_set_word(bne,e);
84 ret = RSA_generate_key_ex(rsa, bits, bne, NULL);
90 fp = fopen(keyfilename, "w");
92 chmod(keyfilename, 0600);
93 if (PEM_write_RSAPrivateKey(fp, /* the file */
96 NULL, /* no passphr */
101 syslog(LOG_ERR, "crypto: cannot write key: %s", ERR_reason_error_string(ERR_get_error()));
114 void init_ssl(void) {
115 const SSL_METHOD *ssl_method;
117 X509_REQ *req = NULL;
120 EVP_PKEY *req_pkey = NULL;
121 X509_NAME *name = NULL;
124 SSLCritters = malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t *));
126 syslog(LOG_ERR, "crypto: can't allocate memory!");
127 exit(CTDLEXIT_CRYPTO);
132 for (a = 0; a < CRYPTO_num_locks(); a++) {
133 SSLCritters[a] = malloc(sizeof(pthread_mutex_t));
134 if (!SSLCritters[a]) {
135 syslog(LOG_ERR, "crypto: can't allocate memory!!");
136 exit(CTDLEXIT_CRYPTO);
138 pthread_mutex_init(SSLCritters[a], NULL);
143 * Initialize SSL transport layer
146 SSL_load_error_strings();
147 ssl_method = SSLv23_server_method();
148 if (!(ssl_ctx = SSL_CTX_new(ssl_method))) {
149 syslog(LOG_ERR, "crypto: SSL_CTX_new failed: %s", ERR_reason_error_string(ERR_get_error()));
152 if (!(SSL_CTX_set_cipher_list(ssl_ctx, CIT_CIPHERS))) {
153 syslog(LOG_ERR, "crypto: No ciphers available");
154 SSL_CTX_free(ssl_ctx);
159 CRYPTO_set_locking_callback(ssl_lock);
160 CRYPTO_set_id_callback(id_callback);
162 mkdir(ctdl_key_dir, 0700); // If the keys directory does not exist, create it
163 generate_key(file_crpt_file_key); // If a private key does not exist, create it
166 * If there is no certificate file on disk, we will be generating a self-signed certificate
167 * in the next step. Therefore, if we have neither a CSR nor a certificate, generate
168 * the CSR in this step so that the next step may commence.
170 if ( (access(file_crpt_file_cer, R_OK) != 0) && (access(file_crpt_file_csr, R_OK) != 0) ) {
171 syslog(LOG_INFO, "crypto: generating a generic certificate signing request.");
174 * Read our key from the file. No, we don't just keep this
175 * in memory from the above key-generation function, because
176 * there is the possibility that the key was already on disk
177 * and we didn't just generate it now.
179 fp = fopen(file_crpt_file_key, "r");
181 rsa = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
187 /* Create a public key from the private key */
188 if (pk=EVP_PKEY_new(), pk != NULL) {
189 EVP_PKEY_assign_RSA(pk, rsa);
190 if (req = X509_REQ_new(), req != NULL) {
192 /* Set the public key */
193 X509_REQ_set_pubkey(req, pk);
194 X509_REQ_set_version(req, 0L);
196 name = X509_REQ_get_subject_name(req);
198 /* Tell it who we are */
199 X509_NAME_add_entry_by_txt(name, "C", MBSTRING_ASC, (unsigned const char *)"ZZ", -1, -1, 0);
200 X509_NAME_add_entry_by_txt(name, "ST", MBSTRING_ASC, (unsigned const char *)"The World", -1, -1, 0);
201 X509_NAME_add_entry_by_txt(name, "L", MBSTRING_ASC, (unsigned const char *)"My Location", -1, -1, 0);
202 X509_NAME_add_entry_by_txt(name, "O", MBSTRING_ASC, (unsigned const char *)"Generic certificate", -1, -1, 0);
203 X509_NAME_add_entry_by_txt(name, "OU", MBSTRING_ASC, (unsigned const char *)"Citadel server", -1, -1, 0);
204 X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC, (unsigned const char *)"*", -1, -1, 0);
205 X509_REQ_set_subject_name(req, name);
208 if (!X509_REQ_sign(req, pk, EVP_md5())) {
209 syslog(LOG_ERR, "crypto: X509_REQ_sign(): error");
212 /* Write it to disk. */
213 fp = fopen(file_crpt_file_csr, "w");
215 chmod(file_crpt_file_csr, 0600);
216 PEM_write_X509_REQ(fp, req);
229 syslog(LOG_ERR, "crypto: unable to read private key.");
235 * Generate a self-signed certificate if we don't have one.
237 if (access(file_crpt_file_cer, R_OK) != 0) {
238 syslog(LOG_INFO, "crypto: generating a generic self-signed certificate.");
240 /* Same deal as before: always read the key from disk because
241 * it may or may not have just been generated.
243 fp = fopen(file_crpt_file_key, "r");
245 rsa = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
249 /* This also holds true for the CSR. */
254 if (pk=EVP_PKEY_new(), pk != NULL) {
255 EVP_PKEY_assign_RSA(pk, rsa);
258 fp = fopen(file_crpt_file_csr, "r");
260 req = PEM_read_X509_REQ(fp, NULL, NULL, NULL);
265 if (cer = X509_new(), cer != NULL) {
266 ASN1_INTEGER_set(X509_get_serialNumber(cer), 0);
267 X509_set_issuer_name(cer, X509_REQ_get_subject_name(req));
268 X509_set_subject_name(cer, X509_REQ_get_subject_name(req));
269 X509_gmtime_adj(X509_get_notBefore(cer),0);
270 X509_gmtime_adj(X509_get_notAfter(cer),(long)60*60*24*SIGN_DAYS);
271 req_pkey = X509_REQ_get_pubkey(req);
272 X509_set_pubkey(cer, req_pkey);
273 EVP_PKEY_free(req_pkey);
276 if (!X509_sign(cer, pk, EVP_md5())) {
277 syslog(LOG_ERR, "crypto: X509_sign() error");
280 /* Write it to disk. */
281 fp = fopen(file_crpt_file_cer, "w");
283 chmod(file_crpt_file_cer, 0600);
284 PEM_write_X509(fp, cer);
298 * Now try to bind to the key and certificate.
300 SSL_CTX_use_certificate_chain_file(ssl_ctx, file_crpt_file_cer);
301 SSL_CTX_use_PrivateKey_file(ssl_ctx, file_crpt_file_key, SSL_FILETYPE_PEM);
302 if ( !SSL_CTX_check_private_key(ssl_ctx) ) {
303 syslog(LOG_ERR, "crypto: cannot install certificate: %s", ERR_reason_error_string(ERR_get_error()));
306 /* Finally let the server know we're here */
307 CtdlRegisterProtoHook(cmd_stls, "STLS", "Start SSL/TLS session");
308 CtdlRegisterProtoHook(cmd_gtls, "GTLS", "Get SSL/TLS session status");
309 CtdlRegisterSessionHook(endtls, EVT_STOP, PRIO_STOP + 10);
313 // client_write_ssl() Send binary data to the client encrypted.
314 void client_write_ssl(const char *buf, int nbytes) {
321 while (nremain > 0) {
322 if (SSL_want_write(CC->ssl)) {
323 if ((SSL_read(CC->ssl, junk, 0)) < 1) {
324 syslog(LOG_DEBUG, "crypto: SSL_read in client_write: %s", ERR_reason_error_string(ERR_get_error()));
328 SSL_write(CC->ssl, &buf[nbytes - nremain], nremain);
332 errval = SSL_get_error(CC->ssl, retval);
333 if (errval == SSL_ERROR_WANT_READ ||
334 errval == SSL_ERROR_WANT_WRITE) {
338 syslog(LOG_DEBUG, "crypto: SSL_write got error %ld, ret %d", errval, retval);
340 syslog(LOG_DEBUG, "crypto: errno is %d", errno);
343 client_write(&buf[nbytes - nremain], nremain);
351 // read data from the encrypted layer.
352 int client_read_sslbuffer(StrBuf *buf, int timeout) {
353 char sbuf[16384]; /* OpenSSL communicates in 16k blocks, so let's speak its native tongue. */
358 if (pssl == NULL) return(-1);
361 if (SSL_want_read(pssl)) {
362 if ((SSL_write(pssl, junk, 0)) < 1) {
363 syslog(LOG_DEBUG, "crypto: SSL_write in client_read");
366 rlen = SSL_read(pssl, sbuf, sizeof(sbuf));
370 errval = SSL_get_error(pssl, rlen);
371 if (errval == SSL_ERROR_WANT_READ || errval == SSL_ERROR_WANT_WRITE) {
375 syslog(LOG_DEBUG, "crypto: SSL_read got error %ld", errval);
379 StrBufAppendBufPlain(buf, sbuf, rlen, 0);
386 int client_readline_sslbuffer(StrBuf *Line, StrBuf *IOBuf, const char **Pos, int timeout) {
387 const char *pos = NULL;
390 int nSuccessLess = 0;
391 const char *pch = NULL;
393 if ((Line == NULL) || (Pos == NULL) || (IOBuf == NULL))
403 if ((StrLength(IOBuf) > 0) && (pos != NULL) && (pos < ChrPtr(IOBuf) + StrLength(IOBuf)))
406 pch = strchr(pch, '\n');
409 StrBufAppendBufPlain(Line, pos, StrLength(IOBuf) - (pos - ChrPtr(IOBuf)), 0);
415 if ((pch > ChrPtr(IOBuf)) &&
416 (*(pch - 1) == '\r')) {
419 StrBufAppendBufPlain(Line, pos,
422 if (StrLength(IOBuf) <= (pch - ChrPtr(IOBuf) + 1)) {
428 return StrLength(Line);
433 while ((nSuccessLess < timeout) &&
437 rlen = client_read_sslbuffer(IOBuf, timeout);
442 pLF = strchr(ChrPtr(IOBuf), '\n');
449 if (len > 0 && (*(pLF - 1) == '\r') )
451 StrBufAppendBufPlain(Line, pos, len, 0);
452 if (pLF + 1 >= ChrPtr(IOBuf) + StrLength(IOBuf))
458 return StrLength(Line);
464 int client_read_sslblob(StrBuf *Target, long bytes, int timeout) {
469 baselen = StrLength(Target);
471 if (StrLength(CC->RecvBuf.Buf) > 0)
477 if (CC->RecvBuf.ReadWritePointer == NULL)
479 CC->RecvBuf.ReadWritePointer = ChrPtr(CC->RecvBuf.Buf);
481 pchs = ChrPtr(CC->RecvBuf.Buf);
482 TotalLen = StrLength(CC->RecvBuf.Buf);
483 RemainLen = TotalLen - (pchs - CC->RecvBuf.ReadWritePointer);
484 if (RemainLen > bytes)
490 StrBufAppendBufPlain(Target, CC->RecvBuf.ReadWritePointer, RemainLen, 0);
491 CC->RecvBuf.ReadWritePointer += RemainLen;
493 if ((ChrPtr(CC->RecvBuf.Buf) + StrLength(CC->RecvBuf.Buf)) <= CC->RecvBuf.ReadWritePointer)
495 CC->RecvBuf.ReadWritePointer = NULL;
496 FlushStrBuf(CC->RecvBuf.Buf);
500 if (StrLength(Target) >= bytes + baselen) {
504 CC->RecvBuf.ReadWritePointer = NULL;
506 while ((StrLength(Target) < bytes + baselen) && (retval >= 0)) {
507 retval = client_read_sslbuffer(CC->RecvBuf.Buf, timeout);
509 RemainRead = bytes - (StrLength (Target) - baselen);
510 if (RemainRead < StrLength(CC->RecvBuf.Buf))
512 StrBufAppendBufPlain(
514 ChrPtr(CC->RecvBuf.Buf),
516 CC->RecvBuf.ReadWritePointer = ChrPtr(CC->RecvBuf.Buf) + RemainRead;
519 StrBufAppendBuf(Target, CC->RecvBuf.Buf, 0); /* todo: Buf > bytes? */
520 FlushStrBuf(CC->RecvBuf.Buf);
523 FlushStrBuf(CC->RecvBuf.Buf);
532 // CtdlStartTLS() starts SSL/TLS encryption for the current session. It
533 // must be supplied with pre-generated strings for responses of "ok," "no
534 // support for TLS," and "error" so that we can use this in any protocol.
535 void CtdlStartTLS(char *ok_response, char *nosup_response, char *error_response) {
536 int retval, bits, alg_bits;
538 if (CC->redirect_ssl) {
539 syslog(LOG_ERR, "crypto: attempt to begin SSL on an already encrypted connection");
540 if (error_response != NULL) {
541 cprintf("%s", error_response);
547 syslog(LOG_ERR, "crypto: SSL failed: no ssl_ctx exists?");
548 if (nosup_response != NULL) cprintf("%s", nosup_response);
551 if (!(CC->ssl = SSL_new(ssl_ctx))) {
552 syslog(LOG_ERR, "crypto: SSL_new failed: %s", ERR_reason_error_string(ERR_get_error()));
553 if (error_response != NULL) {
554 cprintf("%s", error_response);
558 if (!(SSL_set_fd(CC->ssl, CC->client_socket))) {
559 syslog(LOG_ERR, "crypto: SSL_set_fd failed: %s", ERR_reason_error_string(ERR_get_error()));
562 if (error_response != NULL) cprintf("%s", error_response);
565 if (ok_response != NULL) cprintf("%s", ok_response);
566 retval = SSL_accept(CC->ssl);
569 * Can't notify the client of an error here; they will
570 * discover the problem at the SSL layer and should
571 * revert to unencrypted communications.
574 char error_string[128];
576 errval = SSL_get_error(CC->ssl, retval);
577 syslog(LOG_ERR, "crypto: SSL_accept failed: retval=%d, errval=%ld, err=%s",
580 ERR_error_string(errval, error_string)
586 // BIO_set_close(CC->ssl->rbio, BIO_NOCLOSE); not needed anymore in openssl 1.1 ?
587 bits = SSL_CIPHER_get_bits(SSL_get_current_cipher(CC->ssl), &alg_bits);
588 syslog(LOG_INFO, "crypto: SSL/TLS using %s on %s (%d of %d bits)",
589 SSL_CIPHER_get_name(SSL_get_current_cipher(CC->ssl)),
590 SSL_CIPHER_get_version(SSL_get_current_cipher(CC->ssl)),
593 CC->redirect_ssl = 1;
597 // cmd_stls() starts SSL/TLS encryption for the current session
598 void cmd_stls(char *params) {
599 char ok_response[SIZ];
600 char nosup_response[SIZ];
601 char error_response[SIZ];
605 sprintf(ok_response, "%d Begin TLS negotiation now\n", CIT_OK);
606 sprintf(nosup_response, "%d TLS not supported here\n", ERROR + CMD_NOT_SUPPORTED);
607 sprintf(error_response, "%d TLS negotiation error\n", ERROR + INTERNAL_ERROR);
609 CtdlStartTLS(ok_response, nosup_response, error_response);
613 // cmd_gtls() returns status info about the TLS connection
614 void cmd_gtls(char *params) {
617 if (!CC->ssl || !CC->redirect_ssl) {
618 cprintf("%d Session is not encrypted.\n", ERROR);
622 SSL_CIPHER_get_bits(SSL_get_current_cipher(CC->ssl),
624 cprintf("%d %s|%s|%d|%d\n", CIT_OK,
625 SSL_CIPHER_get_version(SSL_get_current_cipher(CC->ssl)),
626 SSL_CIPHER_get_name(SSL_get_current_cipher(CC->ssl)),
631 // endtls() shuts down the TLS connection
633 // WARNING: This may make your session vulnerable to a known plaintext
634 // attack in the current implmentation.
637 CC->redirect_ssl = 0;
641 syslog(LOG_INFO, "crypto: ending SSL/TLS");
642 SSL_shutdown(CC->ssl);
645 CC->redirect_ssl = 0;
649 // ssl_lock() callback for OpenSSL mutex locks
650 void ssl_lock(int mode, int n, const char *file, int line) {
651 if (mode & CRYPTO_LOCK) {
652 pthread_mutex_lock(SSLCritters[n]);
655 pthread_mutex_unlock(SSLCritters[n]);
658 #endif /* HAVE_OPENSSL */