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 char *ssl_cipher_list = DEFAULT_SSL_CIPHER_LIST;
29 pthread_key_t ThreadSSL; /* Per-thread SSL context */
31 void shutdown_ssl(void) {
36 void generate_key(char *keyfilename) {
41 unsigned long e = RSA_F4;
44 if (access(keyfilename, R_OK) == 0) {
48 syslog(LOG_INFO, "crypto: generating RSA key pair");
52 ret = BN_set_word(bne,e);
58 ret = RSA_generate_key_ex(rsa, bits, bne, NULL);
64 fp = fopen(keyfilename, "w");
66 chmod(file_crpt_file_key, 0600);
67 if (PEM_write_RSAPrivateKey(fp, /* the file */
70 NULL, /* no passphr */
75 syslog(LOG_ERR, "crypto: cannot write key: %s", ERR_reason_error_string(ERR_get_error()));
89 * initialize ssl engine, load certs and initialize openssl internals
93 const SSL_METHOD *ssl_method;
98 EVP_PKEY *req_pkey = NULL;
99 X509_NAME *name = NULL;
104 #ifndef OPENSSL_NO_EGD
105 if (!access("/var/run/egd-pool", F_OK)) {
106 RAND_egd("/var/run/egd-pool");
110 if (!RAND_status()) {
111 syslog(LOG_WARNING, "PRNG not adequately seeded, won't do SSL/TLS\n");
116 * Initialize SSL transport layer
119 SSL_load_error_strings();
120 ssl_method = SSLv23_server_method();
121 if (!(ssl_ctx = SSL_CTX_new(ssl_method))) {
122 syslog(LOG_WARNING, "SSL_CTX_new failed: %s\n", ERR_reason_error_string(ERR_get_error()));
126 syslog(LOG_INFO, "Requesting cipher list: %s\n", ssl_cipher_list);
127 if (!(SSL_CTX_set_cipher_list(ssl_ctx, ssl_cipher_list))) {
128 syslog(LOG_WARNING, "SSL_CTX_set_cipher_list failed: %s\n", ERR_reason_error_string(ERR_get_error()));
132 CRYPTO_set_locking_callback(ssl_lock);
133 CRYPTO_set_id_callback(id_callback);
136 * Get our certificates in order. (FIXME: dirify. this is a setup job.)
137 * First, create the key/cert directory if it's not there already...
139 mkdir(CTDL_CRYPTO_DIR, 0700);
142 * Before attempting to generate keys/certificates, first try
143 * link to them from the Citadel server if it's on the same host.
144 * We ignore any error return because it either meant that there
145 * was nothing in Citadel to link from (in which case we just
146 * generate new files) or the target files already exist (which
147 * is not fatal either).
149 if (!strcasecmp(ctdlhost, "uds")) {
150 sprintf(buf, "%s/keys/citadel.key", ctdlport);
151 rv = symlink(buf, CTDL_KEY_PATH);
152 if (!rv) syslog(LOG_DEBUG, "%s\n", strerror(errno));
153 sprintf(buf, "%s/keys/citadel.csr", ctdlport);
154 rv = symlink(buf, CTDL_CSR_PATH);
155 if (!rv) syslog(LOG_DEBUG, "%s\n", strerror(errno));
156 sprintf(buf, "%s/keys/citadel.cer", ctdlport);
157 rv = symlink(buf, CTDL_CER_PATH);
158 if (!rv) syslog(LOG_DEBUG, "%s\n", strerror(errno));
162 * If we still don't have a private key, generate one.
164 generate_key(CTDL_KEY_PATH);
167 * If there is no certificate file on disk, we will be generating a self-signed certificate
168 * in the next step. Therefore, if we have neither a CSR nor a certificate, generate
169 * the CSR in this step so that the next step may commence.
171 if ( (access(CTDL_CER_PATH, R_OK) != 0) && (access(CTDL_CSR_PATH, R_OK) != 0) ) {
172 syslog(LOG_INFO, "Generating a certificate signing request.\n");
175 * Read our key from the file. No, we don't just keep this
176 * in memory from the above key-generation function, because
177 * there is the possibility that the key was already on disk
178 * and we didn't just generate it now.
180 fp = fopen(CTDL_KEY_PATH, "r");
182 rsa = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
188 /** Create a public key from the private key */
189 if (pk=EVP_PKEY_new(), pk != NULL) {
190 EVP_PKEY_assign_RSA(pk, rsa);
191 if (req = X509_REQ_new(), req != NULL) {
193 /* Set the public key */
194 X509_REQ_set_pubkey(req, pk);
195 X509_REQ_set_version(req, 0L);
197 name = X509_REQ_get_subject_name(req);
199 /* Tell it who we are */
202 * We used to add these fields to the subject, but
203 * now we don't. Someone doing this for real isn't
204 * going to use the webcit-generated CSR anyway.
206 X509_NAME_add_entry_by_txt(name, "C",
207 MBSTRING_ASC, "US", -1, -1, 0);
209 X509_NAME_add_entry_by_txt(name, "ST",
210 MBSTRING_ASC, "New York", -1, -1, 0);
212 X509_NAME_add_entry_by_txt(name, "L",
213 MBSTRING_ASC, "Mount Kisco", -1, -1, 0);
218 env = "Organization name",
220 X509_NAME_add_entry_by_txt(
229 env = "Citadel server";
231 X509_NAME_add_entry_by_txt(
242 X509_NAME_add_entry_by_txt(
249 X509_REQ_set_subject_name(req, name);
252 if (!X509_REQ_sign(req, pk, EVP_md5())) {
253 syslog(LOG_WARNING, "X509_REQ_sign(): error\n");
256 /* Write it to disk. */
257 fp = fopen(CTDL_CSR_PATH, "w");
259 chmod(CTDL_CSR_PATH, 0600);
260 PEM_write_X509_REQ(fp, req);
264 syslog(LOG_WARNING, "Cannot write key: %s\n", CTDL_CSR_PATH);
278 syslog(LOG_WARNING, "Unable to read private key.\n");
285 * Generate a self-signed certificate if we don't have one.
287 if (access(CTDL_CER_PATH, R_OK) != 0) {
288 syslog(LOG_INFO, "Generating a self-signed certificate.\n");
290 /* Same deal as before: always read the key from disk because
291 * it may or may not have just been generated.
293 fp = fopen(CTDL_KEY_PATH, "r");
295 rsa = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
299 /* This also holds true for the CSR. */
304 if (pk=EVP_PKEY_new(), pk != NULL) {
305 EVP_PKEY_assign_RSA(pk, rsa);
308 fp = fopen(CTDL_CSR_PATH, "r");
310 req = PEM_read_X509_REQ(fp, NULL, NULL, NULL);
315 if (cer = X509_new(), cer != NULL) {
317 ASN1_INTEGER_set(X509_get_serialNumber(cer), 0);
318 X509_set_issuer_name(cer, X509_REQ_get_subject_name(req));
319 X509_set_subject_name(cer, X509_REQ_get_subject_name(req));
320 X509_gmtime_adj(X509_get_notBefore(cer), 0);
321 X509_gmtime_adj(X509_get_notAfter(cer),(long)60*60*24*SIGN_DAYS);
323 req_pkey = X509_REQ_get_pubkey(req);
324 X509_set_pubkey(cer, req_pkey);
325 EVP_PKEY_free(req_pkey);
328 if (!X509_sign(cer, pk, EVP_md5())) {
329 syslog(LOG_WARNING, "X509_sign(): error\n");
332 /* Write it to disk. */
333 fp = fopen(CTDL_CER_PATH, "w");
335 chmod(CTDL_CER_PATH, 0600);
336 PEM_write_X509(fp, cer);
340 syslog(LOG_WARNING, "Cannot write key: %s\n", CTDL_CER_PATH);
354 * Now try to bind to the key and certificate.
355 * Note that we use SSL_CTX_use_certificate_chain_file() which allows
356 * the certificate file to contain intermediate certificates.
358 SSL_CTX_use_certificate_chain_file(ssl_ctx, CTDL_CER_PATH);
359 SSL_CTX_use_PrivateKey_file(ssl_ctx, CTDL_KEY_PATH, SSL_FILETYPE_PEM);
360 if ( !SSL_CTX_check_private_key(ssl_ctx) ) {
361 syslog(LOG_WARNING, "crypto: cannot install certificate: %s\n", ERR_reason_error_string(ERR_get_error()));
367 * starts SSL/TLS encryption for the current session.
369 int starttls(int sock) {
370 int retval, bits, alg_bits;/*r; */
373 pthread_setspecific(ThreadSSL, NULL);
378 if (!(newssl = SSL_new(ssl_ctx))) {
379 syslog(LOG_WARNING, "SSL_new failed: %s\n", ERR_reason_error_string(ERR_get_error()));
382 if (!(SSL_set_fd(newssl, sock))) {
383 syslog(LOG_WARNING, "SSL_set_fd failed: %s\n", ERR_reason_error_string(ERR_get_error()));
387 retval = SSL_accept(newssl);
390 * Can't notify the client of an error here; they will
391 * discover the problem at the SSL layer and should
392 * revert to unencrypted communications.
395 const char *ssl_error_reason = NULL;
397 errval = SSL_get_error(newssl, retval);
398 ssl_error_reason = ERR_reason_error_string(ERR_get_error());
399 if (ssl_error_reason == NULL) {
400 syslog(LOG_WARNING, "SSL_accept failed: errval=%ld, retval=%d %s\n", errval, retval, strerror(errval));
403 syslog(LOG_WARNING, "SSL_accept failed: %s\n", ssl_error_reason);
406 retval = SSL_accept(newssl);
410 const char *ssl_error_reason = NULL;
412 errval = SSL_get_error(newssl, retval);
413 ssl_error_reason = ERR_reason_error_string(ERR_get_error());
414 if (ssl_error_reason == NULL) {
415 syslog(LOG_WARNING, "SSL_accept failed: errval=%ld, retval=%d (%s)\n", errval, retval, strerror(errval));
418 syslog(LOG_WARNING, "SSL_accept failed: %s\n", ssl_error_reason);
425 syslog(LOG_INFO, "SSL_accept success\n");
427 /*r = */BIO_set_close(SSL_get_rbio(newssl), BIO_NOCLOSE);
428 bits = SSL_CIPHER_get_bits(SSL_get_current_cipher(newssl), &alg_bits);
429 syslog(LOG_INFO, "SSL/TLS using %s on %s (%d of %d bits)\n",
430 SSL_CIPHER_get_name(SSL_get_current_cipher(newssl)),
431 SSL_CIPHER_get_version(SSL_get_current_cipher(newssl)),
434 pthread_setspecific(ThreadSSL, newssl);
435 syslog(LOG_INFO, "SSL started\n");
442 * shuts down the TLS connection
444 * WARNING: This may make your session vulnerable to a known plaintext
445 * attack in the current implmentation.
451 if (THREADSSL == NULL) return;
453 syslog(LOG_INFO, "Ending SSL/TLS\n");
454 SSL_shutdown(THREADSSL);
455 /*ctx = */SSL_get_SSL_CTX(THREADSSL);
457 /* I don't think this is needed, and it crashes the server anyway
460 * syslog(LOG_DEBUG, "Freeing CTX at %x\n", (int)ctx );
466 pthread_setspecific(ThreadSSL, NULL);
471 * Send binary data to the client encrypted.
473 int client_write_ssl(const StrBuf *Buf)
481 if (THREADSSL == NULL) return -1;
483 nbytes = nremain = StrLength(Buf);
486 while (nremain > 0) {
487 if (SSL_want_write(THREADSSL)) {
488 if ((SSL_read(THREADSSL, junk, 0)) < 1) {
489 syslog(LOG_WARNING, "SSL_read in client_write: %s\n",
490 ERR_reason_error_string(ERR_get_error()));
493 retval = SSL_write(THREADSSL, &buf[nbytes - nremain], nremain);
497 errval = SSL_get_error(THREADSSL, retval);
498 if (errval == SSL_ERROR_WANT_READ || errval == SSL_ERROR_WANT_WRITE) {
502 syslog(LOG_WARNING, "SSL_write got error %ld, ret %d\n", errval, retval);
504 syslog(LOG_WARNING, "errno is %d\n", errno);
516 * read data from the encrypted layer.
518 int client_read_sslbuffer(StrBuf *buf, int timeout)
520 char sbuf[16384]; /* OpenSSL communicates in 16k blocks, so let's speak its native tongue. */
523 SSL *pssl = THREADSSL;
525 if (pssl == NULL) return(-1);
528 if (SSL_want_read(pssl)) {
529 if ((SSL_write(pssl, junk, 0)) < 1) {
530 syslog(LOG_WARNING, "SSL_write in client_read\n");
533 rlen = SSL_read(pssl, sbuf, sizeof(sbuf));
537 errval = SSL_get_error(pssl, rlen);
538 if (errval == SSL_ERROR_WANT_READ || errval == SSL_ERROR_WANT_WRITE) {
542 syslog(LOG_WARNING, "SSL_read got error %ld\n", errval);
546 StrBufAppendBufPlain(buf, sbuf, rlen, 0);
552 #endif /* HAVE_OPENSSL */