4 * Provides HTTPS, when the OpenSSL library is available.
10 #include "webserver.h"
12 #define CTDL_CRYPTO_DIR "./keys"
13 #define CTDL_KEY_PATH CTDL_CRYPTO_DIR "/citadel.key"
14 #define CTDL_CSR_PATH CTDL_CRYPTO_DIR "/citadel.csr"
15 #define CTDL_CER_PATH CTDL_CRYPTO_DIR "/citadel.cer"
18 SSL_CTX *ssl_ctx; /* SSL context */
19 pthread_mutex_t **SSLCritters; /* Things needing locking */
21 pthread_key_t ThreadSSL; /* Per-thread SSL context */
23 static unsigned long id_callback(void)
25 return (unsigned long) pthread_self();
31 SSL_METHOD *ssl_method;
36 EVP_PKEY *req_pkey = NULL;
37 X509_NAME *name = NULL;
41 if (!access("/var/run/egd-pool", F_OK))
42 RAND_egd("/var/run/egd-pool");
46 "PRNG not adequately seeded, won't do SSL/TLS\n");
50 malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t *));
52 lprintf(1, "citserver: can't allocate memory!!\n");
53 /* Nothing's been initialized, just die */
58 for (a = 0; a < CRYPTO_num_locks(); a++) {
59 SSLCritters[a] = malloc(sizeof(pthread_mutex_t));
60 if (!SSLCritters[a]) {
62 "citserver: can't allocate memory!!\n");
63 /* Nothing's been initialized, just die */
66 pthread_mutex_init(SSLCritters[a], NULL);
71 * Initialize SSL transport layer
74 SSL_load_error_strings();
75 ssl_method = SSLv23_server_method();
76 if (!(ssl_ctx = SSL_CTX_new(ssl_method))) {
77 lprintf(3, "SSL_CTX_new failed: %s\n",
78 ERR_reason_error_string(ERR_get_error()));
82 CRYPTO_set_locking_callback(ssl_lock);
83 CRYPTO_set_id_callback(id_callback);
85 /* Get our certificates in order.
86 * First, create the key/cert directory if it's not there already...
88 mkdir(CTDL_CRYPTO_DIR, 0700);
91 * Before attempting to generate keys/certificates, first try
92 * link to them from the Citadel server if it's on the same host.
93 * We ignore any error return because it either meant that there
94 * was nothing in Citadel to link from (in which case we just
95 * generate new files) or the target files already exist (which
96 * is not fatal either).
98 if (!strcasecmp(ctdlhost, "uds")) {
99 sprintf(buf, "%s/keys/citadel.key", ctdlport);
100 symlink(buf, CTDL_KEY_PATH);
101 sprintf(buf, "%s/keys/citadel.csr", ctdlport);
102 symlink(buf, CTDL_CSR_PATH);
103 sprintf(buf, "%s/keys/citadel.cer", ctdlport);
104 symlink(buf, CTDL_CER_PATH);
108 * If we still don't have a private key, generate one.
110 if (access(CTDL_KEY_PATH, R_OK) != 0) {
111 lprintf(5, "Generating RSA key pair.\n");
112 rsa = RSA_generate_key(1024, /* modulus size */
113 65537, /* exponent */
114 NULL, /* no callback */
115 NULL); /* no callback */
117 lprintf(3, "Key generation failed: %s\n",
118 ERR_reason_error_string(ERR_get_error()));
121 fp = fopen(CTDL_KEY_PATH, "w");
123 chmod(CTDL_KEY_PATH, 0600);
124 if (PEM_write_RSAPrivateKey(fp, /* the file */
127 NULL, /* no passphr */
129 NULL, /* no callbk */
132 lprintf(3, "Cannot write key: %s\n",
133 ERR_reason_error_string(ERR_get_error()));
134 unlink(CTDL_KEY_PATH);
143 * Generate a CSR if we don't have one.
145 if (access(CTDL_CSR_PATH, R_OK) != 0) {
146 lprintf(5, "Generating a certificate signing request.\n");
149 * Read our key from the file. No, we don't just keep this
150 * in memory from the above key-generation function, because
151 * there is the possibility that the key was already on disk
152 * and we didn't just generate it now.
154 fp = fopen(CTDL_KEY_PATH, "r");
156 rsa = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
162 /* Create a public key from the private key */
163 if (pk=EVP_PKEY_new(), pk != NULL) {
164 EVP_PKEY_assign_RSA(pk, rsa);
165 if (req = X509_REQ_new(), req != NULL) {
167 /* Set the public key */
168 X509_REQ_set_pubkey(req, pk);
169 X509_REQ_set_version(req, 0L);
171 name = X509_REQ_get_subject_name(req);
173 /* Tell it who we are */
176 X509_NAME_add_entry_by_txt(name, "C",
177 MBSTRING_ASC, "US", -1, -1, 0);
179 X509_NAME_add_entry_by_txt(name, "ST",
180 MBSTRING_ASC, "New York", -1, -1, 0);
182 X509_NAME_add_entry_by_txt(name, "L",
183 MBSTRING_ASC, "Mount Kisco", -1, -1, 0);
186 X509_NAME_add_entry_by_txt(name, "O",
187 MBSTRING_ASC, "FIXME.FIXME.org", -1, -1, 0);
189 X509_NAME_add_entry_by_txt(name, "OU",
190 MBSTRING_ASC, "Citadel server", -1, -1, 0);
192 X509_NAME_add_entry_by_txt(name, "CN",
193 MBSTRING_ASC, "FIXME.FIXME.org", -1, -1, 0);
195 X509_REQ_set_subject_name(req, name);
198 if (!X509_REQ_sign(req, pk, EVP_md5())) {
199 lprintf(3, "X509_REQ_sign(): error\n");
202 /* Write it to disk. */
203 fp = fopen(CTDL_CSR_PATH, "w");
205 chmod(CTDL_CSR_PATH, 0600);
206 PEM_write_X509_REQ(fp, req);
219 lprintf(3, "Unable to read private key.\n");
226 * Generate a self-signed certificate if we don't have one.
228 if (access(CTDL_CER_PATH, R_OK) != 0) {
229 lprintf(5, "Generating a self-signed certificate.\n");
231 /* Same deal as before: always read the key from disk because
232 * it may or may not have just been generated.
234 fp = fopen(CTDL_KEY_PATH, "r");
236 rsa = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
240 /* This also holds true for the CSR. */
245 if (pk=EVP_PKEY_new(), pk != NULL) {
246 EVP_PKEY_assign_RSA(pk, rsa);
249 fp = fopen(CTDL_CSR_PATH, "r");
251 req = PEM_read_X509_REQ(fp, NULL, NULL, NULL);
256 if (cer = X509_new(), cer != NULL) {
258 ASN1_INTEGER_set(X509_get_serialNumber(cer), 0);
259 X509_set_issuer_name(cer, req->req_info->subject);
260 X509_set_subject_name(cer, req->req_info->subject);
261 X509_gmtime_adj(X509_get_notBefore(cer), 0);
262 X509_gmtime_adj(X509_get_notAfter(cer),(long)60*60*24*SIGN_DAYS);
264 req_pkey = X509_REQ_get_pubkey(req);
265 X509_set_pubkey(cer, req_pkey);
266 EVP_PKEY_free(req_pkey);
269 if (!X509_sign(cer, pk, EVP_md5())) {
270 lprintf(3, "X509_sign(): error\n");
273 /* Write it to disk. */
274 fp = fopen(CTDL_CER_PATH, "w");
276 chmod(CTDL_CER_PATH, 0600);
277 PEM_write_X509(fp, cer);
290 * Now try to bind to the key and certificate.
291 * Note that we use SSL_CTX_use_certificate_chain_file() which allows
292 * the certificate file to contain intermediate certificates.
294 SSL_CTX_use_certificate_chain_file(ssl_ctx, CTDL_CER_PATH);
295 SSL_CTX_use_PrivateKey_file(ssl_ctx, CTDL_KEY_PATH, SSL_FILETYPE_PEM);
296 if ( !SSL_CTX_check_private_key(ssl_ctx) ) {
297 lprintf(3, "Cannot install certificate: %s\n",
298 ERR_reason_error_string(ERR_get_error()));
305 * starttls() starts SSL/TLS encryption for the current session.
307 int starttls(int sock) {
308 int retval, bits, alg_bits;
311 pthread_setspecific(ThreadSSL, NULL);
316 if (!(newssl = SSL_new(ssl_ctx))) {
317 lprintf(3, "SSL_new failed: %s\n",
318 ERR_reason_error_string(ERR_get_error()));
321 if (!(SSL_set_fd(newssl, sock))) {
322 lprintf(3, "SSL_set_fd failed: %s\n",
323 ERR_reason_error_string(ERR_get_error()));
327 retval = SSL_accept(newssl);
330 * Can't notify the client of an error here; they will
331 * discover the problem at the SSL layer and should
332 * revert to unencrypted communications.
336 errval = SSL_get_error(newssl, retval);
337 lprintf(3, "SSL_accept failed: %s\n",
338 ERR_reason_error_string(ERR_get_error()));
343 BIO_set_close(newssl->rbio, BIO_NOCLOSE);
345 SSL_CIPHER_get_bits(SSL_get_current_cipher(newssl),
347 lprintf(5, "SSL/TLS using %s on %s (%d of %d bits)\n",
348 SSL_CIPHER_get_name(SSL_get_current_cipher(newssl)),
349 SSL_CIPHER_get_version(SSL_get_current_cipher(newssl)),
352 pthread_setspecific(ThreadSSL, newssl);
359 * endtls() shuts down the TLS connection
361 * WARNING: This may make your session vulnerable to a known plaintext
362 * attack in the current implmentation.
366 if (THREADSSL == NULL) return;
368 lprintf(5, "Ending SSL/TLS\n");
369 SSL_shutdown(THREADSSL);
371 pthread_setspecific(ThreadSSL, NULL);
376 * ssl_lock() callback for OpenSSL mutex locks
378 void ssl_lock(int mode, int n, const char *file, int line)
380 if (mode & CRYPTO_LOCK)
381 pthread_mutex_lock(SSLCritters[n]);
383 pthread_mutex_unlock(SSLCritters[n]);
387 * client_write_ssl() Send binary data to the client encrypted.
389 void client_write_ssl(char *buf, int nbytes)
395 if (THREADSSL == NULL) return;
399 while (nremain > 0) {
400 if (SSL_want_write(THREADSSL)) {
401 if ((SSL_read(THREADSSL, junk, 0)) < 1) {
402 lprintf(9, "SSL_read in client_write: %s\n",
403 ERR_reason_error_string(ERR_get_error()));
406 retval = SSL_write(THREADSSL, &buf[nbytes - nremain], nremain);
410 errval = SSL_get_error(THREADSSL, retval);
411 if (errval == SSL_ERROR_WANT_READ ||
412 errval == SSL_ERROR_WANT_WRITE) {
416 lprintf(9, "SSL_write got error %ld, ret %d\n", errval, retval);
418 lprintf(9, "errno is %d\n", errno);
429 * client_read_ssl() - read data from the encrypted layer.
431 int client_read_ssl(char *buf, int bytes, int timeout)
442 if (THREADSSL == NULL) return(0);
445 while (len < bytes) {
448 * This code is disabled because we don't need it when
449 * using blocking reads (which we are). -IO
452 s = BIO_get_fd(THREADSSL->rbio, NULL);
457 retval = select(s + 1, &rfds, NULL, NULL, &tv);
459 if (FD_ISSET(s, &rfds) == 0) {
464 if (SSL_want_read(THREADSSL)) {
465 if ((SSL_write(THREADSSL, junk, 0)) < 1) {
466 lprintf(9, "SSL_write in client_read: %s\n", ERR_reason_error_string(ERR_get_error()));
469 rlen = SSL_read(THREADSSL, &buf[len], bytes - len);
473 errval = SSL_get_error(THREADSSL, rlen);
474 if (errval == SSL_ERROR_WANT_READ ||
475 errval == SSL_ERROR_WANT_WRITE) {
479 lprintf(9, "SSL_read got error %ld\n", errval);
489 #endif /* HAVE_OPENSSL */