2 * Copyright (c) 1987-2015 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"
54 /* TODO: should we use the standard module init stuff to start this? */
55 /* TODO: should we register an event handler to call destruct_ssl? */
58 SSL_CTX *ssl_ctx; /* SSL context */
59 pthread_mutex_t **SSLCritters; /* Things needing locking */
61 static unsigned long id_callback(void)
63 return (unsigned long) pthread_self();
66 void destruct_ssl(void)
69 for (a = 0; a < CRYPTO_num_locks(); a++)
76 const SSL_METHOD *ssl_method;
82 EVP_PKEY *req_pkey = NULL;
83 X509_NAME *name = NULL;
86 if (!access(EGD_POOL, F_OK))
90 syslog(LOG_CRIT, "PRNG not adequately seeded, won't do SSL/TLS");
94 malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t *));
96 syslog(LOG_EMERG, "citserver: can't allocate memory!!");
97 /* Nothing's been initialized, just die */
102 for (a = 0; a < CRYPTO_num_locks(); a++) {
103 SSLCritters[a] = malloc(sizeof(pthread_mutex_t));
104 if (!SSLCritters[a]) {
105 syslog(LOG_EMERG, "citserver: can't allocate memory!!");
106 /* Nothing's been initialized, just die */
109 pthread_mutex_init(SSLCritters[a], NULL);
114 * Initialize SSL transport layer
117 SSL_load_error_strings();
118 ssl_method = SSLv23_server_method();
119 if (!(ssl_ctx = SSL_CTX_new(ssl_method))) {
120 syslog(LOG_CRIT, "SSL_CTX_new failed: %s", ERR_reason_error_string(ERR_get_error()));
123 if (!(SSL_CTX_set_cipher_list(ssl_ctx, CIT_CIPHERS))) {
124 syslog(LOG_CRIT, "SSL: No ciphers available");
125 SSL_CTX_free(ssl_ctx);
130 #if SSLEAY_VERSION_NUMBER >= 0x00906000L
131 SSL_CTX_set_mode(ssl_ctx, SSL_CTX_get_mode(ssl_ctx) |
132 SSL_MODE_AUTO_RETRY);
136 CRYPTO_set_locking_callback(ssl_lock);
137 CRYPTO_set_id_callback(id_callback);
139 /* Load DH parameters into the context */
142 syslog(LOG_CRIT, "init_ssl() can't allocate a DH object: %s", ERR_reason_error_string(ERR_get_error()));
143 SSL_CTX_free(ssl_ctx);
147 if (!(BN_hex2bn(&(dh->p), DH_P))) {
148 syslog(LOG_CRIT, "init_ssl() can't assign DH_P: %s", ERR_reason_error_string(ERR_get_error()));
149 SSL_CTX_free(ssl_ctx);
153 if (!(BN_hex2bn(&(dh->g), DH_G))) {
154 syslog(LOG_CRIT, "init_ssl() can't assign DH_G: %s", ERR_reason_error_string(ERR_get_error()));
155 SSL_CTX_free(ssl_ctx);
160 SSL_CTX_set_tmp_dh(ssl_ctx, dh);
163 /* Get our certificates in order.
164 * First, create the key/cert directory if it's not there already...
166 mkdir(ctdl_key_dir, 0700);
169 * Generate a key pair if we don't have one.
171 if (access(file_crpt_file_key, R_OK) != 0) {
172 syslog(LOG_INFO, "Generating RSA key pair.");
173 rsa = RSA_generate_key(1024, /* modulus size */
174 65537, /* exponent */
175 NULL, /* no callback */
176 NULL); /* no callback */
178 syslog(LOG_CRIT, "Key generation failed: %s", ERR_reason_error_string(ERR_get_error()));
181 fp = fopen(file_crpt_file_key, "w");
183 chmod(file_crpt_file_key, 0600);
184 if (PEM_write_RSAPrivateKey(fp, /* the file */
187 NULL, /* no passphr */
189 NULL, /* no callbk */
192 syslog(LOG_CRIT, "Cannot write key: %s", ERR_reason_error_string(ERR_get_error()));
193 unlink(file_crpt_file_key);
202 * If there is no certificate file on disk, we will be generating a self-signed certificate
203 * in the next step. Therefore, if we have neither a CSR nor a certificate, generate
204 * the CSR in this step so that the next step may commence.
206 if ( (access(file_crpt_file_cer, R_OK) != 0) && (access(file_crpt_file_csr, R_OK) != 0) ) {
207 syslog(LOG_INFO, "Generating a generic certificate signing request.");
210 * Read our key from the file. No, we don't just keep this
211 * in memory from the above key-generation function, because
212 * there is the possibility that the key was already on disk
213 * and we didn't just generate it now.
215 fp = fopen(file_crpt_file_key, "r");
217 rsa = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
223 /* Create a public key from the private key */
224 if (pk=EVP_PKEY_new(), pk != NULL) {
225 EVP_PKEY_assign_RSA(pk, rsa);
226 if (req = X509_REQ_new(), req != NULL) {
228 /* Set the public key */
229 X509_REQ_set_pubkey(req, pk);
230 X509_REQ_set_version(req, 0L);
232 name = X509_REQ_get_subject_name(req);
234 /* Tell it who we are */
235 X509_NAME_add_entry_by_txt(name, "C", MBSTRING_ASC, (unsigned const char *)"ZZ", -1, -1, 0);
236 X509_NAME_add_entry_by_txt(name, "ST", MBSTRING_ASC, (unsigned const char *)"The World", -1, -1, 0);
237 X509_NAME_add_entry_by_txt(name, "L", MBSTRING_ASC, (unsigned const char *)"My Location", -1, -1, 0);
238 X509_NAME_add_entry_by_txt(name, "O", MBSTRING_ASC, (unsigned const char *)"Generic certificate", -1, -1, 0);
239 X509_NAME_add_entry_by_txt(name, "OU", MBSTRING_ASC, (unsigned const char *)"Citadel server", -1, -1, 0);
240 X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC, (unsigned const char *)"*", -1, -1, 0);
241 X509_REQ_set_subject_name(req, name);
244 if (!X509_REQ_sign(req, pk, EVP_md5())) {
245 syslog(LOG_CRIT, "X509_REQ_sign(): error");
248 /* Write it to disk. */
249 fp = fopen(file_crpt_file_csr, "w");
251 chmod(file_crpt_file_csr, 0600);
252 PEM_write_X509_REQ(fp, req);
265 syslog(LOG_CRIT, "Unable to read private key.");
272 * Generate a self-signed certificate if we don't have one.
274 if (access(file_crpt_file_cer, R_OK) != 0) {
275 syslog(LOG_INFO, "Generating a generic self-signed certificate.");
277 /* Same deal as before: always read the key from disk because
278 * it may or may not have just been generated.
280 fp = fopen(file_crpt_file_key, "r");
282 rsa = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
286 /* This also holds true for the CSR. */
291 if (pk=EVP_PKEY_new(), pk != NULL) {
292 EVP_PKEY_assign_RSA(pk, rsa);
295 fp = fopen(file_crpt_file_csr, "r");
297 req = PEM_read_X509_REQ(fp, NULL, NULL, NULL);
302 if (cer = X509_new(), cer != NULL) {
304 ASN1_INTEGER_set(X509_get_serialNumber(cer), 0);
305 X509_set_issuer_name(cer, req->req_info->subject);
306 X509_set_subject_name(cer, req->req_info->subject);
307 X509_gmtime_adj(X509_get_notBefore(cer),0);
308 X509_gmtime_adj(X509_get_notAfter(cer),(long)60*60*24*SIGN_DAYS);
309 req_pkey = X509_REQ_get_pubkey(req);
310 X509_set_pubkey(cer, req_pkey);
311 EVP_PKEY_free(req_pkey);
314 if (!X509_sign(cer, pk, EVP_md5())) {
315 syslog(LOG_CRIT, "X509_sign(): error");
318 /* Write it to disk. */
319 fp = fopen(file_crpt_file_cer, "w");
321 chmod(file_crpt_file_cer, 0600);
322 PEM_write_X509(fp, cer);
336 * Now try to bind to the key and certificate.
338 SSL_CTX_use_certificate_chain_file(ssl_ctx, file_crpt_file_cer);
339 SSL_CTX_use_PrivateKey_file(ssl_ctx, file_crpt_file_key, SSL_FILETYPE_PEM);
340 if ( !SSL_CTX_check_private_key(ssl_ctx) ) {
341 syslog(LOG_CRIT, "Cannot install certificate: %s", ERR_reason_error_string(ERR_get_error()));
344 /* Finally let the server know we're here */
345 CtdlRegisterProtoHook(cmd_stls, "STLS", "Start SSL/TLS session");
346 CtdlRegisterProtoHook(cmd_gtls, "GTLS",
347 "Get SSL/TLS session status");
348 CtdlRegisterSessionHook(endtls, EVT_STOP, PRIO_STOP + 10);
353 * client_write_ssl() Send binary data to the client encrypted.
355 void client_write_ssl(const char *buf, int nbytes)
363 while (nremain > 0) {
364 if (SSL_want_write(CC->ssl)) {
365 if ((SSL_read(CC->ssl, junk, 0)) < 1) {
366 syslog(LOG_DEBUG, "SSL_read in client_write: %s", ERR_reason_error_string(ERR_get_error()));
370 SSL_write(CC->ssl, &buf[nbytes - nremain], nremain);
374 errval = SSL_get_error(CC->ssl, retval);
375 if (errval == SSL_ERROR_WANT_READ ||
376 errval == SSL_ERROR_WANT_WRITE) {
380 syslog(LOG_DEBUG, "SSL_write got error %ld, ret %d", errval, retval);
382 syslog(LOG_DEBUG, "errno is %d", errno);
384 client_write(&buf[nbytes - nremain], nremain);
393 * read data from the encrypted layer.
395 int client_read_sslbuffer(StrBuf *buf, int timeout)
397 char sbuf[16384]; /* OpenSSL communicates in 16k blocks, so let's speak its native tongue. */
402 if (pssl == NULL) return(-1);
405 if (SSL_want_read(pssl)) {
406 if ((SSL_write(pssl, junk, 0)) < 1) {
407 syslog(LOG_DEBUG, "SSL_write in client_read");
410 rlen = SSL_read(pssl, sbuf, sizeof(sbuf));
414 errval = SSL_get_error(pssl, rlen);
415 if (errval == SSL_ERROR_WANT_READ || errval == SSL_ERROR_WANT_WRITE) {
419 syslog(LOG_DEBUG, "SSL_read got error %ld", errval);
423 StrBufAppendBufPlain(buf, sbuf, rlen, 0);
429 int client_readline_sslbuffer(StrBuf *Line, StrBuf *IOBuf, const char **Pos, int timeout)
431 CitContext *CCC = CC;
432 const char *pos = NULL;
435 int nSuccessLess = 0;
436 const char *pch = NULL;
438 if ((Line == NULL) ||
444 // *Error = ErrRBLF_PreConditionFailed;
449 if ((StrLength(IOBuf) > 0) &&
451 (pos < ChrPtr(IOBuf) + StrLength(IOBuf)))
454 pch = strchr(pch, '\n');
457 StrBufAppendBufPlain(Line, pos,
458 StrLength(IOBuf) - (pos - ChrPtr(IOBuf)), 0);
464 if ((pch > ChrPtr(IOBuf)) &&
465 (*(pch - 1) == '\r')) {
468 StrBufAppendBufPlain(Line, pos,
471 if (StrLength(IOBuf) <= (pch - ChrPtr(IOBuf) + 1)) {
477 return StrLength(Line);
482 while ((nSuccessLess < timeout) &&
484 (CCC->ssl != NULL)) {
486 rlen = client_read_sslbuffer(IOBuf, timeout);
488 // *Error = strerror(errno);
494 pLF = strchr(ChrPtr(IOBuf), '\n');
501 if (len > 0 && (*(pLF - 1) == '\r') )
503 StrBufAppendBufPlain(Line, pos, len, 0);
504 if (pLF + 1 >= ChrPtr(IOBuf) + StrLength(IOBuf))
510 return StrLength(Line);
512 // *Error = ErrRBLF_NotEnoughSentFromServer;
518 int client_read_sslblob(StrBuf *Target, long bytes, int timeout)
523 CitContext *CCC = CC;
525 baselen = StrLength(Target);
527 if (StrLength(CCC->RecvBuf.Buf) > 0)
533 if (CCC->RecvBuf.ReadWritePointer == NULL)
534 CCC->RecvBuf.ReadWritePointer = ChrPtr(CCC->RecvBuf.Buf);
535 pchs = ChrPtr(CCC->RecvBuf.Buf);
536 TotalLen = StrLength(CCC->RecvBuf.Buf);
537 RemainLen = TotalLen - (pchs - CCC->RecvBuf.ReadWritePointer);
538 if (RemainLen > bytes)
542 StrBufAppendBufPlain(Target,
543 CCC->RecvBuf.ReadWritePointer,
545 CCC->RecvBuf.ReadWritePointer += RemainLen;
547 if ((ChrPtr(CCC->RecvBuf.Buf) + StrLength(CCC->RecvBuf.Buf)) <= CCC->RecvBuf.ReadWritePointer)
549 CCC->RecvBuf.ReadWritePointer = NULL;
550 FlushStrBuf(CCC->RecvBuf.Buf);
554 if (StrLength(Target) >= bytes + baselen)
557 CCC->RecvBuf.ReadWritePointer = NULL;
559 while ((StrLength(Target) < bytes + baselen) &&
562 retval = client_read_sslbuffer(CCC->RecvBuf.Buf, timeout);
564 RemainRead = bytes - (StrLength (Target) - baselen);
565 if (RemainRead < StrLength(CCC->RecvBuf.Buf))
567 StrBufAppendBufPlain(
569 ChrPtr(CCC->RecvBuf.Buf),
571 CCC->RecvBuf.ReadWritePointer = ChrPtr(CCC->RecvBuf.Buf) + RemainRead;
574 StrBufAppendBuf(Target, CCC->RecvBuf.Buf, 0); /* todo: Buf > bytes? */
575 FlushStrBuf(CCC->RecvBuf.Buf);
579 FlushStrBuf(CCC->RecvBuf.Buf);
589 * CtdlStartTLS() starts SSL/TLS encryption for the current session. It
590 * must be supplied with pre-generated strings for responses of "ok," "no
591 * support for TLS," and "error" so that we can use this in any protocol.
593 void CtdlStartTLS(char *ok_response, char *nosup_response,
594 char *error_response) {
596 int retval, bits, alg_bits;
599 syslog(LOG_CRIT, "SSL failed: no ssl_ctx exists?");
600 if (nosup_response != NULL) cprintf("%s", nosup_response);
603 if (!(CC->ssl = SSL_new(ssl_ctx))) {
604 syslog(LOG_CRIT, "SSL_new failed: %s",
605 ERR_reason_error_string(ERR_get_error()));
606 if (error_response != NULL) cprintf("%s", error_response);
609 if (!(SSL_set_fd(CC->ssl, CC->client_socket))) {
610 syslog(LOG_CRIT, "SSL_set_fd failed: %s", ERR_reason_error_string(ERR_get_error()));
613 if (error_response != NULL) cprintf("%s", error_response);
616 if (ok_response != NULL) cprintf("%s", ok_response);
617 retval = SSL_accept(CC->ssl);
620 * Can't notify the client of an error here; they will
621 * discover the problem at the SSL layer and should
622 * revert to unencrypted communications.
625 char error_string[128];
627 errval = SSL_get_error(CC->ssl, retval);
628 syslog(LOG_CRIT, "SSL_accept failed: retval=%d, errval=%ld, err=%s",
631 ERR_error_string(errval, error_string)
637 BIO_set_close(CC->ssl->rbio, BIO_NOCLOSE);
638 bits = SSL_CIPHER_get_bits(SSL_get_current_cipher(CC->ssl), &alg_bits);
639 syslog(LOG_INFO, "SSL/TLS using %s on %s (%d of %d bits)",
640 SSL_CIPHER_get_name(SSL_get_current_cipher(CC->ssl)),
641 SSL_CIPHER_get_version(SSL_get_current_cipher(CC->ssl)),
643 CC->redirect_ssl = 1;
648 * cmd_stls() starts SSL/TLS encryption for the current session
650 void cmd_stls(char *params)
652 char ok_response[SIZ];
653 char nosup_response[SIZ];
654 char error_response[SIZ];
659 "%d Begin TLS negotiation now\n",
661 sprintf(nosup_response,
662 "%d TLS not supported here\n",
663 ERROR + CMD_NOT_SUPPORTED);
664 sprintf(error_response,
665 "%d TLS negotiation error\n",
666 ERROR + INTERNAL_ERROR);
668 CtdlStartTLS(ok_response, nosup_response, error_response);
673 * cmd_gtls() returns status info about the TLS connection
675 void cmd_gtls(char *params)
679 if (!CC->ssl || !CC->redirect_ssl) {
680 cprintf("%d Session is not encrypted.\n", ERROR);
684 SSL_CIPHER_get_bits(SSL_get_current_cipher(CC->ssl),
686 cprintf("%d %s|%s|%d|%d\n", CIT_OK,
687 SSL_CIPHER_get_version(SSL_get_current_cipher(CC->ssl)),
688 SSL_CIPHER_get_name(SSL_get_current_cipher(CC->ssl)),
694 * endtls() shuts down the TLS connection
696 * WARNING: This may make your session vulnerable to a known plaintext
697 * attack in the current implmentation.
702 CC->redirect_ssl = 0;
706 syslog(LOG_INFO, "Ending SSL/TLS");
707 SSL_shutdown(CC->ssl);
710 CC->redirect_ssl = 0;
715 * ssl_lock() callback for OpenSSL mutex locks
717 void ssl_lock(int mode, int n, const char *file, int line)
719 if (mode & CRYPTO_LOCK)
720 pthread_mutex_lock(SSLCritters[n]);
722 pthread_mutex_unlock(SSLCritters[n]);
724 #endif /* HAVE_OPENSSL */