4 * Copyright (c) 1996-2010 by the citadel.org team
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 3 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
25 #include "webserver.h"
27 /* where to find the keys */
28 #define CTDL_CRYPTO_DIR ctdl_key_dir
29 #define CTDL_KEY_PATH file_crpt_file_key
30 #define CTDL_CSR_PATH file_crpt_file_csr
31 #define CTDL_CER_PATH file_crpt_file_cer
32 #define SIGN_DAYS 3650 /* how long our certificate should live */
34 SSL_CTX *ssl_ctx; /* SSL context */
35 pthread_mutex_t **SSLCritters; /* Things needing locking */
36 char *ssl_cipher_list = DEFAULT_SSL_CIPHER_LIST;
38 pthread_key_t ThreadSSL; /* Per-thread SSL context */
40 static unsigned long id_callback(void)
42 return (unsigned long) pthread_self();
45 void shutdown_ssl(void)
49 /* Openssl requires these while shutdown.
50 * Didn't find a way to get out of this clean.
51 * int i, n = CRYPTO_num_locks();
52 * for (i = 0; i < n; i++)
53 * free(SSLCritters[i]);
59 * initialize ssl engine, load certs and initialize openssl internals
63 SSL_METHOD *ssl_method;
68 EVP_PKEY *req_pkey = NULL;
69 X509_NAME *name = NULL;
74 if (!access("/var/run/egd-pool", F_OK)) {
75 RAND_egd("/var/run/egd-pool");
79 lprintf(3, "PRNG not adequately seeded, won't do SSL/TLS\n");
82 SSLCritters = malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t *));
84 lprintf(1, "citserver: can't allocate memory!!\n");
85 /* Nothing's been initialized, just die */
91 for (a = 0; a < CRYPTO_num_locks(); a++) {
92 SSLCritters[a] = malloc(sizeof(pthread_mutex_t));
93 if (!SSLCritters[a]) {
95 "citserver: can't allocate memory!!\n");
96 /** Nothing's been initialized, just die */
100 pthread_mutex_init(SSLCritters[a], NULL);
105 * Initialize SSL transport layer
108 SSL_load_error_strings();
109 ssl_method = SSLv23_server_method();
110 if (!(ssl_ctx = SSL_CTX_new(ssl_method))) {
111 lprintf(3, "SSL_CTX_new failed: %s\n", ERR_reason_error_string(ERR_get_error()));
115 lprintf(9, "Requesting cipher list: %s\n", ssl_cipher_list);
116 if (!(SSL_CTX_set_cipher_list(ssl_ctx, ssl_cipher_list))) {
117 lprintf(3, "SSL_CTX_set_cipher_list failed: %s\n", ERR_reason_error_string(ERR_get_error()));
121 CRYPTO_set_locking_callback(ssl_lock);
122 CRYPTO_set_id_callback(id_callback);
125 * Get our certificates in order. (FIXME: dirify. this is a setup job.)
126 * First, create the key/cert directory if it's not there already...
128 mkdir(CTDL_CRYPTO_DIR, 0700);
131 * Before attempting to generate keys/certificates, first try
132 * link to them from the Citadel server if it's on the same host.
133 * We ignore any error return because it either meant that there
134 * was nothing in Citadel to link from (in which case we just
135 * generate new files) or the target files already exist (which
136 * is not fatal either).
138 if (!strcasecmp(ctdlhost, "uds")) {
139 sprintf(buf, "%s/keys/citadel.key", ctdlport);
140 rv = symlink(buf, CTDL_KEY_PATH);
141 if (!rv) lprintf(1, "%s\n", strerror(errno));
142 sprintf(buf, "%s/keys/citadel.csr", ctdlport);
143 rv = symlink(buf, CTDL_CSR_PATH);
144 if (!rv) lprintf(1, "%s\n", strerror(errno));
145 sprintf(buf, "%s/keys/citadel.cer", ctdlport);
146 rv = symlink(buf, CTDL_CER_PATH);
147 if (!rv) lprintf(1, "%s\n", strerror(errno));
151 * If we still don't have a private key, generate one.
153 if (access(CTDL_KEY_PATH, R_OK) != 0) {
154 lprintf(5, "Generating RSA key pair.\n");
155 rsa = RSA_generate_key(1024, /* modulus size */
156 65537, /* exponent */
157 NULL, /* no callback */
158 NULL /* no callback */
161 lprintf(3, "Key generation failed: %s\n", ERR_reason_error_string(ERR_get_error()));
164 fp = fopen(CTDL_KEY_PATH, "w");
166 chmod(CTDL_KEY_PATH, 0600);
167 if (PEM_write_RSAPrivateKey(fp, /* the file */
170 NULL, /* no passphr */
172 NULL, /* no callbk */
175 lprintf(3, "Cannot write key: %s\n",
176 ERR_reason_error_string(ERR_get_error()));
177 unlink(CTDL_KEY_PATH);
182 lprintf(3, "Cannot write key: %s\n", CTDL_KEY_PATH);
191 * If there is no certificate file on disk, we will be generating a self-signed certificate
192 * in the next step. Therefore, if we have neither a CSR nor a certificate, generate
193 * the CSR in this step so that the next step may commence.
195 if ( (access(CTDL_CER_PATH, R_OK) != 0) && (access(CTDL_CSR_PATH, R_OK) != 0) ) {
196 lprintf(5, "Generating a certificate signing request.\n");
199 * Read our key from the file. No, we don't just keep this
200 * in memory from the above key-generation function, because
201 * there is the possibility that the key was already on disk
202 * and we didn't just generate it now.
204 fp = fopen(CTDL_KEY_PATH, "r");
206 rsa = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
212 /** Create a public key from the private key */
213 if (pk=EVP_PKEY_new(), pk != NULL) {
214 EVP_PKEY_assign_RSA(pk, rsa);
215 if (req = X509_REQ_new(), req != NULL) {
217 /* Set the public key */
218 X509_REQ_set_pubkey(req, pk);
219 X509_REQ_set_version(req, 0L);
221 name = X509_REQ_get_subject_name(req);
223 /* Tell it who we are */
226 * We used to add these fields to the subject, but
227 * now we don't. Someone doing this for real isn't
228 * going to use the webcit-generated CSR anyway.
230 X509_NAME_add_entry_by_txt(name, "C",
231 MBSTRING_ASC, "US", -1, -1, 0);
233 X509_NAME_add_entry_by_txt(name, "ST",
234 MBSTRING_ASC, "New York", -1, -1, 0);
236 X509_NAME_add_entry_by_txt(name, "L",
237 MBSTRING_ASC, "Mount Kisco", -1, -1, 0);
242 env = "Organization name",
244 X509_NAME_add_entry_by_txt(
253 env = "Citadel server";
255 X509_NAME_add_entry_by_txt(
266 X509_NAME_add_entry_by_txt(
273 X509_REQ_set_subject_name(req, name);
276 if (!X509_REQ_sign(req, pk, EVP_md5())) {
277 lprintf(3, "X509_REQ_sign(): error\n");
280 /* Write it to disk. */
281 fp = fopen(CTDL_CSR_PATH, "w");
283 chmod(CTDL_CSR_PATH, 0600);
284 PEM_write_X509_REQ(fp, req);
288 lprintf(3, "Cannot write key: %s\n", CTDL_CSR_PATH);
302 lprintf(3, "Unable to read private key.\n");
309 * Generate a self-signed certificate if we don't have one.
311 if (access(CTDL_CER_PATH, R_OK) != 0) {
312 lprintf(5, "Generating a self-signed certificate.\n");
314 /* Same deal as before: always read the key from disk because
315 * it may or may not have just been generated.
317 fp = fopen(CTDL_KEY_PATH, "r");
319 rsa = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
323 /* This also holds true for the CSR. */
328 if (pk=EVP_PKEY_new(), pk != NULL) {
329 EVP_PKEY_assign_RSA(pk, rsa);
332 fp = fopen(CTDL_CSR_PATH, "r");
334 req = PEM_read_X509_REQ(fp, NULL, NULL, NULL);
339 if (cer = X509_new(), cer != NULL) {
341 ASN1_INTEGER_set(X509_get_serialNumber(cer), 0);
342 X509_set_issuer_name(cer, req->req_info->subject);
343 X509_set_subject_name(cer, req->req_info->subject);
344 X509_gmtime_adj(X509_get_notBefore(cer), 0);
345 X509_gmtime_adj(X509_get_notAfter(cer),(long)60*60*24*SIGN_DAYS);
347 req_pkey = X509_REQ_get_pubkey(req);
348 X509_set_pubkey(cer, req_pkey);
349 EVP_PKEY_free(req_pkey);
352 if (!X509_sign(cer, pk, EVP_md5())) {
353 lprintf(3, "X509_sign(): error\n");
356 /* Write it to disk. */
357 fp = fopen(CTDL_CER_PATH, "w");
359 chmod(CTDL_CER_PATH, 0600);
360 PEM_write_X509(fp, cer);
364 lprintf(3, "Cannot write key: %s\n", CTDL_CER_PATH);
378 * Now try to bind to the key and certificate.
379 * Note that we use SSL_CTX_use_certificate_chain_file() which allows
380 * the certificate file to contain intermediate certificates.
382 SSL_CTX_use_certificate_chain_file(ssl_ctx, CTDL_CER_PATH);
383 SSL_CTX_use_PrivateKey_file(ssl_ctx, CTDL_KEY_PATH, SSL_FILETYPE_PEM);
384 if ( !SSL_CTX_check_private_key(ssl_ctx) ) {
385 lprintf(3, "Cannot install certificate: %s\n",
386 ERR_reason_error_string(ERR_get_error()));
393 * starts SSL/TLS encryption for the current session.
395 int starttls(int sock) {
396 int retval, bits, alg_bits, r;
399 pthread_setspecific(ThreadSSL, NULL);
404 if (!(newssl = SSL_new(ssl_ctx))) {
405 lprintf(3, "SSL_new failed: %s\n", ERR_reason_error_string(ERR_get_error()));
408 if (!(SSL_set_fd(newssl, sock))) {
409 lprintf(3, "SSL_set_fd failed: %s\n", ERR_reason_error_string(ERR_get_error()));
413 retval = SSL_accept(newssl);
416 * Can't notify the client of an error here; they will
417 * discover the problem at the SSL layer and should
418 * revert to unencrypted communications.
421 const char *ssl_error_reason = NULL;
423 errval = SSL_get_error(newssl, retval);
424 ssl_error_reason = ERR_reason_error_string(ERR_get_error());
425 if (ssl_error_reason == NULL) {
426 lprintf(3, "SSL_accept failed: errval=%i, retval=%i %s\n", errval, retval, strerror(errval));
429 lprintf(3, "SSL_accept failed: %s\n", ssl_error_reason);
432 retval = SSL_accept(newssl);
436 const char *ssl_error_reason = NULL;
438 errval = SSL_get_error(newssl, retval);
439 ssl_error_reason = ERR_reason_error_string(ERR_get_error());
440 if (ssl_error_reason == NULL) {
441 lprintf(3, "SSL_accept failed: errval=%i, retval=%i (%s)\n", errval, retval, strerror(errval));
444 lprintf(3, "SSL_accept failed: %s\n", ssl_error_reason);
451 lprintf(15, "SSL_accept success\n");
453 r = BIO_set_close(newssl->rbio, BIO_NOCLOSE);
454 bits = SSL_CIPHER_get_bits(SSL_get_current_cipher(newssl), &alg_bits);
455 lprintf(15, "SSL/TLS using %s on %s (%d of %d bits)\n",
456 SSL_CIPHER_get_name(SSL_get_current_cipher(newssl)),
457 SSL_CIPHER_get_version(SSL_get_current_cipher(newssl)),
460 pthread_setspecific(ThreadSSL, newssl);
461 lprintf(15, "SSL started\n");
468 * shuts down the TLS connection
470 * WARNING: This may make your session vulnerable to a known plaintext
471 * attack in the current implmentation.
477 if (THREADSSL == NULL) return;
479 lprintf(15, "Ending SSL/TLS\n");
480 SSL_shutdown(THREADSSL);
481 ctx = SSL_get_SSL_CTX(THREADSSL);
483 /* I don't think this is needed, and it crashes the server anyway
486 * lprintf(9, "Freeing CTX at %x\n", (int)ctx );
492 pthread_setspecific(ThreadSSL, NULL);
497 * callback for OpenSSL mutex locks
499 void ssl_lock(int mode, int n, const char *file, int line)
501 if (mode & CRYPTO_LOCK) {
502 pthread_mutex_lock(SSLCritters[n]);
505 pthread_mutex_unlock(SSLCritters[n]);
510 * Send binary data to the client encrypted.
512 void client_write_ssl(const StrBuf *Buf)
520 if (THREADSSL == NULL) return;
522 nbytes = nremain = StrLength(Buf);
525 while (nremain > 0) {
526 if (SSL_want_write(THREADSSL)) {
527 if ((SSL_read(THREADSSL, junk, 0)) < 1) {
528 lprintf(9, "SSL_read in client_write: %s\n",
529 ERR_reason_error_string(ERR_get_error()));
532 retval = SSL_write(THREADSSL, &buf[nbytes - nremain], nremain);
536 errval = SSL_get_error(THREADSSL, retval);
537 if (errval == SSL_ERROR_WANT_READ || errval == SSL_ERROR_WANT_WRITE) {
541 lprintf(9, "SSL_write got error %ld, ret %d\n", errval, retval);
543 lprintf(9, "errno is %d\n", errno);
554 * read data from the encrypted layer.
556 int client_read_sslbuffer(StrBuf *buf, int timeout)
558 char sbuf[16384]; /* OpenSSL communicates in 16k blocks, so let's speak its native tongue. */
561 SSL *pssl = THREADSSL;
563 if (pssl == NULL) return(-1);
566 if (SSL_want_read(pssl)) {
567 if ((SSL_write(pssl, junk, 0)) < 1) {
568 lprintf(9, "SSL_write in client_read\n");
571 rlen = SSL_read(pssl, sbuf, sizeof(sbuf));
575 errval = SSL_get_error(pssl, rlen);
576 if (errval == SSL_ERROR_WANT_READ || errval == SSL_ERROR_WANT_WRITE) {
580 lprintf(9, "SSL_read got error %ld\n", errval);
584 StrBufAppendBufPlain(buf, sbuf, rlen, 0);
590 #endif /* HAVE_OPENSSL */