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;
81 EVP_PKEY *req_pkey = NULL;
82 X509_NAME *name = NULL;
85 if (!access(EGD_POOL, F_OK))
89 syslog(LOG_CRIT, "PRNG not adequately seeded, won't do SSL/TLS");
93 malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t *));
95 syslog(LOG_EMERG, "citserver: can't allocate memory!!");
96 /* Nothing's been initialized, just die */
101 for (a = 0; a < CRYPTO_num_locks(); a++) {
102 SSLCritters[a] = malloc(sizeof(pthread_mutex_t));
103 if (!SSLCritters[a]) {
104 syslog(LOG_EMERG, "citserver: can't allocate memory!!");
105 /* Nothing's been initialized, just die */
108 pthread_mutex_init(SSLCritters[a], NULL);
113 * Initialize SSL transport layer
116 SSL_load_error_strings();
117 ssl_method = SSLv23_server_method();
118 if (!(ssl_ctx = SSL_CTX_new(ssl_method))) {
119 syslog(LOG_CRIT, "SSL_CTX_new failed: %s", ERR_reason_error_string(ERR_get_error()));
122 if (!(SSL_CTX_set_cipher_list(ssl_ctx, CIT_CIPHERS))) {
123 syslog(LOG_CRIT, "SSL: No ciphers available");
124 SSL_CTX_free(ssl_ctx);
129 #if SSLEAY_VERSION_NUMBER >= 0x00906000L
130 SSL_CTX_set_mode(ssl_ctx, SSL_CTX_get_mode(ssl_ctx) |
131 SSL_MODE_AUTO_RETRY);
135 CRYPTO_set_locking_callback(ssl_lock);
136 CRYPTO_set_id_callback(id_callback);
138 #if 0 // this doesn't work in newer openssl
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);
162 #endif // this doesn't work in newer openssl
164 /* Get our certificates in order.
165 * First, create the key/cert directory if it's not there already...
167 mkdir(ctdl_key_dir, 0700);
170 * Generate a key pair if we don't have one.
172 if (access(file_crpt_file_key, R_OK) != 0) {
173 syslog(LOG_INFO, "Generating RSA key pair.");
174 rsa = RSA_generate_key(1024, /* modulus size */
175 65537, /* exponent */
176 NULL, /* no callback */
177 NULL); /* no callback */
179 syslog(LOG_CRIT, "Key generation failed: %s", ERR_reason_error_string(ERR_get_error()));
182 fp = fopen(file_crpt_file_key, "w");
184 chmod(file_crpt_file_key, 0600);
185 if (PEM_write_RSAPrivateKey(fp, /* the file */
188 NULL, /* no passphr */
190 NULL, /* no callbk */
193 syslog(LOG_CRIT, "Cannot write key: %s", ERR_reason_error_string(ERR_get_error()));
194 unlink(file_crpt_file_key);
203 * If there is no certificate file on disk, we will be generating a self-signed certificate
204 * in the next step. Therefore, if we have neither a CSR nor a certificate, generate
205 * the CSR in this step so that the next step may commence.
207 if ( (access(file_crpt_file_cer, R_OK) != 0) && (access(file_crpt_file_csr, R_OK) != 0) ) {
208 syslog(LOG_INFO, "Generating a generic certificate signing request.");
211 * Read our key from the file. No, we don't just keep this
212 * in memory from the above key-generation function, because
213 * there is the possibility that the key was already on disk
214 * and we didn't just generate it now.
216 fp = fopen(file_crpt_file_key, "r");
218 rsa = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
224 /* Create a public key from the private key */
225 if (pk=EVP_PKEY_new(), pk != NULL) {
226 EVP_PKEY_assign_RSA(pk, rsa);
227 if (req = X509_REQ_new(), req != NULL) {
229 /* Set the public key */
230 X509_REQ_set_pubkey(req, pk);
231 X509_REQ_set_version(req, 0L);
233 name = X509_REQ_get_subject_name(req);
235 /* Tell it who we are */
236 X509_NAME_add_entry_by_txt(name, "C", MBSTRING_ASC, (unsigned const char *)"ZZ", -1, -1, 0);
237 X509_NAME_add_entry_by_txt(name, "ST", MBSTRING_ASC, (unsigned const char *)"The World", -1, -1, 0);
238 X509_NAME_add_entry_by_txt(name, "L", MBSTRING_ASC, (unsigned const char *)"My Location", -1, -1, 0);
239 X509_NAME_add_entry_by_txt(name, "O", MBSTRING_ASC, (unsigned const char *)"Generic certificate", -1, -1, 0);
240 X509_NAME_add_entry_by_txt(name, "OU", MBSTRING_ASC, (unsigned const char *)"Citadel server", -1, -1, 0);
241 X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC, (unsigned const char *)"*", -1, -1, 0);
242 X509_REQ_set_subject_name(req, name);
245 if (!X509_REQ_sign(req, pk, EVP_md5())) {
246 syslog(LOG_CRIT, "X509_REQ_sign(): error");
249 /* Write it to disk. */
250 fp = fopen(file_crpt_file_csr, "w");
252 chmod(file_crpt_file_csr, 0600);
253 PEM_write_X509_REQ(fp, req);
266 syslog(LOG_CRIT, "Unable to read private key.");
273 * Generate a self-signed certificate if we don't have one.
275 if (access(file_crpt_file_cer, R_OK) != 0) {
276 syslog(LOG_INFO, "Generating a generic self-signed certificate.");
278 /* Same deal as before: always read the key from disk because
279 * it may or may not have just been generated.
281 fp = fopen(file_crpt_file_key, "r");
283 rsa = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
287 /* This also holds true for the CSR. */
292 if (pk=EVP_PKEY_new(), pk != NULL) {
293 EVP_PKEY_assign_RSA(pk, rsa);
296 fp = fopen(file_crpt_file_csr, "r");
298 req = PEM_read_X509_REQ(fp, NULL, NULL, NULL);
303 if (cer = X509_new(), cer != NULL) {
305 ASN1_INTEGER_set(X509_get_serialNumber(cer), 0);
306 X509_set_issuer_name(cer, req->req_info->subject);
307 X509_set_subject_name(cer, req->req_info->subject);
308 X509_gmtime_adj(X509_get_notBefore(cer),0);
309 X509_gmtime_adj(X509_get_notAfter(cer),(long)60*60*24*SIGN_DAYS);
310 req_pkey = X509_REQ_get_pubkey(req);
311 X509_set_pubkey(cer, req_pkey);
312 EVP_PKEY_free(req_pkey);
315 if (!X509_sign(cer, pk, EVP_md5())) {
316 syslog(LOG_CRIT, "X509_sign(): error");
319 /* Write it to disk. */
320 fp = fopen(file_crpt_file_cer, "w");
322 chmod(file_crpt_file_cer, 0600);
323 PEM_write_X509(fp, cer);
337 * Now try to bind to the key and certificate.
339 SSL_CTX_use_certificate_chain_file(ssl_ctx, file_crpt_file_cer);
340 SSL_CTX_use_PrivateKey_file(ssl_ctx, file_crpt_file_key, SSL_FILETYPE_PEM);
341 if ( !SSL_CTX_check_private_key(ssl_ctx) ) {
342 syslog(LOG_CRIT, "Cannot install certificate: %s", ERR_reason_error_string(ERR_get_error()));
345 /* Finally let the server know we're here */
346 CtdlRegisterProtoHook(cmd_stls, "STLS", "Start SSL/TLS session");
347 CtdlRegisterProtoHook(cmd_gtls, "GTLS",
348 "Get SSL/TLS session status");
349 CtdlRegisterSessionHook(endtls, EVT_STOP, PRIO_STOP + 10);
354 * client_write_ssl() Send binary data to the client encrypted.
356 void client_write_ssl(const char *buf, int nbytes)
364 while (nremain > 0) {
365 if (SSL_want_write(CC->ssl)) {
366 if ((SSL_read(CC->ssl, junk, 0)) < 1) {
367 syslog(LOG_DEBUG, "SSL_read in client_write: %s", ERR_reason_error_string(ERR_get_error()));
371 SSL_write(CC->ssl, &buf[nbytes - nremain], nremain);
375 errval = SSL_get_error(CC->ssl, retval);
376 if (errval == SSL_ERROR_WANT_READ ||
377 errval == SSL_ERROR_WANT_WRITE) {
381 syslog(LOG_DEBUG, "SSL_write got error %ld, ret %d", errval, retval);
383 syslog(LOG_DEBUG, "errno is %d", errno);
385 client_write(&buf[nbytes - nremain], nremain);
394 * read data from the encrypted layer.
396 int client_read_sslbuffer(StrBuf *buf, int timeout)
398 char sbuf[16384]; /* OpenSSL communicates in 16k blocks, so let's speak its native tongue. */
403 if (pssl == NULL) return(-1);
406 if (SSL_want_read(pssl)) {
407 if ((SSL_write(pssl, junk, 0)) < 1) {
408 syslog(LOG_DEBUG, "SSL_write in client_read");
411 rlen = SSL_read(pssl, sbuf, sizeof(sbuf));
415 errval = SSL_get_error(pssl, rlen);
416 if (errval == SSL_ERROR_WANT_READ || errval == SSL_ERROR_WANT_WRITE) {
420 syslog(LOG_DEBUG, "SSL_read got error %ld", errval);
424 StrBufAppendBufPlain(buf, sbuf, rlen, 0);
430 int client_readline_sslbuffer(StrBuf *Line, StrBuf *IOBuf, const char **Pos, int timeout)
432 CitContext *CCC = CC;
433 const char *pos = NULL;
436 int nSuccessLess = 0;
437 const char *pch = NULL;
439 if ((Line == NULL) ||
445 // *Error = ErrRBLF_PreConditionFailed;
450 if ((StrLength(IOBuf) > 0) &&
452 (pos < ChrPtr(IOBuf) + StrLength(IOBuf)))
455 pch = strchr(pch, '\n');
458 StrBufAppendBufPlain(Line, pos,
459 StrLength(IOBuf) - (pos - ChrPtr(IOBuf)), 0);
465 if ((pch > ChrPtr(IOBuf)) &&
466 (*(pch - 1) == '\r')) {
469 StrBufAppendBufPlain(Line, pos,
472 if (StrLength(IOBuf) <= (pch - ChrPtr(IOBuf) + 1)) {
478 return StrLength(Line);
483 while ((nSuccessLess < timeout) &&
485 (CCC->ssl != NULL)) {
487 rlen = client_read_sslbuffer(IOBuf, timeout);
489 // *Error = strerror(errno);
495 pLF = strchr(ChrPtr(IOBuf), '\n');
502 if (len > 0 && (*(pLF - 1) == '\r') )
504 StrBufAppendBufPlain(Line, pos, len, 0);
505 if (pLF + 1 >= ChrPtr(IOBuf) + StrLength(IOBuf))
511 return StrLength(Line);
513 // *Error = ErrRBLF_NotEnoughSentFromServer;
519 int client_read_sslblob(StrBuf *Target, long bytes, int timeout)
524 CitContext *CCC = CC;
526 baselen = StrLength(Target);
528 if (StrLength(CCC->RecvBuf.Buf) > 0)
534 if (CCC->RecvBuf.ReadWritePointer == NULL)
535 CCC->RecvBuf.ReadWritePointer = ChrPtr(CCC->RecvBuf.Buf);
536 pchs = ChrPtr(CCC->RecvBuf.Buf);
537 TotalLen = StrLength(CCC->RecvBuf.Buf);
538 RemainLen = TotalLen - (pchs - CCC->RecvBuf.ReadWritePointer);
539 if (RemainLen > bytes)
543 StrBufAppendBufPlain(Target,
544 CCC->RecvBuf.ReadWritePointer,
546 CCC->RecvBuf.ReadWritePointer += RemainLen;
548 if ((ChrPtr(CCC->RecvBuf.Buf) + StrLength(CCC->RecvBuf.Buf)) <= CCC->RecvBuf.ReadWritePointer)
550 CCC->RecvBuf.ReadWritePointer = NULL;
551 FlushStrBuf(CCC->RecvBuf.Buf);
555 if (StrLength(Target) >= bytes + baselen)
558 CCC->RecvBuf.ReadWritePointer = NULL;
560 while ((StrLength(Target) < bytes + baselen) &&
563 retval = client_read_sslbuffer(CCC->RecvBuf.Buf, timeout);
565 RemainRead = bytes - (StrLength (Target) - baselen);
566 if (RemainRead < StrLength(CCC->RecvBuf.Buf))
568 StrBufAppendBufPlain(
570 ChrPtr(CCC->RecvBuf.Buf),
572 CCC->RecvBuf.ReadWritePointer = ChrPtr(CCC->RecvBuf.Buf) + RemainRead;
575 StrBufAppendBuf(Target, CCC->RecvBuf.Buf, 0); /* todo: Buf > bytes? */
576 FlushStrBuf(CCC->RecvBuf.Buf);
580 FlushStrBuf(CCC->RecvBuf.Buf);
590 * CtdlStartTLS() starts SSL/TLS encryption for the current session. It
591 * must be supplied with pre-generated strings for responses of "ok," "no
592 * support for TLS," and "error" so that we can use this in any protocol.
594 void CtdlStartTLS(char *ok_response, char *nosup_response,
595 char *error_response) {
597 int retval, bits, alg_bits;
600 syslog(LOG_CRIT, "SSL failed: no ssl_ctx exists?");
601 if (nosup_response != NULL) cprintf("%s", nosup_response);
604 if (!(CC->ssl = SSL_new(ssl_ctx))) {
605 syslog(LOG_CRIT, "SSL_new failed: %s",
606 ERR_reason_error_string(ERR_get_error()));
607 if (error_response != NULL) cprintf("%s", error_response);
610 if (!(SSL_set_fd(CC->ssl, CC->client_socket))) {
611 syslog(LOG_CRIT, "SSL_set_fd failed: %s", ERR_reason_error_string(ERR_get_error()));
614 if (error_response != NULL) cprintf("%s", error_response);
617 if (ok_response != NULL) cprintf("%s", ok_response);
618 retval = SSL_accept(CC->ssl);
621 * Can't notify the client of an error here; they will
622 * discover the problem at the SSL layer and should
623 * revert to unencrypted communications.
626 char error_string[128];
628 errval = SSL_get_error(CC->ssl, retval);
629 syslog(LOG_CRIT, "SSL_accept failed: retval=%d, errval=%ld, err=%s",
632 ERR_error_string(errval, error_string)
638 BIO_set_close(CC->ssl->rbio, BIO_NOCLOSE);
639 bits = SSL_CIPHER_get_bits(SSL_get_current_cipher(CC->ssl), &alg_bits);
640 syslog(LOG_INFO, "SSL/TLS using %s on %s (%d of %d bits)",
641 SSL_CIPHER_get_name(SSL_get_current_cipher(CC->ssl)),
642 SSL_CIPHER_get_version(SSL_get_current_cipher(CC->ssl)),
644 CC->redirect_ssl = 1;
649 * cmd_stls() starts SSL/TLS encryption for the current session
651 void cmd_stls(char *params)
653 char ok_response[SIZ];
654 char nosup_response[SIZ];
655 char error_response[SIZ];
660 "%d Begin TLS negotiation now\n",
662 sprintf(nosup_response,
663 "%d TLS not supported here\n",
664 ERROR + CMD_NOT_SUPPORTED);
665 sprintf(error_response,
666 "%d TLS negotiation error\n",
667 ERROR + INTERNAL_ERROR);
669 CtdlStartTLS(ok_response, nosup_response, error_response);
674 * cmd_gtls() returns status info about the TLS connection
676 void cmd_gtls(char *params)
680 if (!CC->ssl || !CC->redirect_ssl) {
681 cprintf("%d Session is not encrypted.\n", ERROR);
685 SSL_CIPHER_get_bits(SSL_get_current_cipher(CC->ssl),
687 cprintf("%d %s|%s|%d|%d\n", CIT_OK,
688 SSL_CIPHER_get_version(SSL_get_current_cipher(CC->ssl)),
689 SSL_CIPHER_get_name(SSL_get_current_cipher(CC->ssl)),
695 * endtls() shuts down the TLS connection
697 * WARNING: This may make your session vulnerable to a known plaintext
698 * attack in the current implmentation.
703 CC->redirect_ssl = 0;
707 syslog(LOG_INFO, "Ending SSL/TLS");
708 SSL_shutdown(CC->ssl);
711 CC->redirect_ssl = 0;
716 * ssl_lock() callback for OpenSSL mutex locks
718 void ssl_lock(int mode, int n, const char *file, int line)
720 if (mode & CRYPTO_LOCK)
721 pthread_mutex_lock(SSLCritters[n]);
723 pthread_mutex_unlock(SSLCritters[n]);
725 #endif /* HAVE_OPENSSL */