4 * Provides HTTPS, when the OpenSSL library is available.
13 #include <sys/types.h>
18 #include "webserver.h"
20 #define CTDL_CRYPTO_DIR "./keys"
21 #define CTDL_KEY_PATH CTDL_CRYPTO_DIR "/citadel.key"
22 #define CTDL_CSR_PATH CTDL_CRYPTO_DIR "/citadel.csr"
23 #define CTDL_CER_PATH CTDL_CRYPTO_DIR "/citadel.cer"
26 SSL_CTX *ssl_ctx; /* SSL context */
27 pthread_mutex_t **SSLCritters; /* Things needing locking */
29 pthread_key_t ThreadSSL; /* Per-thread SSL context */
31 static unsigned long id_callback(void)
33 return (unsigned long) pthread_self();
39 SSL_METHOD *ssl_method;
44 EVP_PKEY *req_pkey = NULL;
45 X509_NAME *name = NULL;
49 if (!access("/var/run/egd-pool", F_OK))
50 RAND_egd("/var/run/egd-pool");
54 "PRNG not adequately seeded, won't do SSL/TLS\n");
58 malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t *));
60 lprintf(1, "citserver: can't allocate memory!!\n");
61 /* Nothing's been initialized, just die */
66 for (a = 0; a < CRYPTO_num_locks(); a++) {
67 SSLCritters[a] = malloc(sizeof(pthread_mutex_t));
68 if (!SSLCritters[a]) {
70 "citserver: can't allocate memory!!\n");
71 /* Nothing's been initialized, just die */
74 pthread_mutex_init(SSLCritters[a], NULL);
79 * Initialize SSL transport layer
82 SSL_load_error_strings();
83 ssl_method = SSLv23_server_method();
84 if (!(ssl_ctx = SSL_CTX_new(ssl_method))) {
85 lprintf(3, "SSL_CTX_new failed: %s\n",
86 ERR_reason_error_string(ERR_get_error()));
90 CRYPTO_set_locking_callback(ssl_lock);
91 CRYPTO_set_id_callback(id_callback);
93 /* Get our certificates in order.
94 * First, create the key/cert directory if it's not there already...
96 mkdir(CTDL_CRYPTO_DIR, 0700);
99 * Before attempting to generate keys/certificates, first try
100 * link to them from the Citadel server if it's on the same host.
101 * We ignore any error return because it either meant that there
102 * was nothing in Citadel to link from (in which case we just
103 * generate new files) or the target files already exist (which
104 * is not fatal either).
106 if (!strcasecmp(ctdlhost, "uds")) {
107 sprintf(buf, "%s/keys/citadel.key", ctdlport);
108 symlink(buf, CTDL_KEY_PATH);
109 sprintf(buf, "%s/keys/citadel.csr", ctdlport);
110 symlink(buf, CTDL_CSR_PATH);
111 sprintf(buf, "%s/keys/citadel.cer", ctdlport);
112 symlink(buf, CTDL_CER_PATH);
116 * If we still don't have a private key, generate one.
118 if (access(CTDL_KEY_PATH, R_OK) != 0) {
119 lprintf(5, "Generating RSA key pair.\n");
120 rsa = RSA_generate_key(1024, /* modulus size */
121 65537, /* exponent */
122 NULL, /* no callback */
123 NULL); /* no callback */
125 lprintf(3, "Key generation failed: %s\n",
126 ERR_reason_error_string(ERR_get_error()));
129 fp = fopen(CTDL_KEY_PATH, "w");
131 chmod(CTDL_KEY_PATH, 0600);
132 if (PEM_write_RSAPrivateKey(fp, /* the file */
135 NULL, /* no passphr */
137 NULL, /* no callbk */
140 lprintf(3, "Cannot write key: %s\n",
141 ERR_reason_error_string(ERR_get_error()));
142 unlink(CTDL_KEY_PATH);
151 * Generate a CSR if we don't have one.
153 if (access(CTDL_CSR_PATH, R_OK) != 0) {
154 lprintf(5, "Generating a certificate signing request.\n");
157 * Read our key from the file. No, we don't just keep this
158 * in memory from the above key-generation function, because
159 * there is the possibility that the key was already on disk
160 * and we didn't just generate it now.
162 fp = fopen(CTDL_KEY_PATH, "r");
164 rsa = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
170 /* Create a public key from the private key */
171 if (pk=EVP_PKEY_new(), pk != NULL) {
172 EVP_PKEY_assign_RSA(pk, rsa);
173 if (req = X509_REQ_new(), req != NULL) {
175 /* Set the public key */
176 X509_REQ_set_pubkey(req, pk);
177 X509_REQ_set_version(req, 0L);
179 name = X509_REQ_get_subject_name(req);
181 /* Tell it who we are */
184 X509_NAME_add_entry_by_txt(name, "C",
185 MBSTRING_ASC, "US", -1, -1, 0);
187 X509_NAME_add_entry_by_txt(name, "ST",
188 MBSTRING_ASC, "New York", -1, -1, 0);
190 X509_NAME_add_entry_by_txt(name, "L",
191 MBSTRING_ASC, "Mount Kisco", -1, -1, 0);
194 X509_NAME_add_entry_by_txt(name, "O",
195 MBSTRING_ASC, "FIXME.FIXME.org", -1, -1, 0);
197 X509_NAME_add_entry_by_txt(name, "OU",
198 MBSTRING_ASC, "Citadel server", -1, -1, 0);
200 X509_NAME_add_entry_by_txt(name, "CN",
201 MBSTRING_ASC, "FIXME.FIXME.org", -1, -1, 0);
203 X509_REQ_set_subject_name(req, name);
206 if (!X509_REQ_sign(req, pk, EVP_md5())) {
207 lprintf(3, "X509_REQ_sign(): error\n");
210 /* Write it to disk. */
211 fp = fopen(CTDL_CSR_PATH, "w");
213 chmod(CTDL_CSR_PATH, 0600);
214 PEM_write_X509_REQ(fp, req);
227 lprintf(3, "Unable to read private key.\n");
234 * Generate a self-signed certificate if we don't have one.
236 if (access(CTDL_CER_PATH, R_OK) != 0) {
237 lprintf(5, "Generating a self-signed certificate.\n");
239 /* Same deal as before: always read the key from disk because
240 * it may or may not have just been generated.
242 fp = fopen(CTDL_KEY_PATH, "r");
244 rsa = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
248 /* This also holds true for the CSR. */
253 if (pk=EVP_PKEY_new(), pk != NULL) {
254 EVP_PKEY_assign_RSA(pk, rsa);
257 fp = fopen(CTDL_CSR_PATH, "r");
259 req = PEM_read_X509_REQ(fp, NULL, NULL, NULL);
264 if (cer = X509_new(), cer != NULL) {
266 ASN1_INTEGER_set(X509_get_serialNumber(cer), 0);
267 X509_set_issuer_name(cer, req->req_info->subject);
268 X509_set_subject_name(cer, req->req_info->subject);
269 X509_gmtime_adj(X509_get_notBefore(cer), 0);
270 X509_gmtime_adj(X509_get_notAfter(cer),(long)60*60*24*SIGN_DAYS);
272 req_pkey = X509_REQ_get_pubkey(req);
273 X509_set_pubkey(cer, req_pkey);
274 EVP_PKEY_free(req_pkey);
277 if (!X509_sign(cer, pk, EVP_md5())) {
278 lprintf(3, "X509_sign(): error\n");
281 /* Write it to disk. */
282 fp = fopen(CTDL_CER_PATH, "w");
284 chmod(CTDL_CER_PATH, 0600);
285 PEM_write_X509(fp, cer);
298 * Now try to bind to the key and certificate.
299 * Note that we use SSL_CTX_use_certificate_chain_file() which allows
300 * the certificate file to contain intermediate certificates.
302 SSL_CTX_use_certificate_chain_file(ssl_ctx, CTDL_CER_PATH);
303 SSL_CTX_use_PrivateKey_file(ssl_ctx, CTDL_KEY_PATH, SSL_FILETYPE_PEM);
304 if ( !SSL_CTX_check_private_key(ssl_ctx) ) {
305 lprintf(3, "Cannot install certificate: %s\n",
306 ERR_reason_error_string(ERR_get_error()));
313 * starttls() starts SSL/TLS encryption for the current session.
315 int starttls(int sock) {
316 int retval, bits, alg_bits;
319 pthread_setspecific(ThreadSSL, NULL);
324 if (!(newssl = SSL_new(ssl_ctx))) {
325 lprintf(3, "SSL_new failed: %s\n",
326 ERR_reason_error_string(ERR_get_error()));
329 if (!(SSL_set_fd(newssl, sock))) {
330 lprintf(3, "SSL_set_fd failed: %s\n",
331 ERR_reason_error_string(ERR_get_error()));
335 retval = SSL_accept(newssl);
338 * Can't notify the client of an error here; they will
339 * discover the problem at the SSL layer and should
340 * revert to unencrypted communications.
344 errval = SSL_get_error(newssl, retval);
345 lprintf(3, "SSL_accept failed: %s\n",
346 ERR_reason_error_string(ERR_get_error()));
351 BIO_set_close(newssl->rbio, BIO_NOCLOSE);
353 SSL_CIPHER_get_bits(SSL_get_current_cipher(newssl),
355 lprintf(5, "SSL/TLS using %s on %s (%d of %d bits)\n",
356 SSL_CIPHER_get_name(SSL_get_current_cipher(newssl)),
357 SSL_CIPHER_get_version(SSL_get_current_cipher(newssl)),
360 pthread_setspecific(ThreadSSL, newssl);
367 * endtls() shuts down the TLS connection
369 * WARNING: This may make your session vulnerable to a known plaintext
370 * attack in the current implmentation.
374 lprintf(5, "Ending SSL/TLS\n");
375 SSL_shutdown(THREADSSL);
377 pthread_setspecific(ThreadSSL, NULL);
382 * ssl_lock() callback for OpenSSL mutex locks
384 void ssl_lock(int mode, int n, const char *file, int line)
386 if (mode & CRYPTO_LOCK)
387 pthread_mutex_lock(SSLCritters[n]);
389 pthread_mutex_unlock(SSLCritters[n]);
393 * client_write_ssl() Send binary data to the client encrypted.
395 void client_write_ssl(char *buf, int nbytes)
403 while (nremain > 0) {
404 if (SSL_want_write(THREADSSL)) {
405 if ((SSL_read(THREADSSL, junk, 0)) < 1) {
406 lprintf(9, "SSL_read in client_write: %s\n", ERR_reason_error_string(ERR_get_error()));
410 SSL_write(THREADSSL, &buf[nbytes - nremain], nremain);
414 errval = SSL_get_error(THREADSSL, retval);
415 if (errval == SSL_ERROR_WANT_READ ||
416 errval == SSL_ERROR_WANT_WRITE) {
420 lprintf(9, "SSL_write got error %ld, ret %d\n", errval, retval);
422 lprintf(9, "errno is %d\n", errno);
432 * client_read_ssl() - read data from the encrypted layer.
434 int client_read_ssl(char *buf, int bytes, int timeout)
446 while (len < bytes) {
449 * This code is disabled because we don't need it when
450 * using blocking reads (which we are). -IO
453 s = BIO_get_fd(THREADSSL->rbio, NULL);
458 retval = select(s + 1, &rfds, NULL, NULL, &tv);
460 if (FD_ISSET(s, &rfds) == 0) {
465 if (SSL_want_read(THREADSSL)) {
466 if ((SSL_write(THREADSSL, junk, 0)) < 1) {
467 lprintf(9, "SSL_write in client_read: %s\n", ERR_reason_error_string(ERR_get_error()));
470 rlen = SSL_read(THREADSSL, &buf[len], bytes - len);
474 errval = SSL_get_error(THREADSSL, rlen);
475 if (errval == SSL_ERROR_WANT_READ ||
476 errval == SSL_ERROR_WANT_WRITE) {
480 lprintf(9, "SSL_read got error %ld\n", errval);
490 #endif /* HAVE_OPENSSL */