2 * Copyright (c) 1996-2017 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 void generate_key(char *keyfilename)
59 unsigned long e = RSA_F4;
62 if (access(keyfilename, R_OK) == 0) {
66 syslog(LOG_INFO, "crypto: generating RSA key pair");
70 ret = BN_set_word(bne,e);
76 ret = RSA_generate_key_ex(rsa, bits, bne, NULL);
82 fp = fopen(keyfilename, "w");
84 chmod(file_crpt_file_key, 0600);
85 if (PEM_write_RSAPrivateKey(fp, /* the file */
88 NULL, /* no passphr */
93 syslog(LOG_ERR, "crypto: cannot write key: %s", ERR_reason_error_string(ERR_get_error()));
107 * initialize ssl engine, load certs and initialize openssl internals
111 const SSL_METHOD *ssl_method;
113 X509_REQ *req = NULL;
116 EVP_PKEY *req_pkey = NULL;
117 X509_NAME *name = NULL;
122 #ifndef OPENSSL_NO_EGD
123 if (!access("/var/run/egd-pool", F_OK)) {
124 RAND_egd("/var/run/egd-pool");
128 if (!RAND_status()) {
129 syslog(LOG_WARNING, "PRNG not adequately seeded, won't do SSL/TLS\n");
132 SSLCritters = malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t *));
134 syslog(LOG_ERR, "citserver: can't allocate memory!!\n");
135 /* Nothing's been initialized, just die */
141 for (a = 0; a < CRYPTO_num_locks(); a++) {
142 SSLCritters[a] = malloc(sizeof(pthread_mutex_t));
143 if (!SSLCritters[a]) {
145 "citserver: can't allocate memory!!\n");
146 /** Nothing's been initialized, just die */
150 pthread_mutex_init(SSLCritters[a], NULL);
155 * Initialize SSL transport layer
158 SSL_load_error_strings();
159 ssl_method = SSLv23_server_method();
160 if (!(ssl_ctx = SSL_CTX_new(ssl_method))) {
161 syslog(LOG_WARNING, "SSL_CTX_new failed: %s\n", ERR_reason_error_string(ERR_get_error()));
165 syslog(LOG_INFO, "Requesting cipher list: %s\n", ssl_cipher_list);
166 if (!(SSL_CTX_set_cipher_list(ssl_ctx, ssl_cipher_list))) {
167 syslog(LOG_WARNING, "SSL_CTX_set_cipher_list failed: %s\n", ERR_reason_error_string(ERR_get_error()));
171 CRYPTO_set_locking_callback(ssl_lock);
172 CRYPTO_set_id_callback(id_callback);
175 * Get our certificates in order. (FIXME: dirify. this is a setup job.)
176 * First, create the key/cert directory if it's not there already...
178 mkdir(CTDL_CRYPTO_DIR, 0700);
181 * Before attempting to generate keys/certificates, first try
182 * link to them from the Citadel server if it's on the same host.
183 * We ignore any error return because it either meant that there
184 * was nothing in Citadel to link from (in which case we just
185 * generate new files) or the target files already exist (which
186 * is not fatal either).
188 if (!strcasecmp(ctdlhost, "uds")) {
189 sprintf(buf, "%s/keys/citadel.key", ctdlport);
190 rv = symlink(buf, CTDL_KEY_PATH);
191 if (!rv) syslog(LOG_DEBUG, "%s\n", strerror(errno));
192 sprintf(buf, "%s/keys/citadel.csr", ctdlport);
193 rv = symlink(buf, CTDL_CSR_PATH);
194 if (!rv) syslog(LOG_DEBUG, "%s\n", strerror(errno));
195 sprintf(buf, "%s/keys/citadel.cer", ctdlport);
196 rv = symlink(buf, CTDL_CER_PATH);
197 if (!rv) syslog(LOG_DEBUG, "%s\n", strerror(errno));
201 * If we still don't have a private key, generate one.
203 generate_key(CTDL_KEY_PATH);
206 * If there is no certificate file on disk, we will be generating a self-signed certificate
207 * in the next step. Therefore, if we have neither a CSR nor a certificate, generate
208 * the CSR in this step so that the next step may commence.
210 if ( (access(CTDL_CER_PATH, R_OK) != 0) && (access(CTDL_CSR_PATH, R_OK) != 0) ) {
211 syslog(LOG_INFO, "Generating a certificate signing request.\n");
214 * Read our key from the file. No, we don't just keep this
215 * in memory from the above key-generation function, because
216 * there is the possibility that the key was already on disk
217 * and we didn't just generate it now.
219 fp = fopen(CTDL_KEY_PATH, "r");
221 rsa = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
227 /** Create a public key from the private key */
228 if (pk=EVP_PKEY_new(), pk != NULL) {
229 EVP_PKEY_assign_RSA(pk, rsa);
230 if (req = X509_REQ_new(), req != NULL) {
232 /* Set the public key */
233 X509_REQ_set_pubkey(req, pk);
234 X509_REQ_set_version(req, 0L);
236 name = X509_REQ_get_subject_name(req);
238 /* Tell it who we are */
241 * We used to add these fields to the subject, but
242 * now we don't. Someone doing this for real isn't
243 * going to use the webcit-generated CSR anyway.
245 X509_NAME_add_entry_by_txt(name, "C",
246 MBSTRING_ASC, "US", -1, -1, 0);
248 X509_NAME_add_entry_by_txt(name, "ST",
249 MBSTRING_ASC, "New York", -1, -1, 0);
251 X509_NAME_add_entry_by_txt(name, "L",
252 MBSTRING_ASC, "Mount Kisco", -1, -1, 0);
257 env = "Organization name",
259 X509_NAME_add_entry_by_txt(
268 env = "Citadel server";
270 X509_NAME_add_entry_by_txt(
281 X509_NAME_add_entry_by_txt(
288 X509_REQ_set_subject_name(req, name);
291 if (!X509_REQ_sign(req, pk, EVP_md5())) {
292 syslog(LOG_WARNING, "X509_REQ_sign(): error\n");
295 /* Write it to disk. */
296 fp = fopen(CTDL_CSR_PATH, "w");
298 chmod(CTDL_CSR_PATH, 0600);
299 PEM_write_X509_REQ(fp, req);
303 syslog(LOG_WARNING, "Cannot write key: %s\n", CTDL_CSR_PATH);
317 syslog(LOG_WARNING, "Unable to read private key.\n");
324 * Generate a self-signed certificate if we don't have one.
326 if (access(CTDL_CER_PATH, R_OK) != 0) {
327 syslog(LOG_INFO, "Generating a self-signed certificate.\n");
329 /* Same deal as before: always read the key from disk because
330 * it may or may not have just been generated.
332 fp = fopen(CTDL_KEY_PATH, "r");
334 rsa = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
338 /* This also holds true for the CSR. */
343 if (pk=EVP_PKEY_new(), pk != NULL) {
344 EVP_PKEY_assign_RSA(pk, rsa);
347 fp = fopen(CTDL_CSR_PATH, "r");
349 req = PEM_read_X509_REQ(fp, NULL, NULL, NULL);
354 if (cer = X509_new(), cer != NULL) {
356 ASN1_INTEGER_set(X509_get_serialNumber(cer), 0);
357 X509_set_issuer_name(cer, X509_REQ_get_subject_name(req));
358 X509_set_subject_name(cer, X509_REQ_get_subject_name(req));
359 X509_gmtime_adj(X509_get_notBefore(cer), 0);
360 X509_gmtime_adj(X509_get_notAfter(cer),(long)60*60*24*SIGN_DAYS);
362 req_pkey = X509_REQ_get_pubkey(req);
363 X509_set_pubkey(cer, req_pkey);
364 EVP_PKEY_free(req_pkey);
367 if (!X509_sign(cer, pk, EVP_md5())) {
368 syslog(LOG_WARNING, "X509_sign(): error\n");
371 /* Write it to disk. */
372 fp = fopen(CTDL_CER_PATH, "w");
374 chmod(CTDL_CER_PATH, 0600);
375 PEM_write_X509(fp, cer);
379 syslog(LOG_WARNING, "Cannot write key: %s\n", CTDL_CER_PATH);
393 * Now try to bind to the key and certificate.
394 * Note that we use SSL_CTX_use_certificate_chain_file() which allows
395 * the certificate file to contain intermediate certificates.
397 SSL_CTX_use_certificate_chain_file(ssl_ctx, CTDL_CER_PATH);
398 SSL_CTX_use_PrivateKey_file(ssl_ctx, CTDL_KEY_PATH, SSL_FILETYPE_PEM);
399 if ( !SSL_CTX_check_private_key(ssl_ctx) ) {
400 syslog(LOG_WARNING, "Cannot install certificate: %s\n",
401 ERR_reason_error_string(ERR_get_error()));
408 * starts SSL/TLS encryption for the current session.
410 int starttls(int sock) {
411 int retval, bits, alg_bits;/*r; */
414 pthread_setspecific(ThreadSSL, NULL);
419 if (!(newssl = SSL_new(ssl_ctx))) {
420 syslog(LOG_WARNING, "SSL_new failed: %s\n", ERR_reason_error_string(ERR_get_error()));
423 if (!(SSL_set_fd(newssl, sock))) {
424 syslog(LOG_WARNING, "SSL_set_fd failed: %s\n", ERR_reason_error_string(ERR_get_error()));
428 retval = SSL_accept(newssl);
431 * Can't notify the client of an error here; they will
432 * discover the problem at the SSL layer and should
433 * revert to unencrypted communications.
436 const char *ssl_error_reason = NULL;
438 errval = SSL_get_error(newssl, retval);
439 ssl_error_reason = ERR_reason_error_string(ERR_get_error());
440 if (ssl_error_reason == NULL) {
441 syslog(LOG_WARNING, "SSL_accept failed: errval=%ld, retval=%d %s\n", errval, retval, strerror(errval));
444 syslog(LOG_WARNING, "SSL_accept failed: %s\n", ssl_error_reason);
447 retval = SSL_accept(newssl);
451 const char *ssl_error_reason = NULL;
453 errval = SSL_get_error(newssl, retval);
454 ssl_error_reason = ERR_reason_error_string(ERR_get_error());
455 if (ssl_error_reason == NULL) {
456 syslog(LOG_WARNING, "SSL_accept failed: errval=%ld, retval=%d (%s)\n", errval, retval, strerror(errval));
459 syslog(LOG_WARNING, "SSL_accept failed: %s\n", ssl_error_reason);
466 syslog(LOG_INFO, "SSL_accept success\n");
468 /*r = */BIO_set_close(SSL_get_rbio(newssl), BIO_NOCLOSE);
469 bits = SSL_CIPHER_get_bits(SSL_get_current_cipher(newssl), &alg_bits);
470 syslog(LOG_INFO, "SSL/TLS using %s on %s (%d of %d bits)\n",
471 SSL_CIPHER_get_name(SSL_get_current_cipher(newssl)),
472 SSL_CIPHER_get_version(SSL_get_current_cipher(newssl)),
475 pthread_setspecific(ThreadSSL, newssl);
476 syslog(LOG_INFO, "SSL started\n");
483 * shuts down the TLS connection
485 * WARNING: This may make your session vulnerable to a known plaintext
486 * attack in the current implmentation.
492 if (THREADSSL == NULL) return;
494 syslog(LOG_INFO, "Ending SSL/TLS\n");
495 SSL_shutdown(THREADSSL);
496 /*ctx = */SSL_get_SSL_CTX(THREADSSL);
498 /* I don't think this is needed, and it crashes the server anyway
501 * syslog(LOG_DEBUG, "Freeing CTX at %x\n", (int)ctx );
507 pthread_setspecific(ThreadSSL, NULL);
512 * callback for OpenSSL mutex locks
514 void ssl_lock(int mode, int n, const char *file, int line)
516 if (mode & CRYPTO_LOCK) {
517 pthread_mutex_lock(SSLCritters[n]);
520 pthread_mutex_unlock(SSLCritters[n]);
525 * Send binary data to the client encrypted.
527 int client_write_ssl(const StrBuf *Buf)
535 if (THREADSSL == NULL) return -1;
537 nbytes = nremain = StrLength(Buf);
540 while (nremain > 0) {
541 if (SSL_want_write(THREADSSL)) {
542 if ((SSL_read(THREADSSL, junk, 0)) < 1) {
543 syslog(LOG_WARNING, "SSL_read in client_write: %s\n",
544 ERR_reason_error_string(ERR_get_error()));
547 retval = SSL_write(THREADSSL, &buf[nbytes - nremain], nremain);
551 errval = SSL_get_error(THREADSSL, retval);
552 if (errval == SSL_ERROR_WANT_READ || errval == SSL_ERROR_WANT_WRITE) {
556 syslog(LOG_WARNING, "SSL_write got error %ld, ret %d\n", errval, retval);
558 syslog(LOG_WARNING, "errno is %d\n", errno);
570 * read data from the encrypted layer.
572 int client_read_sslbuffer(StrBuf *buf, int timeout)
574 char sbuf[16384]; /* OpenSSL communicates in 16k blocks, so let's speak its native tongue. */
577 SSL *pssl = THREADSSL;
579 if (pssl == NULL) return(-1);
582 if (SSL_want_read(pssl)) {
583 if ((SSL_write(pssl, junk, 0)) < 1) {
584 syslog(LOG_WARNING, "SSL_write in client_read\n");
587 rlen = SSL_read(pssl, sbuf, sizeof(sbuf));
591 errval = SSL_get_error(pssl, rlen);
592 if (errval == SSL_ERROR_WANT_READ || errval == SSL_ERROR_WANT_WRITE) {
596 syslog(LOG_WARNING, "SSL_read got error %ld\n", errval);
600 StrBufAppendBufPlain(buf, sbuf, rlen, 0);
606 #endif /* HAVE_OPENSSL */