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.
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.
23 #include "webserver.h"
25 /* where to find the keys */
26 #define CTDL_CRYPTO_DIR ctdl_key_dir
27 #define CTDL_KEY_PATH file_crpt_file_key
28 #define CTDL_CSR_PATH file_crpt_file_csr
29 #define CTDL_CER_PATH file_crpt_file_cer
30 #define SIGN_DAYS 3650 /* how long our certificate should live */
32 SSL_CTX *ssl_ctx; /* SSL context */
33 pthread_mutex_t **SSLCritters; /* Things needing locking */
34 char *ssl_cipher_list = DEFAULT_SSL_CIPHER_LIST;
36 pthread_key_t ThreadSSL; /* Per-thread SSL context */
38 static unsigned long id_callback(void)
40 return (unsigned long) pthread_self();
43 void shutdown_ssl(void)
47 /* Openssl requires these while shutdown.
48 * Didn't find a way to get out of this clean.
49 * int i, n = CRYPTO_num_locks();
50 * for (i = 0; i < n; i++)
51 * free(SSLCritters[i]);
57 * initialize ssl engine, load certs and initialize openssl internals
61 const SSL_METHOD *ssl_method;
66 EVP_PKEY *req_pkey = NULL;
67 X509_NAME *name = NULL;
72 if (!access("/var/run/egd-pool", F_OK)) {
73 RAND_egd("/var/run/egd-pool");
77 syslog(3, "PRNG not adequately seeded, won't do SSL/TLS\n");
80 SSLCritters = malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t *));
82 syslog(1, "citserver: can't allocate memory!!\n");
83 /* Nothing's been initialized, just die */
89 for (a = 0; a < CRYPTO_num_locks(); a++) {
90 SSLCritters[a] = malloc(sizeof(pthread_mutex_t));
91 if (!SSLCritters[a]) {
93 "citserver: can't allocate memory!!\n");
94 /** Nothing's been initialized, just die */
98 pthread_mutex_init(SSLCritters[a], NULL);
103 * Initialize SSL transport layer
106 SSL_load_error_strings();
107 ssl_method = SSLv23_server_method();
108 if (!(ssl_ctx = SSL_CTX_new(ssl_method))) {
109 syslog(3, "SSL_CTX_new failed: %s\n", ERR_reason_error_string(ERR_get_error()));
113 syslog(9, "Requesting cipher list: %s\n", ssl_cipher_list);
114 if (!(SSL_CTX_set_cipher_list(ssl_ctx, ssl_cipher_list))) {
115 syslog(3, "SSL_CTX_set_cipher_list failed: %s\n", ERR_reason_error_string(ERR_get_error()));
119 CRYPTO_set_locking_callback(ssl_lock);
120 CRYPTO_set_id_callback(id_callback);
123 * Get our certificates in order. (FIXME: dirify. this is a setup job.)
124 * First, create the key/cert directory if it's not there already...
126 mkdir(CTDL_CRYPTO_DIR, 0700);
129 * Before attempting to generate keys/certificates, first try
130 * link to them from the Citadel server if it's on the same host.
131 * We ignore any error return because it either meant that there
132 * was nothing in Citadel to link from (in which case we just
133 * generate new files) or the target files already exist (which
134 * is not fatal either).
136 if (!strcasecmp(ctdlhost, "uds")) {
137 sprintf(buf, "%s/keys/citadel.key", ctdlport);
138 rv = symlink(buf, CTDL_KEY_PATH);
139 if (!rv) syslog(1, "%s\n", strerror(errno));
140 sprintf(buf, "%s/keys/citadel.csr", ctdlport);
141 rv = symlink(buf, CTDL_CSR_PATH);
142 if (!rv) syslog(1, "%s\n", strerror(errno));
143 sprintf(buf, "%s/keys/citadel.cer", ctdlport);
144 rv = symlink(buf, CTDL_CER_PATH);
145 if (!rv) syslog(1, "%s\n", strerror(errno));
149 * If we still don't have a private key, generate one.
151 if (access(CTDL_KEY_PATH, R_OK) != 0) {
152 syslog(5, "Generating RSA key pair.\n");
153 rsa = RSA_generate_key(1024, /* modulus size */
154 65537, /* exponent */
155 NULL, /* no callback */
156 NULL /* no callback */
159 syslog(3, "Key generation failed: %s\n", ERR_reason_error_string(ERR_get_error()));
162 fp = fopen(CTDL_KEY_PATH, "w");
164 chmod(CTDL_KEY_PATH, 0600);
165 if (PEM_write_RSAPrivateKey(fp, /* the file */
168 NULL, /* no passphr */
170 NULL, /* no callbk */
173 syslog(3, "Cannot write key: %s\n",
174 ERR_reason_error_string(ERR_get_error()));
175 unlink(CTDL_KEY_PATH);
180 syslog(3, "Cannot write key: %s\n", CTDL_KEY_PATH);
189 * If there is no certificate file on disk, we will be generating a self-signed certificate
190 * in the next step. Therefore, if we have neither a CSR nor a certificate, generate
191 * the CSR in this step so that the next step may commence.
193 if ( (access(CTDL_CER_PATH, R_OK) != 0) && (access(CTDL_CSR_PATH, R_OK) != 0) ) {
194 syslog(5, "Generating a certificate signing request.\n");
197 * Read our key from the file. No, we don't just keep this
198 * in memory from the above key-generation function, because
199 * there is the possibility that the key was already on disk
200 * and we didn't just generate it now.
202 fp = fopen(CTDL_KEY_PATH, "r");
204 rsa = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
210 /** Create a public key from the private key */
211 if (pk=EVP_PKEY_new(), pk != NULL) {
212 EVP_PKEY_assign_RSA(pk, rsa);
213 if (req = X509_REQ_new(), req != NULL) {
215 /* Set the public key */
216 X509_REQ_set_pubkey(req, pk);
217 X509_REQ_set_version(req, 0L);
219 name = X509_REQ_get_subject_name(req);
221 /* Tell it who we are */
224 * We used to add these fields to the subject, but
225 * now we don't. Someone doing this for real isn't
226 * going to use the webcit-generated CSR anyway.
228 X509_NAME_add_entry_by_txt(name, "C",
229 MBSTRING_ASC, "US", -1, -1, 0);
231 X509_NAME_add_entry_by_txt(name, "ST",
232 MBSTRING_ASC, "New York", -1, -1, 0);
234 X509_NAME_add_entry_by_txt(name, "L",
235 MBSTRING_ASC, "Mount Kisco", -1, -1, 0);
240 env = "Organization name",
242 X509_NAME_add_entry_by_txt(
251 env = "Citadel server";
253 X509_NAME_add_entry_by_txt(
264 X509_NAME_add_entry_by_txt(
271 X509_REQ_set_subject_name(req, name);
274 if (!X509_REQ_sign(req, pk, EVP_md5())) {
275 syslog(3, "X509_REQ_sign(): error\n");
278 /* Write it to disk. */
279 fp = fopen(CTDL_CSR_PATH, "w");
281 chmod(CTDL_CSR_PATH, 0600);
282 PEM_write_X509_REQ(fp, req);
286 syslog(3, "Cannot write key: %s\n", CTDL_CSR_PATH);
300 syslog(3, "Unable to read private key.\n");
307 * Generate a self-signed certificate if we don't have one.
309 if (access(CTDL_CER_PATH, R_OK) != 0) {
310 syslog(5, "Generating a self-signed certificate.\n");
312 /* Same deal as before: always read the key from disk because
313 * it may or may not have just been generated.
315 fp = fopen(CTDL_KEY_PATH, "r");
317 rsa = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
321 /* This also holds true for the CSR. */
326 if (pk=EVP_PKEY_new(), pk != NULL) {
327 EVP_PKEY_assign_RSA(pk, rsa);
330 fp = fopen(CTDL_CSR_PATH, "r");
332 req = PEM_read_X509_REQ(fp, NULL, NULL, NULL);
337 if (cer = X509_new(), cer != NULL) {
339 ASN1_INTEGER_set(X509_get_serialNumber(cer), 0);
340 X509_set_issuer_name(cer, req->req_info->subject);
341 X509_set_subject_name(cer, req->req_info->subject);
342 X509_gmtime_adj(X509_get_notBefore(cer), 0);
343 X509_gmtime_adj(X509_get_notAfter(cer),(long)60*60*24*SIGN_DAYS);
345 req_pkey = X509_REQ_get_pubkey(req);
346 X509_set_pubkey(cer, req_pkey);
347 EVP_PKEY_free(req_pkey);
350 if (!X509_sign(cer, pk, EVP_md5())) {
351 syslog(3, "X509_sign(): error\n");
354 /* Write it to disk. */
355 fp = fopen(CTDL_CER_PATH, "w");
357 chmod(CTDL_CER_PATH, 0600);
358 PEM_write_X509(fp, cer);
362 syslog(3, "Cannot write key: %s\n", CTDL_CER_PATH);
376 * Now try to bind to the key and certificate.
377 * Note that we use SSL_CTX_use_certificate_chain_file() which allows
378 * the certificate file to contain intermediate certificates.
380 SSL_CTX_use_certificate_chain_file(ssl_ctx, CTDL_CER_PATH);
381 SSL_CTX_use_PrivateKey_file(ssl_ctx, CTDL_KEY_PATH, SSL_FILETYPE_PEM);
382 if ( !SSL_CTX_check_private_key(ssl_ctx) ) {
383 syslog(3, "Cannot install certificate: %s\n",
384 ERR_reason_error_string(ERR_get_error()));
391 * starts SSL/TLS encryption for the current session.
393 int starttls(int sock) {
394 int retval, bits, alg_bits;/*r; */
397 pthread_setspecific(ThreadSSL, NULL);
402 if (!(newssl = SSL_new(ssl_ctx))) {
403 syslog(3, "SSL_new failed: %s\n", ERR_reason_error_string(ERR_get_error()));
406 if (!(SSL_set_fd(newssl, sock))) {
407 syslog(3, "SSL_set_fd failed: %s\n", ERR_reason_error_string(ERR_get_error()));
411 retval = SSL_accept(newssl);
414 * Can't notify the client of an error here; they will
415 * discover the problem at the SSL layer and should
416 * revert to unencrypted communications.
419 const char *ssl_error_reason = NULL;
421 errval = SSL_get_error(newssl, retval);
422 ssl_error_reason = ERR_reason_error_string(ERR_get_error());
423 if (ssl_error_reason == NULL) {
424 syslog(3, "SSL_accept failed: errval=%ld, retval=%d %s\n", errval, retval, strerror(errval));
427 syslog(3, "SSL_accept failed: %s\n", ssl_error_reason);
430 retval = SSL_accept(newssl);
434 const char *ssl_error_reason = NULL;
436 errval = SSL_get_error(newssl, retval);
437 ssl_error_reason = ERR_reason_error_string(ERR_get_error());
438 if (ssl_error_reason == NULL) {
439 syslog(3, "SSL_accept failed: errval=%ld, retval=%d (%s)\n", errval, retval, strerror(errval));
442 syslog(3, "SSL_accept failed: %s\n", ssl_error_reason);
449 syslog(15, "SSL_accept success\n");
451 /*r = */BIO_set_close(newssl->rbio, BIO_NOCLOSE);
452 bits = SSL_CIPHER_get_bits(SSL_get_current_cipher(newssl), &alg_bits);
453 syslog(15, "SSL/TLS using %s on %s (%d of %d bits)\n",
454 SSL_CIPHER_get_name(SSL_get_current_cipher(newssl)),
455 SSL_CIPHER_get_version(SSL_get_current_cipher(newssl)),
458 pthread_setspecific(ThreadSSL, newssl);
459 syslog(15, "SSL started\n");
466 * shuts down the TLS connection
468 * WARNING: This may make your session vulnerable to a known plaintext
469 * attack in the current implmentation.
475 if (THREADSSL == NULL) return;
477 syslog(15, "Ending SSL/TLS\n");
478 SSL_shutdown(THREADSSL);
479 /*ctx = */SSL_get_SSL_CTX(THREADSSL);
481 /* I don't think this is needed, and it crashes the server anyway
484 * syslog(9, "Freeing CTX at %x\n", (int)ctx );
490 pthread_setspecific(ThreadSSL, NULL);
495 * callback for OpenSSL mutex locks
497 void ssl_lock(int mode, int n, const char *file, int line)
499 if (mode & CRYPTO_LOCK) {
500 pthread_mutex_lock(SSLCritters[n]);
503 pthread_mutex_unlock(SSLCritters[n]);
508 * Send binary data to the client encrypted.
510 void client_write_ssl(const StrBuf *Buf)
518 if (THREADSSL == NULL) return;
520 nbytes = nremain = StrLength(Buf);
523 while (nremain > 0) {
524 if (SSL_want_write(THREADSSL)) {
525 if ((SSL_read(THREADSSL, junk, 0)) < 1) {
526 syslog(9, "SSL_read in client_write: %s\n",
527 ERR_reason_error_string(ERR_get_error()));
530 retval = SSL_write(THREADSSL, &buf[nbytes - nremain], nremain);
534 errval = SSL_get_error(THREADSSL, retval);
535 if (errval == SSL_ERROR_WANT_READ || errval == SSL_ERROR_WANT_WRITE) {
539 syslog(9, "SSL_write got error %ld, ret %d\n", errval, retval);
541 syslog(9, "errno is %d\n", errno);
552 * read data from the encrypted layer.
554 int client_read_sslbuffer(StrBuf *buf, int timeout)
556 char sbuf[16384]; /* OpenSSL communicates in 16k blocks, so let's speak its native tongue. */
559 SSL *pssl = THREADSSL;
561 if (pssl == NULL) return(-1);
564 if (SSL_want_read(pssl)) {
565 if ((SSL_write(pssl, junk, 0)) < 1) {
566 syslog(9, "SSL_write in client_read\n");
569 rlen = SSL_read(pssl, sbuf, sizeof(sbuf));
573 errval = SSL_get_error(pssl, rlen);
574 if (errval == SSL_ERROR_WANT_READ || errval == SSL_ERROR_WANT_WRITE) {
578 syslog(9, "SSL_read got error %ld\n", errval);
582 StrBufAppendBufPlain(buf, sbuf, rlen, 0);
588 #endif /* HAVE_OPENSSL */