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 #ifndef OPENSSL_NO_EGD
69 if (!access("/var/run/egd-pool", F_OK)) {
70 RAND_egd("/var/run/egd-pool");
75 syslog(LOG_WARNING, "PRNG not adequately seeded, won't do SSL/TLS\n");
78 SSLCritters = malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t *));
80 syslog(LOG_ERR, "citserver: can't allocate memory!!\n");
81 /* Nothing's been initialized, just die */
87 for (a = 0; a < CRYPTO_num_locks(); a++) {
88 SSLCritters[a] = malloc(sizeof(pthread_mutex_t));
89 if (!SSLCritters[a]) {
91 "citserver: can't allocate memory!!\n");
92 /** Nothing's been initialized, just die */
96 pthread_mutex_init(SSLCritters[a], NULL);
101 * Initialize SSL transport layer
104 SSL_load_error_strings();
105 ssl_method = SSLv23_server_method();
106 if (!(ssl_ctx = SSL_CTX_new(ssl_method))) {
107 syslog(LOG_WARNING, "SSL_CTX_new failed: %s\n", ERR_reason_error_string(ERR_get_error()));
111 syslog(LOG_INFO, "Requesting cipher list: %s\n", ssl_cipher_list);
112 if (!(SSL_CTX_set_cipher_list(ssl_ctx, ssl_cipher_list))) {
113 syslog(LOG_WARNING, "SSL_CTX_set_cipher_list failed: %s\n", ERR_reason_error_string(ERR_get_error()));
117 CRYPTO_set_locking_callback(ssl_lock);
118 CRYPTO_set_id_callback(id_callback);
121 * Get our certificates in order. (FIXME: dirify. this is a setup job.)
122 * First, create the key/cert directory if it's not there already...
124 mkdir(CTDL_CRYPTO_DIR, 0700);
127 * Before attempting to generate keys/certificates, first try
128 * link to them from the Citadel server if it's on the same host.
129 * We ignore any error return because it either meant that there
130 * was nothing in Citadel to link from (in which case we just
131 * generate new files) or the target files already exist (which
132 * is not fatal either).
134 if (!strcasecmp(ctdlhost, "uds")) {
135 sprintf(buf, "%s/keys/citadel.key", ctdlport);
136 rv = symlink(buf, CTDL_KEY_PATH);
137 if (!rv) syslog(LOG_DEBUG, "%s\n", strerror(errno));
138 sprintf(buf, "%s/keys/citadel.csr", ctdlport);
139 rv = symlink(buf, CTDL_CSR_PATH);
140 if (!rv) syslog(LOG_DEBUG, "%s\n", strerror(errno));
141 sprintf(buf, "%s/keys/citadel.cer", ctdlport);
142 rv = symlink(buf, CTDL_CER_PATH);
143 if (!rv) syslog(LOG_DEBUG, "%s\n", strerror(errno));
147 * If we still don't have a private key, generate one.
149 if (access(CTDL_KEY_PATH, R_OK) != 0) {
150 syslog(LOG_INFO, "Generating RSA key pair.\n");
151 rsa = RSA_generate_key(1024, /* modulus size */
152 65537, /* exponent */
153 NULL, /* no callback */
154 NULL /* no callback */
157 syslog(LOG_WARNING, "Key generation failed: %s\n", ERR_reason_error_string(ERR_get_error()));
160 fp = fopen(CTDL_KEY_PATH, "w");
162 chmod(CTDL_KEY_PATH, 0600);
163 if (PEM_write_RSAPrivateKey(fp, /* the file */
166 NULL, /* no passphr */
168 NULL, /* no callbk */
171 syslog(LOG_WARNING, "Cannot write key: %s\n",
172 ERR_reason_error_string(ERR_get_error()));
173 unlink(CTDL_KEY_PATH);
178 syslog(LOG_WARNING, "Cannot write key: %s\n", CTDL_KEY_PATH);
187 * If there is no certificate file on disk, we will be generating a self-signed certificate
188 * in the next step. Therefore, if we have neither a CSR nor a certificate, generate
189 * the CSR in this step so that the next step may commence.
191 if ( (access(CTDL_CER_PATH, R_OK) != 0) && (access(CTDL_CSR_PATH, R_OK) != 0) ) {
192 syslog(LOG_INFO, "Generating a certificate signing request.\n");
195 * Read our key from the file. No, we don't just keep this
196 * in memory from the above key-generation function, because
197 * there is the possibility that the key was already on disk
198 * and we didn't just generate it now.
200 fp = fopen(CTDL_KEY_PATH, "r");
202 rsa = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
208 /** Create a public key from the private key */
209 if (pk=EVP_PKEY_new(), pk != NULL) {
210 EVP_PKEY_assign_RSA(pk, rsa);
211 if (req = X509_REQ_new(), req != NULL) {
213 /* Set the public key */
214 X509_REQ_set_pubkey(req, pk);
215 X509_REQ_set_version(req, 0L);
217 name = X509_REQ_get_subject_name(req);
219 /* Tell it who we are */
222 * We used to add these fields to the subject, but
223 * now we don't. Someone doing this for real isn't
224 * going to use the webcit-generated CSR anyway.
226 X509_NAME_add_entry_by_txt(name, "C",
227 MBSTRING_ASC, "US", -1, -1, 0);
229 X509_NAME_add_entry_by_txt(name, "ST",
230 MBSTRING_ASC, "New York", -1, -1, 0);
232 X509_NAME_add_entry_by_txt(name, "L",
233 MBSTRING_ASC, "Mount Kisco", -1, -1, 0);
238 env = "Organization name",
240 X509_NAME_add_entry_by_txt(
249 env = "Citadel server";
251 X509_NAME_add_entry_by_txt(
262 X509_NAME_add_entry_by_txt(
269 X509_REQ_set_subject_name(req, name);
272 if (!X509_REQ_sign(req, pk, EVP_md5())) {
273 syslog(LOG_WARNING, "X509_REQ_sign(): error\n");
276 /* Write it to disk. */
277 fp = fopen(CTDL_CSR_PATH, "w");
279 chmod(CTDL_CSR_PATH, 0600);
280 PEM_write_X509_REQ(fp, req);
284 syslog(LOG_WARNING, "Cannot write key: %s\n", CTDL_CSR_PATH);
298 syslog(LOG_WARNING, "Unable to read private key.\n");
305 * Generate a self-signed certificate if we don't have one.
307 if (access(CTDL_CER_PATH, R_OK) != 0) {
308 syslog(LOG_INFO, "Generating a self-signed certificate.\n");
310 /* Same deal as before: always read the key from disk because
311 * it may or may not have just been generated.
313 fp = fopen(CTDL_KEY_PATH, "r");
315 rsa = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
319 /* This also holds true for the CSR. */
324 if (pk=EVP_PKEY_new(), pk != NULL) {
325 EVP_PKEY_assign_RSA(pk, rsa);
328 fp = fopen(CTDL_CSR_PATH, "r");
330 req = PEM_read_X509_REQ(fp, NULL, NULL, NULL);
335 if (cer = X509_new(), cer != NULL) {
337 ASN1_INTEGER_set(X509_get_serialNumber(cer), 0);
338 X509_set_issuer_name(cer, X509_REQ_get_subject_name(req));
339 X509_set_subject_name(cer, X509_REQ_get_subject_name(req));
340 X509_gmtime_adj(X509_get_notBefore(cer), 0);
341 X509_gmtime_adj(X509_get_notAfter(cer),(long)60*60*24*SIGN_DAYS);
343 req_pkey = X509_REQ_get_pubkey(req);
344 X509_set_pubkey(cer, req_pkey);
345 EVP_PKEY_free(req_pkey);
348 if (!X509_sign(cer, pk, EVP_md5())) {
349 syslog(LOG_WARNING, "X509_sign(): error\n");
352 /* Write it to disk. */
353 fp = fopen(CTDL_CER_PATH, "w");
355 chmod(CTDL_CER_PATH, 0600);
356 PEM_write_X509(fp, cer);
360 syslog(LOG_WARNING, "Cannot write key: %s\n", CTDL_CER_PATH);
374 * Now try to bind to the key and certificate.
375 * Note that we use SSL_CTX_use_certificate_chain_file() which allows
376 * the certificate file to contain intermediate certificates.
378 SSL_CTX_use_certificate_chain_file(ssl_ctx, CTDL_CER_PATH);
379 SSL_CTX_use_PrivateKey_file(ssl_ctx, CTDL_KEY_PATH, SSL_FILETYPE_PEM);
380 if ( !SSL_CTX_check_private_key(ssl_ctx) ) {
381 syslog(LOG_WARNING, "Cannot install certificate: %s\n",
382 ERR_reason_error_string(ERR_get_error()));
389 * starts SSL/TLS encryption for the current session.
391 int starttls(int sock) {
392 int retval, bits, alg_bits;/*r; */
395 pthread_setspecific(ThreadSSL, NULL);
400 if (!(newssl = SSL_new(ssl_ctx))) {
401 syslog(LOG_WARNING, "SSL_new failed: %s\n", ERR_reason_error_string(ERR_get_error()));
404 if (!(SSL_set_fd(newssl, sock))) {
405 syslog(LOG_WARNING, "SSL_set_fd failed: %s\n", ERR_reason_error_string(ERR_get_error()));
409 retval = SSL_accept(newssl);
412 * Can't notify the client of an error here; they will
413 * discover the problem at the SSL layer and should
414 * revert to unencrypted communications.
417 const char *ssl_error_reason = NULL;
419 errval = SSL_get_error(newssl, retval);
420 ssl_error_reason = ERR_reason_error_string(ERR_get_error());
421 if (ssl_error_reason == NULL) {
422 syslog(LOG_WARNING, "SSL_accept failed: errval=%ld, retval=%d %s\n", errval, retval, strerror(errval));
425 syslog(LOG_WARNING, "SSL_accept failed: %s\n", ssl_error_reason);
428 retval = SSL_accept(newssl);
432 const char *ssl_error_reason = NULL;
434 errval = SSL_get_error(newssl, retval);
435 ssl_error_reason = ERR_reason_error_string(ERR_get_error());
436 if (ssl_error_reason == NULL) {
437 syslog(LOG_WARNING, "SSL_accept failed: errval=%ld, retval=%d (%s)\n", errval, retval, strerror(errval));
440 syslog(LOG_WARNING, "SSL_accept failed: %s\n", ssl_error_reason);
447 syslog(LOG_INFO, "SSL_accept success\n");
449 /*r = */BIO_set_close(SSL_get_rbio(newssl), BIO_NOCLOSE);
450 bits = SSL_CIPHER_get_bits(SSL_get_current_cipher(newssl), &alg_bits);
451 syslog(LOG_INFO, "SSL/TLS using %s on %s (%d of %d bits)\n",
452 SSL_CIPHER_get_name(SSL_get_current_cipher(newssl)),
453 SSL_CIPHER_get_version(SSL_get_current_cipher(newssl)),
456 pthread_setspecific(ThreadSSL, newssl);
457 syslog(LOG_INFO, "SSL started\n");
464 * shuts down the TLS connection
466 * WARNING: This may make your session vulnerable to a known plaintext
467 * attack in the current implmentation.
473 if (THREADSSL == NULL) return;
475 syslog(LOG_INFO, "Ending SSL/TLS\n");
476 SSL_shutdown(THREADSSL);
477 /*ctx = */SSL_get_SSL_CTX(THREADSSL);
479 /* I don't think this is needed, and it crashes the server anyway
482 * syslog(LOG_DEBUG, "Freeing CTX at %x\n", (int)ctx );
488 pthread_setspecific(ThreadSSL, NULL);
493 * callback for OpenSSL mutex locks
495 void ssl_lock(int mode, int n, const char *file, int line)
497 if (mode & CRYPTO_LOCK) {
498 pthread_mutex_lock(SSLCritters[n]);
501 pthread_mutex_unlock(SSLCritters[n]);
506 * Send binary data to the client encrypted.
508 int client_write_ssl(const StrBuf *Buf)
516 if (THREADSSL == NULL) return -1;
518 nbytes = nremain = StrLength(Buf);
521 while (nremain > 0) {
522 if (SSL_want_write(THREADSSL)) {
523 if ((SSL_read(THREADSSL, junk, 0)) < 1) {
524 syslog(LOG_WARNING, "SSL_read in client_write: %s\n",
525 ERR_reason_error_string(ERR_get_error()));
528 retval = SSL_write(THREADSSL, &buf[nbytes - nremain], nremain);
532 errval = SSL_get_error(THREADSSL, retval);
533 if (errval == SSL_ERROR_WANT_READ || errval == SSL_ERROR_WANT_WRITE) {
537 syslog(LOG_WARNING, "SSL_write got error %ld, ret %d\n", errval, retval);
539 syslog(LOG_WARNING, "errno is %d\n", errno);
551 * read data from the encrypted layer.
553 int client_read_sslbuffer(StrBuf *buf, int timeout)
555 char sbuf[16384]; /* OpenSSL communicates in 16k blocks, so let's speak its native tongue. */
558 SSL *pssl = THREADSSL;
560 if (pssl == NULL) return(-1);
563 if (SSL_want_read(pssl)) {
564 if ((SSL_write(pssl, junk, 0)) < 1) {
565 syslog(LOG_WARNING, "SSL_write in client_read\n");
568 rlen = SSL_read(pssl, sbuf, sizeof(sbuf));
572 errval = SSL_get_error(pssl, rlen);
573 if (errval == SSL_ERROR_WANT_READ || errval == SSL_ERROR_WANT_WRITE) {
577 syslog(LOG_WARNING, "SSL_read got error %ld\n", errval);
581 StrBufAppendBufPlain(buf, sbuf, rlen, 0);
587 #endif /* HAVE_OPENSSL */