3 * Copyright (c) 1987-2009 by the citadel.org team
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 3 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23 #include <sys/types.h>
27 #include <openssl/ssl.h>
28 #include <openssl/err.h>
29 #include <openssl/rand.h>
32 #if TIME_WITH_SYS_TIME
33 # include <sys/time.h>
37 # include <sys/time.h>
47 #ifdef HAVE_SYS_SELECT_H
48 #include <sys/select.h>
52 #include <libcitadel.h>
54 #include "serv_crypto.h"
55 #include "sysdep_decls.h"
60 #include "ctdl_module.h"
61 /* TODO: should we use the standard module init stuff to start this? */
62 /* TODO: should we register an event handler to call destruct_ssl? */
65 SSL_CTX *ssl_ctx; /* SSL context */
66 pthread_mutex_t **SSLCritters; /* Things needing locking */
68 static unsigned long id_callback(void)
70 return (unsigned long) pthread_self();
73 void destruct_ssl(void)
76 for (a = 0; a < CRYPTO_num_locks(); a++)
83 SSL_METHOD *ssl_method;
89 EVP_PKEY *req_pkey = NULL;
90 X509_NAME *name = NULL;
93 if (!access(EGD_POOL, F_OK))
97 CtdlLogPrintf(CTDL_CRIT,
98 "PRNG not adequately seeded, won't do SSL/TLS\n");
102 malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t *));
104 CtdlLogPrintf(CTDL_EMERG, "citserver: can't allocate memory!!\n");
105 /* Nothing's been initialized, just die */
110 for (a = 0; a < CRYPTO_num_locks(); a++) {
111 SSLCritters[a] = malloc(sizeof(pthread_mutex_t));
112 if (!SSLCritters[a]) {
113 CtdlLogPrintf(CTDL_EMERG,
114 "citserver: can't allocate memory!!\n");
115 /* Nothing's been initialized, just die */
118 pthread_mutex_init(SSLCritters[a], NULL);
123 * Initialize SSL transport layer
126 SSL_load_error_strings();
127 ssl_method = SSLv23_server_method();
128 if (!(ssl_ctx = SSL_CTX_new(ssl_method))) {
129 CtdlLogPrintf(CTDL_CRIT, "SSL_CTX_new failed: %s\n",
130 ERR_reason_error_string(ERR_get_error()));
133 if (!(SSL_CTX_set_cipher_list(ssl_ctx, CIT_CIPHERS))) {
134 CtdlLogPrintf(CTDL_CRIT, "SSL: No ciphers available\n");
135 SSL_CTX_free(ssl_ctx);
140 #if SSLEAY_VERSION_NUMBER >= 0x00906000L
141 SSL_CTX_set_mode(ssl_ctx, SSL_CTX_get_mode(ssl_ctx) |
142 SSL_MODE_AUTO_RETRY);
146 CRYPTO_set_locking_callback(ssl_lock);
147 CRYPTO_set_id_callback(id_callback);
149 /* Load DH parameters into the context */
152 CtdlLogPrintf(CTDL_CRIT, "init_ssl() can't allocate a DH object: %s\n",
153 ERR_reason_error_string(ERR_get_error()));
154 SSL_CTX_free(ssl_ctx);
158 if (!(BN_hex2bn(&(dh->p), DH_P))) {
159 CtdlLogPrintf(CTDL_CRIT, "init_ssl() can't assign DH_P: %s\n",
160 ERR_reason_error_string(ERR_get_error()));
161 SSL_CTX_free(ssl_ctx);
165 if (!(BN_hex2bn(&(dh->g), DH_G))) {
166 CtdlLogPrintf(CTDL_CRIT, "init_ssl() can't assign DH_G: %s\n",
167 ERR_reason_error_string(ERR_get_error()));
168 SSL_CTX_free(ssl_ctx);
173 SSL_CTX_set_tmp_dh(ssl_ctx, dh);
176 /* Get our certificates in order.
177 * First, create the key/cert directory if it's not there already...
179 mkdir(ctdl_key_dir, 0700);
182 * Generate a key pair if we don't have one.
184 if (access(file_crpt_file_key, R_OK) != 0) {
185 CtdlLogPrintf(CTDL_INFO, "Generating RSA key pair.\n");
186 rsa = RSA_generate_key(1024, /* modulus size */
187 65537, /* exponent */
188 NULL, /* no callback */
189 NULL); /* no callback */
191 CtdlLogPrintf(CTDL_CRIT, "Key generation failed: %s\n",
192 ERR_reason_error_string(ERR_get_error()));
195 fp = fopen(file_crpt_file_key, "w");
197 chmod(file_crpt_file_key, 0600);
198 if (PEM_write_RSAPrivateKey(fp, /* the file */
201 NULL, /* no passphr */
203 NULL, /* no callbk */
206 CtdlLogPrintf(CTDL_CRIT, "Cannot write key: %s\n",
207 ERR_reason_error_string(ERR_get_error()));
208 unlink(file_crpt_file_key);
217 * If there is no certificate file on disk, we will be generating a self-signed certificate
218 * in the next step. Therefore, if we have neither a CSR nor a certificate, generate
219 * the CSR in this step so that the next step may commence.
221 if ( (access(file_crpt_file_cer, R_OK) != 0) && (access(file_crpt_file_csr, R_OK) != 0) ) {
222 CtdlLogPrintf(CTDL_INFO, "Generating a certificate signing request.\n");
225 * Read our key from the file. No, we don't just keep this
226 * in memory from the above key-generation function, because
227 * there is the possibility that the key was already on disk
228 * and we didn't just generate it now.
230 fp = fopen(file_crpt_file_key, "r");
232 rsa = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
238 /* Create a public key from the private key */
239 if (pk=EVP_PKEY_new(), pk != NULL) {
240 EVP_PKEY_assign_RSA(pk, rsa);
241 if (req = X509_REQ_new(), req != NULL) {
243 /* Set the public key */
244 X509_REQ_set_pubkey(req, pk);
245 X509_REQ_set_version(req, 0L);
247 name = X509_REQ_get_subject_name(req);
249 /* Tell it who we are */
252 X509_NAME_add_entry_by_txt(name, "C",
253 MBSTRING_ASC, "US", -1, -1, 0);
255 X509_NAME_add_entry_by_txt(name, "ST",
256 MBSTRING_ASC, "New York", -1, -1, 0);
258 X509_NAME_add_entry_by_txt(name, "L",
259 MBSTRING_ASC, "Mount Kisco", -1, -1, 0);
262 X509_NAME_add_entry_by_txt(name, "O",
264 (unsigned char*) config.c_humannode,
267 X509_NAME_add_entry_by_txt(name, "OU",
269 (unsigned const char*)"Citadel server",
272 /* X509_NAME_add_entry_by_txt(name, "CN",
273 MBSTRING_ASC, config.c_fqdn, -1, -1, 0);
276 X509_NAME_add_entry_by_txt(name,
279 (const unsigned char *)"*", -1, -1, 0);
281 X509_REQ_set_subject_name(req, name);
284 if (!X509_REQ_sign(req, pk, EVP_md5())) {
285 CtdlLogPrintf(CTDL_CRIT, "X509_REQ_sign(): error\n");
288 /* Write it to disk. */
289 fp = fopen(file_crpt_file_csr, "w");
291 chmod(file_crpt_file_csr, 0600);
292 PEM_write_X509_REQ(fp, req);
305 CtdlLogPrintf(CTDL_CRIT, "Unable to read private key.\n");
312 * Generate a self-signed certificate if we don't have one.
314 if (access(file_crpt_file_cer, R_OK) != 0) {
315 CtdlLogPrintf(CTDL_INFO, "Generating a self-signed certificate.\n");
317 /* Same deal as before: always read the key from disk because
318 * it may or may not have just been generated.
320 fp = fopen(file_crpt_file_key, "r");
322 rsa = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
326 /* This also holds true for the CSR. */
331 if (pk=EVP_PKEY_new(), pk != NULL) {
332 EVP_PKEY_assign_RSA(pk, rsa);
335 fp = fopen(file_crpt_file_csr, "r");
337 req = PEM_read_X509_REQ(fp, NULL, NULL, NULL);
342 if (cer = X509_new(), cer != NULL) {
344 ASN1_INTEGER_set(X509_get_serialNumber(cer), 0);
345 X509_set_issuer_name(cer, req->req_info->subject);
346 X509_set_subject_name(cer, req->req_info->subject);
347 X509_gmtime_adj(X509_get_notBefore(cer),0);
348 X509_gmtime_adj(X509_get_notAfter(cer),(long)60*60*24*SIGN_DAYS);
349 req_pkey = X509_REQ_get_pubkey(req);
350 X509_set_pubkey(cer, req_pkey);
351 EVP_PKEY_free(req_pkey);
354 if (!X509_sign(cer, pk, EVP_md5())) {
355 CtdlLogPrintf(CTDL_CRIT, "X509_sign(): error\n");
358 /* Write it to disk. */
359 fp = fopen(file_crpt_file_cer, "w");
361 chmod(file_crpt_file_cer, 0600);
362 PEM_write_X509(fp, cer);
376 * Now try to bind to the key and certificate.
378 SSL_CTX_use_certificate_chain_file(ssl_ctx, file_crpt_file_cer);
379 SSL_CTX_use_PrivateKey_file(ssl_ctx, file_crpt_file_key, SSL_FILETYPE_PEM);
380 if ( !SSL_CTX_check_private_key(ssl_ctx) ) {
381 CtdlLogPrintf(CTDL_CRIT, "Cannot install certificate: %s\n",
382 ERR_reason_error_string(ERR_get_error()));
385 /* Finally let the server know we're here */
386 CtdlRegisterProtoHook(cmd_stls, "STLS", "Start SSL/TLS session");
387 CtdlRegisterProtoHook(cmd_gtls, "GTLS",
388 "Get SSL/TLS session status");
389 CtdlRegisterSessionHook(endtls, EVT_STOP);
394 * client_write_ssl() Send binary data to the client encrypted.
396 void client_write_ssl(const char *buf, int nbytes)
404 while (nremain > 0) {
405 if (SSL_want_write(CC->ssl)) {
406 if ((SSL_read(CC->ssl, junk, 0)) < 1) {
407 CtdlLogPrintf(CTDL_DEBUG, "SSL_read in client_write: %s\n", ERR_reason_error_string(ERR_get_error()));
411 SSL_write(CC->ssl, &buf[nbytes - nremain], nremain);
415 errval = SSL_get_error(CC->ssl, retval);
416 if (errval == SSL_ERROR_WANT_READ ||
417 errval == SSL_ERROR_WANT_WRITE) {
421 CtdlLogPrintf(CTDL_DEBUG, "SSL_write got error %ld, ret %d\n", errval, retval);
423 CtdlLogPrintf(CTDL_DEBUG, "errno is %d\n", errno);
425 client_write(&buf[nbytes - nremain], nremain);
434 * client_read_ssl() - read data from the encrypted layer.
436 int client_read_ssl(char *buf, int bytes, int timeout)
448 while (len < bytes) {
451 * This code is disabled because we don't need it when
452 * using blocking reads (which we are). -IO
455 s = BIO_get_fd(CC->ssl->rbio, NULL);
460 retval = select(s + 1, &rfds, NULL, NULL, &tv);
462 if (FD_ISSET(s, &rfds) == 0) {
467 if (SSL_want_read(CC->ssl)) {
468 if ((SSL_write(CC->ssl, junk, 0)) < 1) {
469 CtdlLogPrintf(CTDL_DEBUG, "SSL_write in client_read: %s\n", ERR_reason_error_string(ERR_get_error()));
472 rlen = SSL_read(CC->ssl, &buf[len], bytes - len);
476 errval = SSL_get_error(CC->ssl, rlen);
477 if (errval == SSL_ERROR_WANT_READ ||
478 errval == SSL_ERROR_WANT_WRITE) {
482 CtdlLogPrintf(CTDL_DEBUG, "SSL_read got error %ld\n", errval);
484 return (client_read_to
485 (&buf[len], bytes - len, timeout));
494 * CtdlStartTLS() starts SSL/TLS encryption for the current session. It
495 * must be supplied with pre-generated strings for responses of "ok," "no
496 * support for TLS," and "error" so that we can use this in any protocol.
498 void CtdlStartTLS(char *ok_response, char *nosup_response,
499 char *error_response) {
501 int retval, bits, alg_bits;
504 CtdlLogPrintf(CTDL_CRIT, "SSL failed: no ssl_ctx exists?\n");
505 if (nosup_response != NULL) cprintf("%s", nosup_response);
508 if (!(CC->ssl = SSL_new(ssl_ctx))) {
509 CtdlLogPrintf(CTDL_CRIT, "SSL_new failed: %s\n",
510 ERR_reason_error_string(ERR_get_error()));
511 if (error_response != NULL) cprintf("%s", error_response);
514 if (!(SSL_set_fd(CC->ssl, CC->client_socket))) {
515 CtdlLogPrintf(CTDL_CRIT, "SSL_set_fd failed: %s\n",
516 ERR_reason_error_string(ERR_get_error()));
519 if (error_response != NULL) cprintf("%s", error_response);
522 if (ok_response != NULL) cprintf("%s", ok_response);
523 retval = SSL_accept(CC->ssl);
526 * Can't notify the client of an error here; they will
527 * discover the problem at the SSL layer and should
528 * revert to unencrypted communications.
531 char error_string[128];
533 errval = SSL_get_error(CC->ssl, retval);
534 CtdlLogPrintf(CTDL_CRIT, "SSL_accept failed: retval=%d, errval=%ld, err=%s\n",
537 ERR_error_string(errval, error_string)
543 BIO_set_close(CC->ssl->rbio, BIO_NOCLOSE);
544 bits = SSL_CIPHER_get_bits(SSL_get_current_cipher(CC->ssl), &alg_bits);
545 CtdlLogPrintf(CTDL_INFO, "SSL/TLS using %s on %s (%d of %d bits)\n",
546 SSL_CIPHER_get_name(SSL_get_current_cipher(CC->ssl)),
547 SSL_CIPHER_get_version(SSL_get_current_cipher(CC->ssl)),
549 CC->redirect_ssl = 1;
554 * cmd_stls() starts SSL/TLS encryption for the current session
556 void cmd_stls(char *params)
558 char ok_response[SIZ];
559 char nosup_response[SIZ];
560 char error_response[SIZ];
565 "%d Begin TLS negotiation now\n",
567 sprintf(nosup_response,
568 "%d TLS not supported here\n",
569 ERROR + CMD_NOT_SUPPORTED);
570 sprintf(error_response,
571 "%d TLS negotiation error\n",
572 ERROR + INTERNAL_ERROR);
574 CtdlStartTLS(ok_response, nosup_response, error_response);
579 * cmd_gtls() returns status info about the TLS connection
581 void cmd_gtls(char *params)
585 if (!CC->ssl || !CC->redirect_ssl) {
586 cprintf("%d Session is not encrypted.\n", ERROR);
590 SSL_CIPHER_get_bits(SSL_get_current_cipher(CC->ssl),
592 cprintf("%d %s|%s|%d|%d\n", CIT_OK,
593 SSL_CIPHER_get_version(SSL_get_current_cipher(CC->ssl)),
594 SSL_CIPHER_get_name(SSL_get_current_cipher(CC->ssl)),
600 * endtls() shuts down the TLS connection
602 * WARNING: This may make your session vulnerable to a known plaintext
603 * attack in the current implmentation.
608 CC->redirect_ssl = 0;
612 CtdlLogPrintf(CTDL_INFO, "Ending SSL/TLS\n");
613 SSL_shutdown(CC->ssl);
616 CC->redirect_ssl = 0;
621 * ssl_lock() callback for OpenSSL mutex locks
623 void ssl_lock(int mode, int n, const char *file, int line)
625 if (mode & CRYPTO_LOCK)
626 pthread_mutex_lock(SSLCritters[n]);
628 pthread_mutex_unlock(SSLCritters[n]);
630 #endif /* HAVE_OPENSSL */