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 static unsigned long id_callback(void)
34 return (unsigned long) pthread_self();
37 void shutdown_ssl(void)
41 /* Openssl requires these while shutdown.
42 * Didn't find a way to get out of this clean.
43 * int i, n = CRYPTO_num_locks();
44 * for (i = 0; i < n; i++)
45 * free(SSLCritters[i]);
51 * initialize ssl engine, load certs and initialize openssl internals
55 const SSL_METHOD *ssl_method;
60 EVP_PKEY *req_pkey = NULL;
61 X509_NAME *name = NULL;
66 if (!access("/var/run/egd-pool", F_OK)) {
67 RAND_egd("/var/run/egd-pool");
71 syslog(3, "PRNG not adequately seeded, won't do SSL/TLS\n");
74 SSLCritters = malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t *));
76 syslog(1, "citserver: can't allocate memory!!\n");
77 /* Nothing's been initialized, just die */
83 for (a = 0; a < CRYPTO_num_locks(); a++) {
84 SSLCritters[a] = malloc(sizeof(pthread_mutex_t));
85 if (!SSLCritters[a]) {
87 "citserver: can't allocate memory!!\n");
88 /** Nothing's been initialized, just die */
92 pthread_mutex_init(SSLCritters[a], NULL);
97 * Initialize SSL transport layer
100 SSL_load_error_strings();
101 ssl_method = SSLv23_server_method();
102 if (!(ssl_ctx = SSL_CTX_new(ssl_method))) {
103 syslog(3, "SSL_CTX_new failed: %s\n", ERR_reason_error_string(ERR_get_error()));
107 syslog(9, "Requesting cipher list: %s\n", ssl_cipher_list);
108 if (!(SSL_CTX_set_cipher_list(ssl_ctx, ssl_cipher_list))) {
109 syslog(3, "SSL_CTX_set_cipher_list failed: %s\n", ERR_reason_error_string(ERR_get_error()));
113 CRYPTO_set_locking_callback(ssl_lock);
114 CRYPTO_set_id_callback(id_callback);
117 * Get our certificates in order. (FIXME: dirify. this is a setup job.)
118 * First, create the key/cert directory if it's not there already...
120 mkdir(CTDL_CRYPTO_DIR, 0700);
123 * Before attempting to generate keys/certificates, first try
124 * link to them from the Citadel server if it's on the same host.
125 * We ignore any error return because it either meant that there
126 * was nothing in Citadel to link from (in which case we just
127 * generate new files) or the target files already exist (which
128 * is not fatal either).
130 if (!strcasecmp(ctdlhost, "uds")) {
131 sprintf(buf, "%s/keys/citadel.key", ctdlport);
132 rv = symlink(buf, CTDL_KEY_PATH);
133 if (!rv) syslog(1, "%s\n", strerror(errno));
134 sprintf(buf, "%s/keys/citadel.csr", ctdlport);
135 rv = symlink(buf, CTDL_CSR_PATH);
136 if (!rv) syslog(1, "%s\n", strerror(errno));
137 sprintf(buf, "%s/keys/citadel.cer", ctdlport);
138 rv = symlink(buf, CTDL_CER_PATH);
139 if (!rv) syslog(1, "%s\n", strerror(errno));
143 * If we still don't have a private key, generate one.
145 if (access(CTDL_KEY_PATH, R_OK) != 0) {
146 syslog(5, "Generating RSA key pair.\n");
147 rsa = RSA_generate_key(1024, /* modulus size */
148 65537, /* exponent */
149 NULL, /* no callback */
150 NULL /* no callback */
153 syslog(3, "Key generation failed: %s\n", ERR_reason_error_string(ERR_get_error()));
156 fp = fopen(CTDL_KEY_PATH, "w");
158 chmod(CTDL_KEY_PATH, 0600);
159 if (PEM_write_RSAPrivateKey(fp, /* the file */
162 NULL, /* no passphr */
164 NULL, /* no callbk */
167 syslog(3, "Cannot write key: %s\n",
168 ERR_reason_error_string(ERR_get_error()));
169 unlink(CTDL_KEY_PATH);
174 syslog(3, "Cannot write key: %s\n", CTDL_KEY_PATH);
183 * If there is no certificate file on disk, we will be generating a self-signed certificate
184 * in the next step. Therefore, if we have neither a CSR nor a certificate, generate
185 * the CSR in this step so that the next step may commence.
187 if ( (access(CTDL_CER_PATH, R_OK) != 0) && (access(CTDL_CSR_PATH, R_OK) != 0) ) {
188 syslog(5, "Generating a certificate signing request.\n");
191 * Read our key from the file. No, we don't just keep this
192 * in memory from the above key-generation function, because
193 * there is the possibility that the key was already on disk
194 * and we didn't just generate it now.
196 fp = fopen(CTDL_KEY_PATH, "r");
198 rsa = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
204 /** Create a public key from the private key */
205 if (pk=EVP_PKEY_new(), pk != NULL) {
206 EVP_PKEY_assign_RSA(pk, rsa);
207 if (req = X509_REQ_new(), req != NULL) {
209 /* Set the public key */
210 X509_REQ_set_pubkey(req, pk);
211 X509_REQ_set_version(req, 0L);
213 name = X509_REQ_get_subject_name(req);
215 /* Tell it who we are */
218 * We used to add these fields to the subject, but
219 * now we don't. Someone doing this for real isn't
220 * going to use the webcit-generated CSR anyway.
222 X509_NAME_add_entry_by_txt(name, "C",
223 MBSTRING_ASC, "US", -1, -1, 0);
225 X509_NAME_add_entry_by_txt(name, "ST",
226 MBSTRING_ASC, "New York", -1, -1, 0);
228 X509_NAME_add_entry_by_txt(name, "L",
229 MBSTRING_ASC, "Mount Kisco", -1, -1, 0);
234 env = "Organization name",
236 X509_NAME_add_entry_by_txt(
245 env = "Citadel server";
247 X509_NAME_add_entry_by_txt(
258 X509_NAME_add_entry_by_txt(
265 X509_REQ_set_subject_name(req, name);
268 if (!X509_REQ_sign(req, pk, EVP_md5())) {
269 syslog(3, "X509_REQ_sign(): error\n");
272 /* Write it to disk. */
273 fp = fopen(CTDL_CSR_PATH, "w");
275 chmod(CTDL_CSR_PATH, 0600);
276 PEM_write_X509_REQ(fp, req);
280 syslog(3, "Cannot write key: %s\n", CTDL_CSR_PATH);
294 syslog(3, "Unable to read private key.\n");
301 * Generate a self-signed certificate if we don't have one.
303 if (access(CTDL_CER_PATH, R_OK) != 0) {
304 syslog(5, "Generating a self-signed certificate.\n");
306 /* Same deal as before: always read the key from disk because
307 * it may or may not have just been generated.
309 fp = fopen(CTDL_KEY_PATH, "r");
311 rsa = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
315 /* This also holds true for the CSR. */
320 if (pk=EVP_PKEY_new(), pk != NULL) {
321 EVP_PKEY_assign_RSA(pk, rsa);
324 fp = fopen(CTDL_CSR_PATH, "r");
326 req = PEM_read_X509_REQ(fp, NULL, NULL, NULL);
331 if (cer = X509_new(), cer != NULL) {
333 ASN1_INTEGER_set(X509_get_serialNumber(cer), 0);
334 X509_set_issuer_name(cer, req->req_info->subject);
335 X509_set_subject_name(cer, req->req_info->subject);
336 X509_gmtime_adj(X509_get_notBefore(cer), 0);
337 X509_gmtime_adj(X509_get_notAfter(cer),(long)60*60*24*SIGN_DAYS);
339 req_pkey = X509_REQ_get_pubkey(req);
340 X509_set_pubkey(cer, req_pkey);
341 EVP_PKEY_free(req_pkey);
344 if (!X509_sign(cer, pk, EVP_md5())) {
345 syslog(3, "X509_sign(): error\n");
348 /* Write it to disk. */
349 fp = fopen(CTDL_CER_PATH, "w");
351 chmod(CTDL_CER_PATH, 0600);
352 PEM_write_X509(fp, cer);
356 syslog(3, "Cannot write key: %s\n", CTDL_CER_PATH);
370 * Now try to bind to the key and certificate.
371 * Note that we use SSL_CTX_use_certificate_chain_file() which allows
372 * the certificate file to contain intermediate certificates.
374 SSL_CTX_use_certificate_chain_file(ssl_ctx, CTDL_CER_PATH);
375 SSL_CTX_use_PrivateKey_file(ssl_ctx, CTDL_KEY_PATH, SSL_FILETYPE_PEM);
376 if ( !SSL_CTX_check_private_key(ssl_ctx) ) {
377 syslog(3, "Cannot install certificate: %s\n",
378 ERR_reason_error_string(ERR_get_error()));
385 * starts SSL/TLS encryption for the current session.
387 int starttls(int sock) {
388 int retval, bits, alg_bits;/*r; */
391 pthread_setspecific(ThreadSSL, NULL);
396 if (!(newssl = SSL_new(ssl_ctx))) {
397 syslog(3, "SSL_new failed: %s\n", ERR_reason_error_string(ERR_get_error()));
400 if (!(SSL_set_fd(newssl, sock))) {
401 syslog(3, "SSL_set_fd failed: %s\n", ERR_reason_error_string(ERR_get_error()));
405 retval = SSL_accept(newssl);
408 * Can't notify the client of an error here; they will
409 * discover the problem at the SSL layer and should
410 * revert to unencrypted communications.
413 const char *ssl_error_reason = NULL;
415 errval = SSL_get_error(newssl, retval);
416 ssl_error_reason = ERR_reason_error_string(ERR_get_error());
417 if (ssl_error_reason == NULL) {
418 syslog(3, "SSL_accept failed: errval=%ld, retval=%d %s\n", errval, retval, strerror(errval));
421 syslog(3, "SSL_accept failed: %s\n", ssl_error_reason);
424 retval = SSL_accept(newssl);
428 const char *ssl_error_reason = NULL;
430 errval = SSL_get_error(newssl, retval);
431 ssl_error_reason = ERR_reason_error_string(ERR_get_error());
432 if (ssl_error_reason == NULL) {
433 syslog(3, "SSL_accept failed: errval=%ld, retval=%d (%s)\n", errval, retval, strerror(errval));
436 syslog(3, "SSL_accept failed: %s\n", ssl_error_reason);
443 syslog(15, "SSL_accept success\n");
445 /*r = */BIO_set_close(newssl->rbio, BIO_NOCLOSE);
446 bits = SSL_CIPHER_get_bits(SSL_get_current_cipher(newssl), &alg_bits);
447 syslog(15, "SSL/TLS using %s on %s (%d of %d bits)\n",
448 SSL_CIPHER_get_name(SSL_get_current_cipher(newssl)),
449 SSL_CIPHER_get_version(SSL_get_current_cipher(newssl)),
452 pthread_setspecific(ThreadSSL, newssl);
453 syslog(15, "SSL started\n");
460 * shuts down the TLS connection
462 * WARNING: This may make your session vulnerable to a known plaintext
463 * attack in the current implmentation.
469 if (THREADSSL == NULL) return;
471 syslog(15, "Ending SSL/TLS\n");
472 SSL_shutdown(THREADSSL);
473 /*ctx = */SSL_get_SSL_CTX(THREADSSL);
475 /* I don't think this is needed, and it crashes the server anyway
478 * syslog(9, "Freeing CTX at %x\n", (int)ctx );
484 pthread_setspecific(ThreadSSL, NULL);
489 * callback for OpenSSL mutex locks
491 void ssl_lock(int mode, int n, const char *file, int line)
493 if (mode & CRYPTO_LOCK) {
494 pthread_mutex_lock(SSLCritters[n]);
497 pthread_mutex_unlock(SSLCritters[n]);
502 * Send binary data to the client encrypted.
504 void client_write_ssl(const StrBuf *Buf)
512 if (THREADSSL == NULL) return;
514 nbytes = nremain = StrLength(Buf);
517 while (nremain > 0) {
518 if (SSL_want_write(THREADSSL)) {
519 if ((SSL_read(THREADSSL, junk, 0)) < 1) {
520 syslog(9, "SSL_read in client_write: %s\n",
521 ERR_reason_error_string(ERR_get_error()));
524 retval = SSL_write(THREADSSL, &buf[nbytes - nremain], nremain);
528 errval = SSL_get_error(THREADSSL, retval);
529 if (errval == SSL_ERROR_WANT_READ || errval == SSL_ERROR_WANT_WRITE) {
533 syslog(9, "SSL_write got error %ld, ret %d\n", errval, retval);
535 syslog(9, "errno is %d\n", errno);
546 * read data from the encrypted layer.
548 int client_read_sslbuffer(StrBuf *buf, int timeout)
550 char sbuf[16384]; /* OpenSSL communicates in 16k blocks, so let's speak its native tongue. */
553 SSL *pssl = THREADSSL;
555 if (pssl == NULL) return(-1);
558 if (SSL_want_read(pssl)) {
559 if ((SSL_write(pssl, junk, 0)) < 1) {
560 syslog(9, "SSL_write in client_read\n");
563 rlen = SSL_read(pssl, sbuf, sizeof(sbuf));
567 errval = SSL_get_error(pssl, rlen);
568 if (errval == SSL_ERROR_WANT_READ || errval == SSL_ERROR_WANT_WRITE) {
572 syslog(9, "SSL_read got error %ld\n", errval);
576 StrBufAppendBufPlain(buf, sbuf, rlen, 0);
582 #endif /* HAVE_OPENSSL */