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, "crypto: cannot install certificate: %s\n", ERR_reason_error_string(ERR_get_error()));
406 * starts SSL/TLS encryption for the current session.
408 int starttls(int sock) {
409 int retval, bits, alg_bits;/*r; */
412 pthread_setspecific(ThreadSSL, NULL);
417 if (!(newssl = SSL_new(ssl_ctx))) {
418 syslog(LOG_WARNING, "SSL_new failed: %s\n", ERR_reason_error_string(ERR_get_error()));
421 if (!(SSL_set_fd(newssl, sock))) {
422 syslog(LOG_WARNING, "SSL_set_fd failed: %s\n", ERR_reason_error_string(ERR_get_error()));
426 retval = SSL_accept(newssl);
429 * Can't notify the client of an error here; they will
430 * discover the problem at the SSL layer and should
431 * revert to unencrypted communications.
434 const char *ssl_error_reason = NULL;
436 errval = SSL_get_error(newssl, retval);
437 ssl_error_reason = ERR_reason_error_string(ERR_get_error());
438 if (ssl_error_reason == NULL) {
439 syslog(LOG_WARNING, "SSL_accept failed: errval=%ld, retval=%d %s\n", errval, retval, strerror(errval));
442 syslog(LOG_WARNING, "SSL_accept failed: %s\n", ssl_error_reason);
445 retval = SSL_accept(newssl);
449 const char *ssl_error_reason = NULL;
451 errval = SSL_get_error(newssl, retval);
452 ssl_error_reason = ERR_reason_error_string(ERR_get_error());
453 if (ssl_error_reason == NULL) {
454 syslog(LOG_WARNING, "SSL_accept failed: errval=%ld, retval=%d (%s)\n", errval, retval, strerror(errval));
457 syslog(LOG_WARNING, "SSL_accept failed: %s\n", ssl_error_reason);
464 syslog(LOG_INFO, "SSL_accept success\n");
466 /*r = */BIO_set_close(SSL_get_rbio(newssl), BIO_NOCLOSE);
467 bits = SSL_CIPHER_get_bits(SSL_get_current_cipher(newssl), &alg_bits);
468 syslog(LOG_INFO, "SSL/TLS using %s on %s (%d of %d bits)\n",
469 SSL_CIPHER_get_name(SSL_get_current_cipher(newssl)),
470 SSL_CIPHER_get_version(SSL_get_current_cipher(newssl)),
473 pthread_setspecific(ThreadSSL, newssl);
474 syslog(LOG_INFO, "SSL started\n");
481 * shuts down the TLS connection
483 * WARNING: This may make your session vulnerable to a known plaintext
484 * attack in the current implmentation.
490 if (THREADSSL == NULL) return;
492 syslog(LOG_INFO, "Ending SSL/TLS\n");
493 SSL_shutdown(THREADSSL);
494 /*ctx = */SSL_get_SSL_CTX(THREADSSL);
496 /* I don't think this is needed, and it crashes the server anyway
499 * syslog(LOG_DEBUG, "Freeing CTX at %x\n", (int)ctx );
505 pthread_setspecific(ThreadSSL, NULL);
510 * callback for OpenSSL mutex locks
512 void ssl_lock(int mode, int n, const char *file, int line)
514 if (mode & CRYPTO_LOCK) {
515 pthread_mutex_lock(SSLCritters[n]);
518 pthread_mutex_unlock(SSLCritters[n]);
523 * Send binary data to the client encrypted.
525 int client_write_ssl(const StrBuf *Buf)
533 if (THREADSSL == NULL) return -1;
535 nbytes = nremain = StrLength(Buf);
538 while (nremain > 0) {
539 if (SSL_want_write(THREADSSL)) {
540 if ((SSL_read(THREADSSL, junk, 0)) < 1) {
541 syslog(LOG_WARNING, "SSL_read in client_write: %s\n",
542 ERR_reason_error_string(ERR_get_error()));
545 retval = SSL_write(THREADSSL, &buf[nbytes - nremain], nremain);
549 errval = SSL_get_error(THREADSSL, retval);
550 if (errval == SSL_ERROR_WANT_READ || errval == SSL_ERROR_WANT_WRITE) {
554 syslog(LOG_WARNING, "SSL_write got error %ld, ret %d\n", errval, retval);
556 syslog(LOG_WARNING, "errno is %d\n", errno);
568 * read data from the encrypted layer.
570 int client_read_sslbuffer(StrBuf *buf, int timeout)
572 char sbuf[16384]; /* OpenSSL communicates in 16k blocks, so let's speak its native tongue. */
575 SSL *pssl = THREADSSL;
577 if (pssl == NULL) return(-1);
580 if (SSL_want_read(pssl)) {
581 if ((SSL_write(pssl, junk, 0)) < 1) {
582 syslog(LOG_WARNING, "SSL_write in client_read\n");
585 rlen = SSL_read(pssl, sbuf, sizeof(sbuf));
589 errval = SSL_get_error(pssl, rlen);
590 if (errval == SSL_ERROR_WANT_READ || errval == SSL_ERROR_WANT_WRITE) {
594 syslog(LOG_WARNING, "SSL_read got error %ld\n", errval);
598 StrBufAppendBufPlain(buf, sbuf, rlen, 0);
604 #endif /* HAVE_OPENSSL */