2 * Copyright (c) 1996-2012 by the citadel.org team
4 * This program is open source software. You can redistribute it and/or
5 * modify 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.
17 #include "webserver.h"
19 /* where to find the keys */
20 #define CTDL_CRYPTO_DIR ctdl_key_dir
21 #define CTDL_KEY_PATH file_crpt_file_key
22 #define CTDL_CSR_PATH file_crpt_file_csr
23 #define CTDL_CER_PATH file_crpt_file_cer
24 #define SIGN_DAYS 3650 /* how long our certificate should live */
26 SSL_CTX *ssl_ctx; /* SSL context */
27 pthread_mutex_t **SSLCritters; /* Things needing locking */
28 char *ssl_cipher_list = DEFAULT_SSL_CIPHER_LIST;
30 pthread_key_t ThreadSSL; /* Per-thread SSL context */
32 void ssl_lock(int mode, int n, const char *file, int line);
34 static unsigned long id_callback(void)
36 return (unsigned long) pthread_self();
39 void shutdown_ssl(void)
43 /* Openssl requires these while shutdown.
44 * Didn't find a way to get out of this clean.
45 * int i, n = CRYPTO_num_locks();
46 * for (i = 0; i < n; i++)
47 * free(SSLCritters[i]);
53 * initialize ssl engine, load certs and initialize openssl internals
57 const SSL_METHOD *ssl_method;
62 EVP_PKEY *req_pkey = NULL;
63 X509_NAME *name = NULL;
68 if (!access("/var/run/egd-pool", F_OK)) {
69 RAND_egd("/var/run/egd-pool");
73 syslog(LOG_WARNING, "PRNG not adequately seeded, won't do SSL/TLS\n");
76 SSLCritters = malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t *));
78 syslog(LOG_ERR, "citserver: can't allocate memory!!\n");
79 /* Nothing's been initialized, just die */
85 for (a = 0; a < CRYPTO_num_locks(); a++) {
86 SSLCritters[a] = malloc(sizeof(pthread_mutex_t));
87 if (!SSLCritters[a]) {
89 "citserver: can't allocate memory!!\n");
90 /** Nothing's been initialized, just die */
94 pthread_mutex_init(SSLCritters[a], NULL);
99 * Initialize SSL transport layer
102 SSL_load_error_strings();
103 ssl_method = SSLv23_server_method();
104 if (!(ssl_ctx = SSL_CTX_new(ssl_method))) {
105 syslog(LOG_WARNING, "SSL_CTX_new failed: %s\n", ERR_reason_error_string(ERR_get_error()));
109 syslog(LOG_INFO, "Requesting cipher list: %s\n", ssl_cipher_list);
110 if (!(SSL_CTX_set_cipher_list(ssl_ctx, ssl_cipher_list))) {
111 syslog(LOG_WARNING, "SSL_CTX_set_cipher_list failed: %s\n", ERR_reason_error_string(ERR_get_error()));
115 CRYPTO_set_locking_callback(ssl_lock);
116 CRYPTO_set_id_callback(id_callback);
119 * Get our certificates in order. (FIXME: dirify. this is a setup job.)
120 * First, create the key/cert directory if it's not there already...
122 mkdir(CTDL_CRYPTO_DIR, 0700);
125 * Before attempting to generate keys/certificates, first try
126 * link to them from the Citadel server if it's on the same host.
127 * We ignore any error return because it either meant that there
128 * was nothing in Citadel to link from (in which case we just
129 * generate new files) or the target files already exist (which
130 * is not fatal either).
132 if (!strcasecmp(ctdlhost, "uds")) {
133 sprintf(buf, "%s/keys/citadel.key", ctdlport);
134 rv = symlink(buf, CTDL_KEY_PATH);
135 if (!rv) syslog(LOG_DEBUG, "%s\n", strerror(errno));
136 sprintf(buf, "%s/keys/citadel.csr", ctdlport);
137 rv = symlink(buf, CTDL_CSR_PATH);
138 if (!rv) syslog(LOG_DEBUG, "%s\n", strerror(errno));
139 sprintf(buf, "%s/keys/citadel.cer", ctdlport);
140 rv = symlink(buf, CTDL_CER_PATH);
141 if (!rv) syslog(LOG_DEBUG, "%s\n", strerror(errno));
145 * If we still don't have a private key, generate one.
147 if (access(CTDL_KEY_PATH, R_OK) != 0) {
148 syslog(LOG_INFO, "Generating RSA key pair.\n");
149 rsa = RSA_generate_key(1024, /* modulus size */
150 65537, /* exponent */
151 NULL, /* no callback */
152 NULL /* no callback */
155 syslog(LOG_WARNING, "Key generation failed: %s\n", ERR_reason_error_string(ERR_get_error()));
158 fp = fopen(CTDL_KEY_PATH, "w");
160 chmod(CTDL_KEY_PATH, 0600);
161 if (PEM_write_RSAPrivateKey(fp, /* the file */
164 NULL, /* no passphr */
166 NULL, /* no callbk */
169 syslog(LOG_WARNING, "Cannot write key: %s\n",
170 ERR_reason_error_string(ERR_get_error()));
171 unlink(CTDL_KEY_PATH);
176 syslog(LOG_WARNING, "Cannot write key: %s\n", CTDL_KEY_PATH);
185 * If there is no certificate file on disk, we will be generating a self-signed certificate
186 * in the next step. Therefore, if we have neither a CSR nor a certificate, generate
187 * the CSR in this step so that the next step may commence.
189 if ( (access(CTDL_CER_PATH, R_OK) != 0) && (access(CTDL_CSR_PATH, R_OK) != 0) ) {
190 syslog(LOG_INFO, "Generating a certificate signing request.\n");
193 * Read our key from the file. No, we don't just keep this
194 * in memory from the above key-generation function, because
195 * there is the possibility that the key was already on disk
196 * and we didn't just generate it now.
198 fp = fopen(CTDL_KEY_PATH, "r");
200 rsa = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
206 /** Create a public key from the private key */
207 if (pk=EVP_PKEY_new(), pk != NULL) {
208 EVP_PKEY_assign_RSA(pk, rsa);
209 if (req = X509_REQ_new(), req != NULL) {
211 /* Set the public key */
212 X509_REQ_set_pubkey(req, pk);
213 X509_REQ_set_version(req, 0L);
215 name = X509_REQ_get_subject_name(req);
217 /* Tell it who we are */
220 * We used to add these fields to the subject, but
221 * now we don't. Someone doing this for real isn't
222 * going to use the webcit-generated CSR anyway.
224 X509_NAME_add_entry_by_txt(name, "C",
225 MBSTRING_ASC, "US", -1, -1, 0);
227 X509_NAME_add_entry_by_txt(name, "ST",
228 MBSTRING_ASC, "New York", -1, -1, 0);
230 X509_NAME_add_entry_by_txt(name, "L",
231 MBSTRING_ASC, "Mount Kisco", -1, -1, 0);
236 env = "Organization name",
238 X509_NAME_add_entry_by_txt(
247 env = "Citadel server";
249 X509_NAME_add_entry_by_txt(
260 X509_NAME_add_entry_by_txt(
267 X509_REQ_set_subject_name(req, name);
270 if (!X509_REQ_sign(req, pk, EVP_md5())) {
271 syslog(LOG_WARNING, "X509_REQ_sign(): error\n");
274 /* Write it to disk. */
275 fp = fopen(CTDL_CSR_PATH, "w");
277 chmod(CTDL_CSR_PATH, 0600);
278 PEM_write_X509_REQ(fp, req);
282 syslog(LOG_WARNING, "Cannot write key: %s\n", CTDL_CSR_PATH);
296 syslog(LOG_WARNING, "Unable to read private key.\n");
303 * Generate a self-signed certificate if we don't have one.
305 if (access(CTDL_CER_PATH, R_OK) != 0) {
306 syslog(LOG_INFO, "Generating a self-signed certificate.\n");
308 /* Same deal as before: always read the key from disk because
309 * it may or may not have just been generated.
311 fp = fopen(CTDL_KEY_PATH, "r");
313 rsa = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
317 /* This also holds true for the CSR. */
322 if (pk=EVP_PKEY_new(), pk != NULL) {
323 EVP_PKEY_assign_RSA(pk, rsa);
326 fp = fopen(CTDL_CSR_PATH, "r");
328 req = PEM_read_X509_REQ(fp, NULL, NULL, NULL);
333 if (cer = X509_new(), cer != NULL) {
335 ASN1_INTEGER_set(X509_get_serialNumber(cer), 0);
336 X509_set_issuer_name(cer, req->req_info->subject);
337 X509_set_subject_name(cer, req->req_info->subject);
338 X509_gmtime_adj(X509_get_notBefore(cer), 0);
339 X509_gmtime_adj(X509_get_notAfter(cer),(long)60*60*24*SIGN_DAYS);
341 req_pkey = X509_REQ_get_pubkey(req);
342 X509_set_pubkey(cer, req_pkey);
343 EVP_PKEY_free(req_pkey);
346 if (!X509_sign(cer, pk, EVP_md5())) {
347 syslog(LOG_WARNING, "X509_sign(): error\n");
350 /* Write it to disk. */
351 fp = fopen(CTDL_CER_PATH, "w");
353 chmod(CTDL_CER_PATH, 0600);
354 PEM_write_X509(fp, cer);
358 syslog(LOG_WARNING, "Cannot write key: %s\n", CTDL_CER_PATH);
372 * Now try to bind to the key and certificate.
373 * Note that we use SSL_CTX_use_certificate_chain_file() which allows
374 * the certificate file to contain intermediate certificates.
376 SSL_CTX_use_certificate_chain_file(ssl_ctx, CTDL_CER_PATH);
377 SSL_CTX_use_PrivateKey_file(ssl_ctx, CTDL_KEY_PATH, SSL_FILETYPE_PEM);
378 if ( !SSL_CTX_check_private_key(ssl_ctx) ) {
379 syslog(LOG_WARNING, "Cannot install certificate: %s\n",
380 ERR_reason_error_string(ERR_get_error()));
387 * starts SSL/TLS encryption for the current session.
389 int starttls(int sock) {
390 int retval, bits, alg_bits;/*r; */
393 pthread_setspecific(ThreadSSL, NULL);
398 if (!(newssl = SSL_new(ssl_ctx))) {
399 syslog(LOG_WARNING, "SSL_new failed: %s\n", ERR_reason_error_string(ERR_get_error()));
402 if (!(SSL_set_fd(newssl, sock))) {
403 syslog(LOG_WARNING, "SSL_set_fd failed: %s\n", ERR_reason_error_string(ERR_get_error()));
407 retval = SSL_accept(newssl);
410 * Can't notify the client of an error here; they will
411 * discover the problem at the SSL layer and should
412 * revert to unencrypted communications.
415 const char *ssl_error_reason = NULL;
417 errval = SSL_get_error(newssl, retval);
418 ssl_error_reason = ERR_reason_error_string(ERR_get_error());
419 if (ssl_error_reason == NULL) {
420 syslog(LOG_WARNING, "SSL_accept failed: errval=%ld, retval=%d %s\n", errval, retval, strerror(errval));
423 syslog(LOG_WARNING, "SSL_accept failed: %s\n", ssl_error_reason);
426 retval = SSL_accept(newssl);
430 const char *ssl_error_reason = NULL;
432 errval = SSL_get_error(newssl, retval);
433 ssl_error_reason = ERR_reason_error_string(ERR_get_error());
434 if (ssl_error_reason == NULL) {
435 syslog(LOG_WARNING, "SSL_accept failed: errval=%ld, retval=%d (%s)\n", errval, retval, strerror(errval));
438 syslog(LOG_WARNING, "SSL_accept failed: %s\n", ssl_error_reason);
445 syslog(LOG_INFO, "SSL_accept success\n");
447 /*r = */BIO_set_close(newssl->rbio, BIO_NOCLOSE);
448 bits = SSL_CIPHER_get_bits(SSL_get_current_cipher(newssl), &alg_bits);
449 syslog(LOG_INFO, "SSL/TLS using %s on %s (%d of %d bits)\n",
450 SSL_CIPHER_get_name(SSL_get_current_cipher(newssl)),
451 SSL_CIPHER_get_version(SSL_get_current_cipher(newssl)),
454 pthread_setspecific(ThreadSSL, newssl);
455 syslog(LOG_INFO, "SSL started\n");
462 * shuts down the TLS connection
464 * WARNING: This may make your session vulnerable to a known plaintext
465 * attack in the current implmentation.
471 if (THREADSSL == NULL) return;
473 syslog(LOG_INFO, "Ending SSL/TLS\n");
474 SSL_shutdown(THREADSSL);
475 /*ctx = */SSL_get_SSL_CTX(THREADSSL);
477 /* I don't think this is needed, and it crashes the server anyway
480 * syslog(LOG_DEBUG, "Freeing CTX at %x\n", (int)ctx );
486 pthread_setspecific(ThreadSSL, NULL);
491 * callback for OpenSSL mutex locks
493 void ssl_lock(int mode, int n, const char *file, int line)
495 if (mode & CRYPTO_LOCK) {
496 pthread_mutex_lock(SSLCritters[n]);
499 pthread_mutex_unlock(SSLCritters[n]);
504 * Send binary data to the client encrypted.
506 int client_write_ssl(const StrBuf *Buf)
514 if (THREADSSL == NULL) return -1;
516 nbytes = nremain = StrLength(Buf);
519 while (nremain > 0) {
520 if (SSL_want_write(THREADSSL)) {
521 if ((SSL_read(THREADSSL, junk, 0)) < 1) {
522 syslog(LOG_WARNING, "SSL_read in client_write: %s\n",
523 ERR_reason_error_string(ERR_get_error()));
526 retval = SSL_write(THREADSSL, &buf[nbytes - nremain], nremain);
530 errval = SSL_get_error(THREADSSL, retval);
531 if (errval == SSL_ERROR_WANT_READ || errval == SSL_ERROR_WANT_WRITE) {
535 syslog(LOG_WARNING, "SSL_write got error %ld, ret %d\n", errval, retval);
537 syslog(LOG_WARNING, "errno is %d\n", errno);
549 * read data from the encrypted layer.
551 int client_read_sslbuffer(StrBuf *buf, int timeout)
553 char sbuf[16384]; /* OpenSSL communicates in 16k blocks, so let's speak its native tongue. */
556 SSL *pssl = THREADSSL;
558 if (pssl == NULL) return(-1);
561 if (SSL_want_read(pssl)) {
562 if ((SSL_write(pssl, junk, 0)) < 1) {
563 syslog(LOG_WARNING, "SSL_write in client_read\n");
566 rlen = SSL_read(pssl, sbuf, sizeof(sbuf));
570 errval = SSL_get_error(pssl, rlen);
571 if (errval == SSL_ERROR_WANT_READ || errval == SSL_ERROR_WANT_WRITE) {
575 syslog(LOG_WARNING, "SSL_read got error %ld\n", errval);
579 StrBufAppendBufPlain(buf, sbuf, rlen, 0);
585 #endif /* HAVE_OPENSSL */