2 * Copyright (c) 1987-2018 by the citadel.org team
4 * This program is open source software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License version 3.
7 * This program is distributed in the hope that it will be useful,
8 * but WITHOUT ANY WARRANTY; without even the implied warranty of
9 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 * GNU General Public License for more details.
16 #include <sys/types.h>
20 #include <openssl/ssl.h>
21 #include <openssl/err.h>
22 #include <openssl/rand.h>
25 #if TIME_WITH_SYS_TIME
26 # include <sys/time.h>
30 # include <sys/time.h>
40 #ifdef HAVE_SYS_SELECT_H
41 #include <sys/select.h>
45 #include <libcitadel.h>
47 #include "serv_crypto.h"
48 #include "sysdep_decls.h"
53 #include "ctdl_module.h"
56 SSL_CTX *ssl_ctx; /* SSL context */
57 pthread_mutex_t **SSLCritters; /* Things needing locking */
59 static unsigned long id_callback(void)
61 return (unsigned long) pthread_self();
64 void destruct_ssl(void)
67 for (a = 0; a < CRYPTO_num_locks(); a++)
73 void generate_key(char *keyfilename)
79 unsigned long e = RSA_F4;
82 if (access(keyfilename, R_OK) == 0) {
86 syslog(LOG_INFO, "crypto: generating RSA key pair");
90 ret = BN_set_word(bne,e);
96 ret = RSA_generate_key_ex(rsa, bits, bne, NULL);
101 // write the key file
102 fp = fopen(keyfilename, "w");
104 chmod(keyfilename, 0600);
105 if (PEM_write_RSAPrivateKey(fp, /* the file */
108 NULL, /* no passphr */
110 NULL, /* no callbk */
113 syslog(LOG_ERR, "crypto: cannot write key: %s", ERR_reason_error_string(ERR_get_error()));
128 const SSL_METHOD *ssl_method;
130 X509_REQ *req = NULL;
133 EVP_PKEY *req_pkey = NULL;
134 X509_NAME *name = NULL;
137 SSLCritters = malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t *));
139 syslog(LOG_ERR, "crypto: can't allocate memory!");
140 exit(CTDLEXIT_CRYPTO);
144 for (a = 0; a < CRYPTO_num_locks(); a++) {
145 SSLCritters[a] = malloc(sizeof(pthread_mutex_t));
146 if (!SSLCritters[a]) {
147 syslog(LOG_ERR, "crypto: can't allocate memory!!");
148 exit(CTDLEXIT_CRYPTO);
150 pthread_mutex_init(SSLCritters[a], NULL);
155 * Initialize SSL transport layer
158 SSL_load_error_strings();
159 ssl_method = SSLv23_server_method();
160 if (!(ssl_ctx = SSL_CTX_new(ssl_method))) {
161 syslog(LOG_ERR, "crypto: SSL_CTX_new failed: %s", ERR_reason_error_string(ERR_get_error()));
164 if (!(SSL_CTX_set_cipher_list(ssl_ctx, CIT_CIPHERS))) {
165 syslog(LOG_ERR, "crypto: No ciphers available");
166 SSL_CTX_free(ssl_ctx);
171 CRYPTO_set_locking_callback(ssl_lock);
172 CRYPTO_set_id_callback(id_callback);
174 mkdir(ctdl_key_dir, 0700); // If the keys directory does not exist, create it
175 generate_key(file_crpt_file_key); // If a private key does not exist, create it
178 * If there is no certificate file on disk, we will be generating a self-signed certificate
179 * in the next step. Therefore, if we have neither a CSR nor a certificate, generate
180 * the CSR in this step so that the next step may commence.
182 if ( (access(file_crpt_file_cer, R_OK) != 0) && (access(file_crpt_file_csr, R_OK) != 0) ) {
183 syslog(LOG_INFO, "crypto: generating a generic certificate signing request.");
186 * Read our key from the file. No, we don't just keep this
187 * in memory from the above key-generation function, because
188 * there is the possibility that the key was already on disk
189 * and we didn't just generate it now.
191 fp = fopen(file_crpt_file_key, "r");
193 rsa = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
199 /* Create a public key from the private key */
200 if (pk=EVP_PKEY_new(), pk != NULL) {
201 EVP_PKEY_assign_RSA(pk, rsa);
202 if (req = X509_REQ_new(), req != NULL) {
204 /* Set the public key */
205 X509_REQ_set_pubkey(req, pk);
206 X509_REQ_set_version(req, 0L);
208 name = X509_REQ_get_subject_name(req);
210 /* Tell it who we are */
211 X509_NAME_add_entry_by_txt(name, "C", MBSTRING_ASC, (unsigned const char *)"ZZ", -1, -1, 0);
212 X509_NAME_add_entry_by_txt(name, "ST", MBSTRING_ASC, (unsigned const char *)"The World", -1, -1, 0);
213 X509_NAME_add_entry_by_txt(name, "L", MBSTRING_ASC, (unsigned const char *)"My Location", -1, -1, 0);
214 X509_NAME_add_entry_by_txt(name, "O", MBSTRING_ASC, (unsigned const char *)"Generic certificate", -1, -1, 0);
215 X509_NAME_add_entry_by_txt(name, "OU", MBSTRING_ASC, (unsigned const char *)"Citadel server", -1, -1, 0);
216 X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC, (unsigned const char *)"*", -1, -1, 0);
217 X509_REQ_set_subject_name(req, name);
220 if (!X509_REQ_sign(req, pk, EVP_md5())) {
221 syslog(LOG_ERR, "crypto: X509_REQ_sign(): error");
224 /* Write it to disk. */
225 fp = fopen(file_crpt_file_csr, "w");
227 chmod(file_crpt_file_csr, 0600);
228 PEM_write_X509_REQ(fp, req);
241 syslog(LOG_ERR, "crypto: unable to read private key.");
247 * Generate a self-signed certificate if we don't have one.
249 if (access(file_crpt_file_cer, R_OK) != 0) {
250 syslog(LOG_INFO, "crypto: generating a generic self-signed certificate.");
252 /* Same deal as before: always read the key from disk because
253 * it may or may not have just been generated.
255 fp = fopen(file_crpt_file_key, "r");
257 rsa = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
261 /* This also holds true for the CSR. */
266 if (pk=EVP_PKEY_new(), pk != NULL) {
267 EVP_PKEY_assign_RSA(pk, rsa);
270 fp = fopen(file_crpt_file_csr, "r");
272 req = PEM_read_X509_REQ(fp, NULL, NULL, NULL);
277 if (cer = X509_new(), cer != NULL) {
278 ASN1_INTEGER_set(X509_get_serialNumber(cer), 0);
279 X509_set_issuer_name(cer, X509_REQ_get_subject_name(req));
280 X509_set_subject_name(cer, X509_REQ_get_subject_name(req));
281 X509_gmtime_adj(X509_get_notBefore(cer),0);
282 X509_gmtime_adj(X509_get_notAfter(cer),(long)60*60*24*SIGN_DAYS);
283 req_pkey = X509_REQ_get_pubkey(req);
284 X509_set_pubkey(cer, req_pkey);
285 EVP_PKEY_free(req_pkey);
288 if (!X509_sign(cer, pk, EVP_md5())) {
289 syslog(LOG_ERR, "crypto: X509_sign() error");
292 /* Write it to disk. */
293 fp = fopen(file_crpt_file_cer, "w");
295 chmod(file_crpt_file_cer, 0600);
296 PEM_write_X509(fp, cer);
310 * Now try to bind to the key and certificate.
312 SSL_CTX_use_certificate_chain_file(ssl_ctx, file_crpt_file_cer);
313 SSL_CTX_use_PrivateKey_file(ssl_ctx, file_crpt_file_key, SSL_FILETYPE_PEM);
314 if ( !SSL_CTX_check_private_key(ssl_ctx) ) {
315 syslog(LOG_ERR, "crypto: cannot install certificate: %s", ERR_reason_error_string(ERR_get_error()));
318 /* Finally let the server know we're here */
319 CtdlRegisterProtoHook(cmd_stls, "STLS", "Start SSL/TLS session");
320 CtdlRegisterProtoHook(cmd_gtls, "GTLS", "Get SSL/TLS session status");
321 CtdlRegisterSessionHook(endtls, EVT_STOP, PRIO_STOP + 10);
326 * client_write_ssl() Send binary data to the client encrypted.
328 void client_write_ssl(const char *buf, int nbytes)
336 while (nremain > 0) {
337 if (SSL_want_write(CC->ssl)) {
338 if ((SSL_read(CC->ssl, junk, 0)) < 1) {
339 syslog(LOG_DEBUG, "crypto: SSL_read in client_write: %s", ERR_reason_error_string(ERR_get_error()));
343 SSL_write(CC->ssl, &buf[nbytes - nremain], nremain);
347 errval = SSL_get_error(CC->ssl, retval);
348 if (errval == SSL_ERROR_WANT_READ ||
349 errval == SSL_ERROR_WANT_WRITE) {
353 syslog(LOG_DEBUG, "crypto: SSL_write got error %ld, ret %d", errval, retval);
355 syslog(LOG_DEBUG, "crypto: errno is %d", errno);
358 client_write(&buf[nbytes - nremain], nremain);
367 * read data from the encrypted layer.
369 int client_read_sslbuffer(StrBuf *buf, int timeout)
371 char sbuf[16384]; /* OpenSSL communicates in 16k blocks, so let's speak its native tongue. */
376 if (pssl == NULL) return(-1);
379 if (SSL_want_read(pssl)) {
380 if ((SSL_write(pssl, junk, 0)) < 1) {
381 syslog(LOG_DEBUG, "crypto: SSL_write in client_read");
384 rlen = SSL_read(pssl, sbuf, sizeof(sbuf));
388 errval = SSL_get_error(pssl, rlen);
389 if (errval == SSL_ERROR_WANT_READ || errval == SSL_ERROR_WANT_WRITE) {
393 syslog(LOG_DEBUG, "crypto: SSL_read got error %ld", errval);
397 StrBufAppendBufPlain(buf, sbuf, rlen, 0);
403 int client_readline_sslbuffer(StrBuf *Line, StrBuf *IOBuf, const char **Pos, int timeout)
405 CitContext *CCC = CC;
406 const char *pos = NULL;
409 int nSuccessLess = 0;
410 const char *pch = NULL;
412 if ((Line == NULL) || (Pos == NULL) || (IOBuf == NULL))
422 if ((StrLength(IOBuf) > 0) && (pos != NULL) && (pos < ChrPtr(IOBuf) + StrLength(IOBuf)))
425 pch = strchr(pch, '\n');
428 StrBufAppendBufPlain(Line, pos, StrLength(IOBuf) - (pos - ChrPtr(IOBuf)), 0);
434 if ((pch > ChrPtr(IOBuf)) &&
435 (*(pch - 1) == '\r')) {
438 StrBufAppendBufPlain(Line, pos,
441 if (StrLength(IOBuf) <= (pch - ChrPtr(IOBuf) + 1)) {
447 return StrLength(Line);
452 while ((nSuccessLess < timeout) &&
454 (CCC->ssl != NULL)) {
456 rlen = client_read_sslbuffer(IOBuf, timeout);
461 pLF = strchr(ChrPtr(IOBuf), '\n');
468 if (len > 0 && (*(pLF - 1) == '\r') )
470 StrBufAppendBufPlain(Line, pos, len, 0);
471 if (pLF + 1 >= ChrPtr(IOBuf) + StrLength(IOBuf))
477 return StrLength(Line);
483 int client_read_sslblob(StrBuf *Target, long bytes, int timeout)
488 CitContext *CCC = CC;
490 baselen = StrLength(Target);
492 if (StrLength(CCC->RecvBuf.Buf) > 0)
498 if (CCC->RecvBuf.ReadWritePointer == NULL)
500 CCC->RecvBuf.ReadWritePointer = ChrPtr(CCC->RecvBuf.Buf);
502 pchs = ChrPtr(CCC->RecvBuf.Buf);
503 TotalLen = StrLength(CCC->RecvBuf.Buf);
504 RemainLen = TotalLen - (pchs - CCC->RecvBuf.ReadWritePointer);
505 if (RemainLen > bytes)
511 StrBufAppendBufPlain(Target, CCC->RecvBuf.ReadWritePointer, RemainLen, 0);
512 CCC->RecvBuf.ReadWritePointer += RemainLen;
514 if ((ChrPtr(CCC->RecvBuf.Buf) + StrLength(CCC->RecvBuf.Buf)) <= CCC->RecvBuf.ReadWritePointer)
516 CCC->RecvBuf.ReadWritePointer = NULL;
517 FlushStrBuf(CCC->RecvBuf.Buf);
521 if (StrLength(Target) >= bytes + baselen)
526 CCC->RecvBuf.ReadWritePointer = NULL;
528 while ((StrLength(Target) < bytes + baselen) && (retval >= 0))
530 retval = client_read_sslbuffer(CCC->RecvBuf.Buf, timeout);
532 RemainRead = bytes - (StrLength (Target) - baselen);
533 if (RemainRead < StrLength(CCC->RecvBuf.Buf))
535 StrBufAppendBufPlain(
537 ChrPtr(CCC->RecvBuf.Buf),
539 CCC->RecvBuf.ReadWritePointer = ChrPtr(CCC->RecvBuf.Buf) + RemainRead;
542 StrBufAppendBuf(Target, CCC->RecvBuf.Buf, 0); /* todo: Buf > bytes? */
543 FlushStrBuf(CCC->RecvBuf.Buf);
547 FlushStrBuf(CCC->RecvBuf.Buf);
557 * CtdlStartTLS() starts SSL/TLS encryption for the current session. It
558 * must be supplied with pre-generated strings for responses of "ok," "no
559 * support for TLS," and "error" so that we can use this in any protocol.
561 void CtdlStartTLS(char *ok_response, char *nosup_response, char *error_response)
563 int retval, bits, alg_bits;
566 syslog(LOG_ERR, "crypto: SSL failed: no ssl_ctx exists?");
567 if (nosup_response != NULL) cprintf("%s", nosup_response);
570 if (!(CC->ssl = SSL_new(ssl_ctx))) {
571 syslog(LOG_ERR, "crypto: SSL_new failed: %s", ERR_reason_error_string(ERR_get_error()));
572 if (error_response != NULL) {
573 cprintf("%s", error_response);
577 if (!(SSL_set_fd(CC->ssl, CC->client_socket))) {
578 syslog(LOG_ERR, "crypto: SSL_set_fd failed: %s", ERR_reason_error_string(ERR_get_error()));
581 if (error_response != NULL) cprintf("%s", error_response);
584 if (ok_response != NULL) cprintf("%s", ok_response);
585 retval = SSL_accept(CC->ssl);
588 * Can't notify the client of an error here; they will
589 * discover the problem at the SSL layer and should
590 * revert to unencrypted communications.
593 char error_string[128];
595 errval = SSL_get_error(CC->ssl, retval);
596 syslog(LOG_ERR, "crypto: SSL_accept failed: retval=%d, errval=%ld, err=%s",
599 ERR_error_string(errval, error_string)
605 // BIO_set_close(CC->ssl->rbio, BIO_NOCLOSE); not needed anymore in openssl 1.1 ?
606 bits = SSL_CIPHER_get_bits(SSL_get_current_cipher(CC->ssl), &alg_bits);
607 syslog(LOG_INFO, "crypto: SSL/TLS using %s on %s (%d of %d bits)",
608 SSL_CIPHER_get_name(SSL_get_current_cipher(CC->ssl)),
609 SSL_CIPHER_get_version(SSL_get_current_cipher(CC->ssl)),
612 CC->redirect_ssl = 1;
617 * cmd_stls() starts SSL/TLS encryption for the current session
619 void cmd_stls(char *params)
621 char ok_response[SIZ];
622 char nosup_response[SIZ];
623 char error_response[SIZ];
627 sprintf(ok_response, "%d Begin TLS negotiation now\n", CIT_OK);
628 sprintf(nosup_response, "%d TLS not supported here\n", ERROR + CMD_NOT_SUPPORTED);
629 sprintf(error_response, "%d TLS negotiation error\n", ERROR + INTERNAL_ERROR);
631 CtdlStartTLS(ok_response, nosup_response, error_response);
636 * cmd_gtls() returns status info about the TLS connection
638 void cmd_gtls(char *params)
642 if (!CC->ssl || !CC->redirect_ssl) {
643 cprintf("%d Session is not encrypted.\n", ERROR);
647 SSL_CIPHER_get_bits(SSL_get_current_cipher(CC->ssl),
649 cprintf("%d %s|%s|%d|%d\n", CIT_OK,
650 SSL_CIPHER_get_version(SSL_get_current_cipher(CC->ssl)),
651 SSL_CIPHER_get_name(SSL_get_current_cipher(CC->ssl)),
657 * endtls() shuts down the TLS connection
659 * WARNING: This may make your session vulnerable to a known plaintext
660 * attack in the current implmentation.
665 CC->redirect_ssl = 0;
669 syslog(LOG_INFO, "crypto: ending SSL/TLS");
670 SSL_shutdown(CC->ssl);
673 CC->redirect_ssl = 0;
678 * ssl_lock() callback for OpenSSL mutex locks
680 void ssl_lock(int mode, int n, const char *file, int line)
682 if (mode & CRYPTO_LOCK)
684 pthread_mutex_lock(SSLCritters[n]);
687 pthread_mutex_unlock(SSLCritters[n]);
690 #endif /* HAVE_OPENSSL */