2 * Copyright (c) 1987-2012 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.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
22 #include <sys/types.h>
26 #include <openssl/ssl.h>
27 #include <openssl/err.h>
28 #include <openssl/rand.h>
31 #if TIME_WITH_SYS_TIME
32 # include <sys/time.h>
36 # include <sys/time.h>
46 #ifdef HAVE_SYS_SELECT_H
47 #include <sys/select.h>
51 #include <libcitadel.h>
53 #include "serv_crypto.h"
54 #include "sysdep_decls.h"
59 #include "ctdl_module.h"
60 /* TODO: should we use the standard module init stuff to start this? */
61 /* TODO: should we register an event handler to call destruct_ssl? */
64 SSL_CTX *ssl_ctx; /* SSL context */
65 pthread_mutex_t **SSLCritters; /* Things needing locking */
67 static unsigned long id_callback(void)
69 return (unsigned long) pthread_self();
72 void destruct_ssl(void)
75 for (a = 0; a < CRYPTO_num_locks(); a++)
82 const SSL_METHOD *ssl_method;
88 EVP_PKEY *req_pkey = NULL;
89 X509_NAME *name = NULL;
92 if (!access(EGD_POOL, F_OK))
97 "PRNG not adequately seeded, won't do SSL/TLS\n");
101 malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t *));
103 syslog(LOG_EMERG, "citserver: can't allocate memory!!\n");
104 /* Nothing's been initialized, just die */
109 for (a = 0; a < CRYPTO_num_locks(); a++) {
110 SSLCritters[a] = malloc(sizeof(pthread_mutex_t));
111 if (!SSLCritters[a]) {
113 "citserver: can't allocate memory!!\n");
114 /* Nothing's been initialized, just die */
117 pthread_mutex_init(SSLCritters[a], NULL);
122 * Initialize SSL transport layer
125 SSL_load_error_strings();
126 ssl_method = SSLv23_server_method();
127 if (!(ssl_ctx = SSL_CTX_new(ssl_method))) {
128 syslog(LOG_CRIT, "SSL_CTX_new failed: %s\n",
129 ERR_reason_error_string(ERR_get_error()));
132 if (!(SSL_CTX_set_cipher_list(ssl_ctx, CIT_CIPHERS))) {
133 syslog(LOG_CRIT, "SSL: No ciphers available\n");
134 SSL_CTX_free(ssl_ctx);
139 #if SSLEAY_VERSION_NUMBER >= 0x00906000L
140 SSL_CTX_set_mode(ssl_ctx, SSL_CTX_get_mode(ssl_ctx) |
141 SSL_MODE_AUTO_RETRY);
145 CRYPTO_set_locking_callback(ssl_lock);
146 CRYPTO_set_id_callback(id_callback);
148 /* Load DH parameters into the context */
151 syslog(LOG_CRIT, "init_ssl() can't allocate a DH object: %s\n",
152 ERR_reason_error_string(ERR_get_error()));
153 SSL_CTX_free(ssl_ctx);
157 if (!(BN_hex2bn(&(dh->p), DH_P))) {
158 syslog(LOG_CRIT, "init_ssl() can't assign DH_P: %s\n",
159 ERR_reason_error_string(ERR_get_error()));
160 SSL_CTX_free(ssl_ctx);
164 if (!(BN_hex2bn(&(dh->g), DH_G))) {
165 syslog(LOG_CRIT, "init_ssl() can't assign DH_G: %s\n",
166 ERR_reason_error_string(ERR_get_error()));
167 SSL_CTX_free(ssl_ctx);
172 SSL_CTX_set_tmp_dh(ssl_ctx, dh);
175 /* Get our certificates in order.
176 * First, create the key/cert directory if it's not there already...
178 mkdir(ctdl_key_dir, 0700);
181 * Generate a key pair if we don't have one.
183 if (access(file_crpt_file_key, R_OK) != 0) {
184 syslog(LOG_INFO, "Generating RSA key pair.\n");
185 rsa = RSA_generate_key(1024, /* modulus size */
186 65537, /* exponent */
187 NULL, /* no callback */
188 NULL); /* no callback */
190 syslog(LOG_CRIT, "Key generation failed: %s\n",
191 ERR_reason_error_string(ERR_get_error()));
194 fp = fopen(file_crpt_file_key, "w");
196 chmod(file_crpt_file_key, 0600);
197 if (PEM_write_RSAPrivateKey(fp, /* the file */
200 NULL, /* no passphr */
202 NULL, /* no callbk */
205 syslog(LOG_CRIT, "Cannot write key: %s\n",
206 ERR_reason_error_string(ERR_get_error()));
207 unlink(file_crpt_file_key);
216 * If there is no certificate file on disk, we will be generating a self-signed certificate
217 * in the next step. Therefore, if we have neither a CSR nor a certificate, generate
218 * the CSR in this step so that the next step may commence.
220 if ( (access(file_crpt_file_cer, R_OK) != 0) && (access(file_crpt_file_csr, R_OK) != 0) ) {
221 syslog(LOG_INFO, "Generating a certificate signing request.\n");
224 * Read our key from the file. No, we don't just keep this
225 * in memory from the above key-generation function, because
226 * there is the possibility that the key was already on disk
227 * and we didn't just generate it now.
229 fp = fopen(file_crpt_file_key, "r");
231 rsa = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
237 /* Create a public key from the private key */
238 if (pk=EVP_PKEY_new(), pk != NULL) {
239 EVP_PKEY_assign_RSA(pk, rsa);
240 if (req = X509_REQ_new(), req != NULL) {
242 /* Set the public key */
243 X509_REQ_set_pubkey(req, pk);
244 X509_REQ_set_version(req, 0L);
246 name = X509_REQ_get_subject_name(req);
248 /* Tell it who we are */
251 X509_NAME_add_entry_by_txt(name, "C",
252 MBSTRING_ASC, "US", -1, -1, 0);
254 X509_NAME_add_entry_by_txt(name, "ST",
255 MBSTRING_ASC, "New York", -1, -1, 0);
257 X509_NAME_add_entry_by_txt(name, "L",
258 MBSTRING_ASC, "Mount Kisco", -1, -1, 0);
261 X509_NAME_add_entry_by_txt(name, "O",
263 (unsigned char*) config.c_humannode,
266 X509_NAME_add_entry_by_txt(name, "OU",
268 (unsigned const char*)"Citadel server",
271 /* X509_NAME_add_entry_by_txt(name, "CN",
272 MBSTRING_ASC, config.c_fqdn, -1, -1, 0);
275 X509_NAME_add_entry_by_txt(name,
278 (const unsigned char *)"*", -1, -1, 0);
280 X509_REQ_set_subject_name(req, name);
283 if (!X509_REQ_sign(req, pk, EVP_md5())) {
284 syslog(LOG_CRIT, "X509_REQ_sign(): error\n");
287 /* Write it to disk. */
288 fp = fopen(file_crpt_file_csr, "w");
290 chmod(file_crpt_file_csr, 0600);
291 PEM_write_X509_REQ(fp, req);
304 syslog(LOG_CRIT, "Unable to read private key.\n");
311 * Generate a self-signed certificate if we don't have one.
313 if (access(file_crpt_file_cer, R_OK) != 0) {
314 syslog(LOG_INFO, "Generating a self-signed certificate.\n");
316 /* Same deal as before: always read the key from disk because
317 * it may or may not have just been generated.
319 fp = fopen(file_crpt_file_key, "r");
321 rsa = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
325 /* This also holds true for the CSR. */
330 if (pk=EVP_PKEY_new(), pk != NULL) {
331 EVP_PKEY_assign_RSA(pk, rsa);
334 fp = fopen(file_crpt_file_csr, "r");
336 req = PEM_read_X509_REQ(fp, NULL, NULL, NULL);
341 if (cer = X509_new(), cer != NULL) {
343 ASN1_INTEGER_set(X509_get_serialNumber(cer), 0);
344 X509_set_issuer_name(cer, req->req_info->subject);
345 X509_set_subject_name(cer, req->req_info->subject);
346 X509_gmtime_adj(X509_get_notBefore(cer),0);
347 X509_gmtime_adj(X509_get_notAfter(cer),(long)60*60*24*SIGN_DAYS);
348 req_pkey = X509_REQ_get_pubkey(req);
349 X509_set_pubkey(cer, req_pkey);
350 EVP_PKEY_free(req_pkey);
353 if (!X509_sign(cer, pk, EVP_md5())) {
354 syslog(LOG_CRIT, "X509_sign(): error\n");
357 /* Write it to disk. */
358 fp = fopen(file_crpt_file_cer, "w");
360 chmod(file_crpt_file_cer, 0600);
361 PEM_write_X509(fp, cer);
375 * Now try to bind to the key and certificate.
377 SSL_CTX_use_certificate_chain_file(ssl_ctx, file_crpt_file_cer);
378 SSL_CTX_use_PrivateKey_file(ssl_ctx, file_crpt_file_key, SSL_FILETYPE_PEM);
379 if ( !SSL_CTX_check_private_key(ssl_ctx) ) {
380 syslog(LOG_CRIT, "Cannot install certificate: %s\n",
381 ERR_reason_error_string(ERR_get_error()));
384 /* Finally let the server know we're here */
385 CtdlRegisterProtoHook(cmd_stls, "STLS", "Start SSL/TLS session");
386 CtdlRegisterProtoHook(cmd_gtls, "GTLS",
387 "Get SSL/TLS session status");
388 CtdlRegisterSessionHook(endtls, EVT_STOP);
393 * client_write_ssl() Send binary data to the client encrypted.
395 void client_write_ssl(const char *buf, int nbytes)
403 while (nremain > 0) {
404 if (SSL_want_write(CC->ssl)) {
405 if ((SSL_read(CC->ssl, junk, 0)) < 1) {
406 syslog(LOG_DEBUG, "SSL_read in client_write: %s\n", ERR_reason_error_string(ERR_get_error()));
410 SSL_write(CC->ssl, &buf[nbytes - nremain], nremain);
414 errval = SSL_get_error(CC->ssl, retval);
415 if (errval == SSL_ERROR_WANT_READ ||
416 errval == SSL_ERROR_WANT_WRITE) {
420 syslog(LOG_DEBUG, "SSL_write got error %ld, ret %d\n", errval, retval);
422 syslog(LOG_DEBUG, "errno is %d\n", errno);
424 client_write(&buf[nbytes - nremain], nremain);
433 * read data from the encrypted layer.
435 int client_read_sslbuffer(StrBuf *buf, int timeout)
437 char sbuf[16384]; /* OpenSSL communicates in 16k blocks, so let's speak its native tongue. */
442 if (pssl == NULL) return(-1);
445 if (SSL_want_read(pssl)) {
446 if ((SSL_write(pssl, junk, 0)) < 1) {
447 syslog(LOG_DEBUG, "SSL_write in client_read\n");
450 rlen = SSL_read(pssl, sbuf, sizeof(sbuf));
454 errval = SSL_get_error(pssl, rlen);
455 if (errval == SSL_ERROR_WANT_READ || errval == SSL_ERROR_WANT_WRITE) {
459 syslog(LOG_DEBUG, "SSL_read got error %ld\n", errval);
463 StrBufAppendBufPlain(buf, sbuf, rlen, 0);
469 int client_readline_sslbuffer(StrBuf *Line, StrBuf *IOBuf, const char **Pos, int timeout)
471 CitContext *CCC = CC;
472 const char *pos = NULL;
475 int nSuccessLess = 0;
476 const char *pch = NULL;
478 if ((Line == NULL) ||
484 // *Error = ErrRBLF_PreConditionFailed;
489 if ((StrLength(IOBuf) > 0) &&
491 (pos < ChrPtr(IOBuf) + StrLength(IOBuf)))
494 pch = strchr(pch, '\n');
497 StrBufAppendBufPlain(Line, pos,
498 StrLength(IOBuf) - (pos - ChrPtr(IOBuf)), 0);
504 if ((pch > ChrPtr(IOBuf)) &&
505 (*(pch - 1) == '\r')) {
508 StrBufAppendBufPlain(Line, pos,
511 if (StrLength(IOBuf) <= (pch - ChrPtr(IOBuf) + 1)) {
517 return StrLength(Line);
522 while ((nSuccessLess < timeout) &&
524 (CCC->ssl != NULL)) {
526 rlen = client_read_sslbuffer(IOBuf, timeout);
528 // *Error = strerror(errno);
534 pLF = strchr(ChrPtr(IOBuf), '\n');
541 if (len > 0 && (*(pLF - 1) == '\r') )
543 StrBufAppendBufPlain(Line, pos, len, 0);
544 if (pLF + 1 >= ChrPtr(IOBuf) + StrLength(IOBuf))
550 return StrLength(Line);
552 // *Error = ErrRBLF_NotEnoughSentFromServer;
558 int client_read_sslblob(StrBuf *Target, long bytes, int timeout)
563 CitContext *CCC = CC;
565 baselen = StrLength(Target);
567 if (StrLength(CCC->RecvBuf.Buf) > 0)
573 if (CCC->RecvBuf.ReadWritePointer == NULL)
574 CCC->RecvBuf.ReadWritePointer = ChrPtr(CCC->RecvBuf.Buf);
575 pchs = ChrPtr(CCC->RecvBuf.Buf);
576 TotalLen = StrLength(CCC->RecvBuf.Buf);
577 RemainLen = TotalLen - (pchs - CCC->RecvBuf.ReadWritePointer);
578 if (RemainLen > bytes)
582 StrBufAppendBufPlain(Target,
583 CCC->RecvBuf.ReadWritePointer,
585 CCC->RecvBuf.ReadWritePointer += RemainLen;
587 if ((ChrPtr(CCC->RecvBuf.Buf) + StrLength(CCC->RecvBuf.Buf)) <= CCC->RecvBuf.ReadWritePointer)
589 CCC->RecvBuf.ReadWritePointer = NULL;
590 FlushStrBuf(CCC->RecvBuf.Buf);
594 if (StrLength(Target) >= bytes + baselen)
597 CCC->RecvBuf.ReadWritePointer = NULL;
599 while ((StrLength(Target) < bytes + baselen) &&
602 retval = client_read_sslbuffer(CCC->RecvBuf.Buf, timeout);
604 RemainRead = bytes - (StrLength (Target) - baselen);
605 if (RemainRead < StrLength(CCC->RecvBuf.Buf))
607 StrBufAppendBufPlain(
609 ChrPtr(CCC->RecvBuf.Buf),
611 CCC->RecvBuf.ReadWritePointer = ChrPtr(CCC->RecvBuf.Buf) + RemainRead;
614 StrBufAppendBuf(Target, CCC->RecvBuf.Buf, 0); /* todo: Buf > bytes? */
615 FlushStrBuf(CCC->RecvBuf.Buf);
619 FlushStrBuf(CCC->RecvBuf.Buf);
629 * CtdlStartTLS() starts SSL/TLS encryption for the current session. It
630 * must be supplied with pre-generated strings for responses of "ok," "no
631 * support for TLS," and "error" so that we can use this in any protocol.
633 void CtdlStartTLS(char *ok_response, char *nosup_response,
634 char *error_response) {
636 int retval, bits, alg_bits;
639 syslog(LOG_CRIT, "SSL failed: no ssl_ctx exists?\n");
640 if (nosup_response != NULL) cprintf("%s", nosup_response);
643 if (!(CC->ssl = SSL_new(ssl_ctx))) {
644 syslog(LOG_CRIT, "SSL_new failed: %s\n",
645 ERR_reason_error_string(ERR_get_error()));
646 if (error_response != NULL) cprintf("%s", error_response);
649 if (!(SSL_set_fd(CC->ssl, CC->client_socket))) {
650 syslog(LOG_CRIT, "SSL_set_fd failed: %s\n",
651 ERR_reason_error_string(ERR_get_error()));
654 if (error_response != NULL) cprintf("%s", error_response);
657 if (ok_response != NULL) cprintf("%s", ok_response);
658 retval = SSL_accept(CC->ssl);
661 * Can't notify the client of an error here; they will
662 * discover the problem at the SSL layer and should
663 * revert to unencrypted communications.
666 char error_string[128];
668 errval = SSL_get_error(CC->ssl, retval);
669 syslog(LOG_CRIT, "SSL_accept failed: retval=%d, errval=%ld, err=%s\n",
672 ERR_error_string(errval, error_string)
678 BIO_set_close(CC->ssl->rbio, BIO_NOCLOSE);
679 bits = SSL_CIPHER_get_bits(SSL_get_current_cipher(CC->ssl), &alg_bits);
680 syslog(LOG_INFO, "SSL/TLS using %s on %s (%d of %d bits)\n",
681 SSL_CIPHER_get_name(SSL_get_current_cipher(CC->ssl)),
682 SSL_CIPHER_get_version(SSL_get_current_cipher(CC->ssl)),
684 CC->redirect_ssl = 1;
689 * cmd_stls() starts SSL/TLS encryption for the current session
691 void cmd_stls(char *params)
693 char ok_response[SIZ];
694 char nosup_response[SIZ];
695 char error_response[SIZ];
700 "%d Begin TLS negotiation now\n",
702 sprintf(nosup_response,
703 "%d TLS not supported here\n",
704 ERROR + CMD_NOT_SUPPORTED);
705 sprintf(error_response,
706 "%d TLS negotiation error\n",
707 ERROR + INTERNAL_ERROR);
709 CtdlStartTLS(ok_response, nosup_response, error_response);
714 * cmd_gtls() returns status info about the TLS connection
716 void cmd_gtls(char *params)
720 if (!CC->ssl || !CC->redirect_ssl) {
721 cprintf("%d Session is not encrypted.\n", ERROR);
725 SSL_CIPHER_get_bits(SSL_get_current_cipher(CC->ssl),
727 cprintf("%d %s|%s|%d|%d\n", CIT_OK,
728 SSL_CIPHER_get_version(SSL_get_current_cipher(CC->ssl)),
729 SSL_CIPHER_get_name(SSL_get_current_cipher(CC->ssl)),
735 * endtls() shuts down the TLS connection
737 * WARNING: This may make your session vulnerable to a known plaintext
738 * attack in the current implmentation.
743 CC->redirect_ssl = 0;
747 syslog(LOG_INFO, "Ending SSL/TLS\n");
748 SSL_shutdown(CC->ssl);
751 CC->redirect_ssl = 0;
756 * ssl_lock() callback for OpenSSL mutex locks
758 void ssl_lock(int mode, int n, const char *file, int line)
760 if (mode & CRYPTO_LOCK)
761 pthread_mutex_lock(SSLCritters[n]);
763 pthread_mutex_unlock(SSLCritters[n]);
765 #endif /* HAVE_OPENSSL */