5 * \defgroup https Provides HTTPS, when the OpenSSL library is available.
12 #include "webserver.h"
14 /** where to find the keys */
15 #define CTDL_CRYPTO_DIR "./keys"
16 #define CTDL_KEY_PATH CTDL_CRYPTO_DIR "/citadel.key" /**< the key */
17 #define CTDL_CSR_PATH CTDL_CRYPTO_DIR "/citadel.csr" /**< the csr file */
18 #define CTDL_CER_PATH CTDL_CRYPTO_DIR "/citadel.cer" /**< the cer file */
19 #define SIGN_DAYS 365 /**< how long our certificate should live */
21 SSL_CTX *ssl_ctx; /**< SSL context */
22 pthread_mutex_t **SSLCritters; /**< Things needing locking */
24 pthread_key_t ThreadSSL; /**< Per-thread SSL context */
28 * \return thread id???
30 static unsigned long id_callback(void)
32 return (unsigned long) pthread_self();
36 * \brief initialize ssl engine
37 * load certs and initialize openssl internals
41 SSL_METHOD *ssl_method;
46 EVP_PKEY *req_pkey = NULL;
47 X509_NAME *name = NULL;
51 if (!access("/var/run/egd-pool", F_OK))
52 RAND_egd("/var/run/egd-pool");
56 "PRNG not adequately seeded, won't do SSL/TLS\n");
60 malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t *));
62 lprintf(1, "citserver: can't allocate memory!!\n");
63 /* Nothing's been initialized, just die */
68 for (a = 0; a < CRYPTO_num_locks(); a++) {
69 SSLCritters[a] = malloc(sizeof(pthread_mutex_t));
70 if (!SSLCritters[a]) {
72 "citserver: can't allocate memory!!\n");
73 /** Nothing's been initialized, just die */
76 pthread_mutex_init(SSLCritters[a], NULL);
81 * Initialize SSL transport layer
84 SSL_load_error_strings();
85 ssl_method = SSLv23_server_method();
86 if (!(ssl_ctx = SSL_CTX_new(ssl_method))) {
87 lprintf(3, "SSL_CTX_new failed: %s\n",
88 ERR_reason_error_string(ERR_get_error()));
92 CRYPTO_set_locking_callback(ssl_lock);
93 CRYPTO_set_id_callback(id_callback);
96 * Get our certificates in order. \todo dirify. this is a setup job.
97 * First, create the key/cert directory if it's not there already...
99 mkdir(CTDL_CRYPTO_DIR, 0700);
102 * Before attempting to generate keys/certificates, first try
103 * link to them from the Citadel server if it's on the same host.
104 * We ignore any error return because it either meant that there
105 * was nothing in Citadel to link from (in which case we just
106 * generate new files) or the target files already exist (which
107 * is not fatal either). \todo dirify
109 if (!strcasecmp(ctdlhost, "uds")) {
110 sprintf(buf, "%s/keys/citadel.key", ctdlport);
111 symlink(buf, CTDL_KEY_PATH);
112 sprintf(buf, "%s/keys/citadel.csr", ctdlport);
113 symlink(buf, CTDL_CSR_PATH);
114 sprintf(buf, "%s/keys/citadel.cer", ctdlport);
115 symlink(buf, CTDL_CER_PATH);
119 * If we still don't have a private key, generate one.
121 if (access(CTDL_KEY_PATH, R_OK) != 0) {
122 lprintf(5, "Generating RSA key pair.\n");
123 rsa = RSA_generate_key(1024, /**< modulus size */
124 65537, /**< exponent */
125 NULL, /**< no callback */
126 NULL); /**< no callback */
128 lprintf(3, "Key generation failed: %s\n",
129 ERR_reason_error_string(ERR_get_error()));
132 fp = fopen(CTDL_KEY_PATH, "w");
134 chmod(CTDL_KEY_PATH, 0600);
135 if (PEM_write_RSAPrivateKey(fp, /**< the file */
138 NULL, /**< no passphr */
139 0, /**< no passphr */
140 NULL, /**< no callbk */
141 NULL /**< no callbk */
143 lprintf(3, "Cannot write key: %s\n",
144 ERR_reason_error_string(ERR_get_error()));
145 unlink(CTDL_KEY_PATH);
154 * Generate a CSR if we don't have one.
156 if (access(CTDL_CSR_PATH, R_OK) != 0) {
157 lprintf(5, "Generating a certificate signing request.\n");
160 * Read our key from the file. No, we don't just keep this
161 * in memory from the above key-generation function, because
162 * there is the possibility that the key was already on disk
163 * and we didn't just generate it now.
165 fp = fopen(CTDL_KEY_PATH, "r");
167 rsa = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
173 /** Create a public key from the private key */
174 if (pk=EVP_PKEY_new(), pk != NULL) {
175 EVP_PKEY_assign_RSA(pk, rsa);
176 if (req = X509_REQ_new(), req != NULL) {
178 /** Set the public key */
179 X509_REQ_set_pubkey(req, pk);
180 X509_REQ_set_version(req, 0L);
182 name = X509_REQ_get_subject_name(req);
184 /** Tell it who we are */
187 X509_NAME_add_entry_by_txt(name, "C",
188 MBSTRING_ASC, "US", -1, -1, 0);
190 X509_NAME_add_entry_by_txt(name, "ST",
191 MBSTRING_ASC, "New York", -1, -1, 0);
193 X509_NAME_add_entry_by_txt(name, "L",
194 MBSTRING_ASC, "Mount Kisco", -1, -1, 0);
197 X509_NAME_add_entry_by_txt(name, "O",
198 MBSTRING_ASC, "FIXME.FIXME.org", -1, -1, 0);
200 X509_NAME_add_entry_by_txt(name, "OU",
201 MBSTRING_ASC, "Citadel server", -1, -1, 0);
203 X509_NAME_add_entry_by_txt(name, "CN",
204 MBSTRING_ASC, "FIXME.FIXME.org", -1, -1, 0);
206 X509_REQ_set_subject_name(req, name);
209 if (!X509_REQ_sign(req, pk, EVP_md5())) {
210 lprintf(3, "X509_REQ_sign(): error\n");
213 /** Write it to disk. */
214 fp = fopen(CTDL_CSR_PATH, "w");
216 chmod(CTDL_CSR_PATH, 0600);
217 PEM_write_X509_REQ(fp, req);
230 lprintf(3, "Unable to read private key.\n");
237 * Generate a self-signed certificate if we don't have one.
239 if (access(CTDL_CER_PATH, R_OK) != 0) {
240 lprintf(5, "Generating a self-signed certificate.\n");
242 /** Same deal as before: always read the key from disk because
243 * it may or may not have just been generated.
245 fp = fopen(CTDL_KEY_PATH, "r");
247 rsa = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
251 /** This also holds true for the CSR. */
256 if (pk=EVP_PKEY_new(), pk != NULL) {
257 EVP_PKEY_assign_RSA(pk, rsa);
260 fp = fopen(CTDL_CSR_PATH, "r");
262 req = PEM_read_X509_REQ(fp, NULL, NULL, NULL);
267 if (cer = X509_new(), cer != NULL) {
269 ASN1_INTEGER_set(X509_get_serialNumber(cer), 0);
270 X509_set_issuer_name(cer, req->req_info->subject);
271 X509_set_subject_name(cer, req->req_info->subject);
272 X509_gmtime_adj(X509_get_notBefore(cer), 0);
273 X509_gmtime_adj(X509_get_notAfter(cer),(long)60*60*24*SIGN_DAYS);
275 req_pkey = X509_REQ_get_pubkey(req);
276 X509_set_pubkey(cer, req_pkey);
277 EVP_PKEY_free(req_pkey);
280 if (!X509_sign(cer, pk, EVP_md5())) {
281 lprintf(3, "X509_sign(): error\n");
284 /** Write it to disk. */
285 fp = fopen(CTDL_CER_PATH, "w");
287 chmod(CTDL_CER_PATH, 0600);
288 PEM_write_X509(fp, cer);
301 * Now try to bind to the key and certificate.
302 * Note that we use SSL_CTX_use_certificate_chain_file() which allows
303 * the certificate file to contain intermediate certificates.
305 SSL_CTX_use_certificate_chain_file(ssl_ctx, CTDL_CER_PATH);
306 SSL_CTX_use_PrivateKey_file(ssl_ctx, CTDL_KEY_PATH, SSL_FILETYPE_PEM);
307 if ( !SSL_CTX_check_private_key(ssl_ctx) ) {
308 lprintf(3, "Cannot install certificate: %s\n",
309 ERR_reason_error_string(ERR_get_error()));
316 * \brief starts SSL/TLS encryption for the current session.
317 * \param sock the socket connection
320 int starttls(int sock) {
321 int retval, bits, alg_bits;
324 pthread_setspecific(ThreadSSL, NULL);
329 if (!(newssl = SSL_new(ssl_ctx))) {
330 lprintf(3, "SSL_new failed: %s\n",
331 ERR_reason_error_string(ERR_get_error()));
334 if (!(SSL_set_fd(newssl, sock))) {
335 lprintf(3, "SSL_set_fd failed: %s\n",
336 ERR_reason_error_string(ERR_get_error()));
340 retval = SSL_accept(newssl);
343 * Can't notify the client of an error here; they will
344 * discover the problem at the SSL layer and should
345 * revert to unencrypted communications.
349 errval = SSL_get_error(newssl, retval);
350 lprintf(3, "SSL_accept failed: %s\n",
351 ERR_reason_error_string(ERR_get_error()));
356 BIO_set_close(newssl->rbio, BIO_NOCLOSE);
358 SSL_CIPHER_get_bits(SSL_get_current_cipher(newssl),
360 lprintf(5, "SSL/TLS using %s on %s (%d of %d bits)\n",
361 SSL_CIPHER_get_name(SSL_get_current_cipher(newssl)),
362 SSL_CIPHER_get_version(SSL_get_current_cipher(newssl)),
365 pthread_setspecific(ThreadSSL, newssl);
372 * \brief shuts down the TLS connection
374 * WARNING: This may make your session vulnerable to a known plaintext
375 * attack in the current implmentation.
379 if (THREADSSL == NULL) return;
381 lprintf(5, "Ending SSL/TLS\n");
382 SSL_shutdown(THREADSSL);
384 pthread_setspecific(ThreadSSL, NULL);
389 * \brief callback for OpenSSL mutex locks
390 * \param mode which mode??????
391 * \param n how many???
392 * \param file which filename ???
393 * \param line what line????
395 void ssl_lock(int mode, int n, const char *file, int line)
397 if (mode & CRYPTO_LOCK)
398 pthread_mutex_lock(SSLCritters[n]);
400 pthread_mutex_unlock(SSLCritters[n]);
404 * \brief Send binary data to the client encrypted.
405 * \param buf chars to send to the client
406 * \param nbytes how many chars
408 void client_write_ssl(char *buf, int nbytes)
414 if (THREADSSL == NULL) return;
418 while (nremain > 0) {
419 if (SSL_want_write(THREADSSL)) {
420 if ((SSL_read(THREADSSL, junk, 0)) < 1) {
421 lprintf(9, "SSL_read in client_write: %s\n",
422 ERR_reason_error_string(ERR_get_error()));
425 retval = SSL_write(THREADSSL, &buf[nbytes - nremain], nremain);
429 errval = SSL_get_error(THREADSSL, retval);
430 if (errval == SSL_ERROR_WANT_READ ||
431 errval == SSL_ERROR_WANT_WRITE) {
435 lprintf(9, "SSL_write got error %ld, ret %d\n", errval, retval);
437 lprintf(9, "errno is %d\n", errno);
448 * \brief read data from the encrypted layer.
449 * \param buf charbuffer to read to
450 * \param bytes how many
451 * \param timeout how long should we wait?
454 int client_read_ssl(char *buf, int bytes, int timeout)
465 if (THREADSSL == NULL) return(0);
468 while (len < bytes) {
471 * This code is disabled because we don't need it when
472 * using blocking reads (which we are). -IO
475 s = BIO_get_fd(THREADSSL->rbio, NULL);
480 retval = select(s + 1, &rfds, NULL, NULL, &tv);
482 if (FD_ISSET(s, &rfds) == 0) {
487 if (SSL_want_read(THREADSSL)) {
488 if ((SSL_write(THREADSSL, junk, 0)) < 1) {
489 lprintf(9, "SSL_write in client_read: %s\n", ERR_reason_error_string(ERR_get_error()));
492 rlen = SSL_read(THREADSSL, &buf[len], bytes - len);
496 errval = SSL_get_error(THREADSSL, rlen);
497 if (errval == SSL_ERROR_WANT_READ ||
498 errval == SSL_ERROR_WANT_WRITE) {
502 lprintf(9, "SSL_read got error %ld\n", errval);
512 #endif /* HAVE_OPENSSL */