1 // Copyright (c) 1996-2021 by the citadel.org team
3 // This program is open source software. You can redistribute it and/or
4 // modify it under the terms of the GNU General Public License, version 3.
6 // This program is distributed in the hope that it will be useful,
7 // but WITHOUT ANY WARRANTY; without even the implied warranty of
8 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
9 // GNU General Public License for more details.
15 #include "webserver.h"
17 /* where to find the keys */
18 #define CTDL_CRYPTO_DIR ctdl_key_dir
19 #define CTDL_KEY_PATH file_crpt_file_key
20 #define CTDL_CSR_PATH file_crpt_file_csr
21 #define CTDL_CER_PATH file_crpt_file_cer
22 #define SIGN_DAYS 3650 // how long our self-signed certificate should live
24 SSL_CTX *ssl_ctx; // Global SSL context
25 char *ssl_cipher_list = DEFAULT_SSL_CIPHER_LIST;
27 pthread_key_t ThreadSSL; // Per-thread SSL context
29 void shutdown_ssl(void) {
34 void generate_key(char *keyfilename) {
39 unsigned long e = RSA_F4;
42 if (access(keyfilename, R_OK) == 0) { // We already have a key -- don't generate a new one.
46 syslog(LOG_INFO, "crypto: generating RSA key pair");
50 ret = BN_set_word(bne,e);
56 ret = RSA_generate_key_ex(rsa, bits, bne, NULL);
62 fp = fopen(keyfilename, "w");
64 chmod(file_crpt_file_key, 0600);
65 if (PEM_write_RSAPrivateKey(fp, // the file
68 NULL, // no passphrase
73 syslog(LOG_ERR, "crypto: cannot write key: %s", ERR_reason_error_string(ERR_get_error()));
79 // Free the memory we used
86 // initialize ssl engine, load certs and initialize openssl internals
88 const SSL_METHOD *ssl_method;
93 EVP_PKEY *req_pkey = NULL;
94 X509_NAME *name = NULL;
99 #ifndef OPENSSL_NO_EGD
100 if (!access("/var/run/egd-pool", F_OK)) {
101 RAND_egd("/var/run/egd-pool");
105 if (!RAND_status()) {
106 syslog(LOG_WARNING, "PRNG not adequately seeded, won't do SSL/TLS");
110 // Initialize SSL transport layer
112 SSL_load_error_strings();
113 ssl_method = SSLv23_server_method();
114 if (!(ssl_ctx = SSL_CTX_new(ssl_method))) {
115 syslog(LOG_WARNING, "SSL_CTX_new failed: %s", ERR_reason_error_string(ERR_get_error()));
119 syslog(LOG_INFO, "Requesting cipher list: %s", ssl_cipher_list);
120 if (!(SSL_CTX_set_cipher_list(ssl_ctx, ssl_cipher_list))) {
121 syslog(LOG_WARNING, "SSL_CTX_set_cipher_list failed: %s", ERR_reason_error_string(ERR_get_error()));
125 CRYPTO_set_locking_callback(ssl_lock);
126 CRYPTO_set_id_callback(id_callback);
128 // Get our certificates in order.
129 // First, create the key/cert directory if it's not there already...
130 mkdir(CTDL_CRYPTO_DIR, 0700);
132 // Before attempting to generate keys/certificates, first try
133 // link to them from the Citadel server if it's on the same host.
134 // We ignore any error return because it either meant that there
135 // was nothing in Citadel to link from (in which case we just
136 // generate new files) or the target files already exist (which
137 // is not fatal either).
138 if (!strcasecmp(ctdlhost, "uds")) {
139 sprintf(buf, "%s/keys/citadel.key", ctdlport);
140 rv = symlink(buf, CTDL_KEY_PATH);
142 syslog(LOG_DEBUG, "%s", strerror(errno));
144 sprintf(buf, "%s/keys/citadel.csr", ctdlport);
145 rv = symlink(buf, CTDL_CSR_PATH);
147 syslog(LOG_DEBUG, "%s", strerror(errno));
149 sprintf(buf, "%s/keys/citadel.cer", ctdlport);
150 rv = symlink(buf, CTDL_CER_PATH);
152 syslog(LOG_DEBUG, "%s", strerror(errno));
156 // If we still don't have a private key, generate one.
157 generate_key(CTDL_KEY_PATH);
159 // If there is no certificate file on disk, we will be generating a self-signed certificate
160 // in the next step. Therefore, if we have neither a CSR nor a certificate, generate
161 // the CSR in this step so that the next step may commence.
162 if ( (access(CTDL_CER_PATH, R_OK) != 0) && (access(CTDL_CSR_PATH, R_OK) != 0) ) {
163 syslog(LOG_INFO, "Generating a certificate signing request.");
165 // Read our key from the file. No, we don't just keep this
166 // in memory from the above key-generation function, because
167 // there is the possibility that the key was already on disk
168 // and we didn't just generate it now.
169 fp = fopen(CTDL_KEY_PATH, "r");
171 rsa = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
176 // Create a public key from the private key
177 if (pk=EVP_PKEY_new(), pk != NULL) {
178 EVP_PKEY_assign_RSA(pk, rsa);
179 if (req = X509_REQ_new(), req != NULL) {
181 // Set the public key
182 X509_REQ_set_pubkey(req, pk);
183 X509_REQ_set_version(req, 0L);
185 name = X509_REQ_get_subject_name(req);
187 // Tell it who we are
190 env = "Organization name";
193 X509_NAME_add_entry_by_txt(
202 env = "Citadel server";
205 X509_NAME_add_entry_by_txt(
216 X509_NAME_add_entry_by_txt(
223 X509_REQ_set_subject_name(req, name);
226 if (!X509_REQ_sign(req, pk, EVP_md5())) {
227 syslog(LOG_WARNING, "X509_REQ_sign(): error");
231 fp = fopen(CTDL_CSR_PATH, "w");
233 chmod(CTDL_CSR_PATH, 0600);
234 PEM_write_X509_REQ(fp, req);
238 syslog(LOG_WARNING, "Cannot write key: %s", CTDL_CSR_PATH);
250 syslog(LOG_WARNING, "Unable to read private key.");
254 // Generate a self-signed certificate if we don't have one.
255 if (access(CTDL_CER_PATH, R_OK) != 0) {
256 syslog(LOG_INFO, "Generating a self-signed certificate.\n");
258 // Same deal as before: always read the key from disk because
259 // it may or may not have just been generated.
260 fp = fopen(CTDL_KEY_PATH, "r");
262 rsa = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
266 // This also holds true for the CSR.
271 if (pk=EVP_PKEY_new(), pk != NULL) {
272 EVP_PKEY_assign_RSA(pk, rsa);
275 fp = fopen(CTDL_CSR_PATH, "r");
277 req = PEM_read_X509_REQ(fp, NULL, NULL, NULL);
282 if (cer = X509_new(), cer != NULL) {
284 ASN1_INTEGER_set(X509_get_serialNumber(cer), 0);
285 X509_set_issuer_name(cer, X509_REQ_get_subject_name(req));
286 X509_set_subject_name(cer, X509_REQ_get_subject_name(req));
287 X509_gmtime_adj(X509_get_notBefore(cer), 0);
288 X509_gmtime_adj(X509_get_notAfter(cer),(long)60*60*24*SIGN_DAYS);
290 req_pkey = X509_REQ_get_pubkey(req);
291 X509_set_pubkey(cer, req_pkey);
292 EVP_PKEY_free(req_pkey);
295 if (!X509_sign(cer, pk, EVP_md5())) {
296 syslog(LOG_WARNING, "X509_sign(): error");
300 fp = fopen(CTDL_CER_PATH, "w");
302 chmod(CTDL_CER_PATH, 0600);
303 PEM_write_X509(fp, cer);
307 syslog(LOG_WARNING, "Cannot write key: %s", CTDL_CER_PATH);
319 // Now try to bind to the key and certificate.
320 // Note that we use SSL_CTX_use_certificate_chain_file() which allows
321 // the certificate file to contain intermediate certificates.
322 SSL_CTX_use_certificate_chain_file(ssl_ctx, CTDL_CER_PATH);
323 SSL_CTX_use_PrivateKey_file(ssl_ctx, CTDL_KEY_PATH, SSL_FILETYPE_PEM);
324 if ( !SSL_CTX_check_private_key(ssl_ctx) ) {
325 syslog(LOG_WARNING, "crypto: cannot install certificate: %s", ERR_reason_error_string(ERR_get_error()));
330 // starts SSL/TLS encryption for the current session.
331 int starttls(int sock) {
332 int retval, bits, alg_bits;
335 pthread_setspecific(ThreadSSL, NULL);
340 if (!(newssl = SSL_new(ssl_ctx))) {
341 syslog(LOG_WARNING, "SSL_new failed: %s", ERR_reason_error_string(ERR_get_error()));
344 if (!(SSL_set_fd(newssl, sock))) {
345 syslog(LOG_WARNING, "SSL_set_fd failed: %s", ERR_reason_error_string(ERR_get_error()));
349 retval = SSL_accept(newssl);
351 // Can't notify the client of an error here; they will
352 // discover the problem at the SSL layer and should
353 // revert to unencrypted communications.
355 const char *ssl_error_reason = NULL;
357 errval = SSL_get_error(newssl, retval);
358 ssl_error_reason = ERR_reason_error_string(ERR_get_error());
359 if (ssl_error_reason == NULL) {
360 syslog(LOG_WARNING, "SSL_accept failed: errval=%ld, retval=%d %s", errval, retval, strerror(errval));
363 syslog(LOG_WARNING, "SSL_accept failed: %s", ssl_error_reason);
366 retval = SSL_accept(newssl);
370 const char *ssl_error_reason = NULL;
372 errval = SSL_get_error(newssl, retval);
373 ssl_error_reason = ERR_reason_error_string(ERR_get_error());
374 if (ssl_error_reason == NULL) {
375 syslog(LOG_WARNING, "SSL_accept failed: errval=%ld, retval=%d (%s)", errval, retval, strerror(errval));
378 syslog(LOG_WARNING, "SSL_accept failed: %s", ssl_error_reason);
385 syslog(LOG_INFO, "SSL_accept success");
387 /*r = */BIO_set_close(SSL_get_rbio(newssl), BIO_NOCLOSE);
388 bits = SSL_CIPHER_get_bits(SSL_get_current_cipher(newssl), &alg_bits);
389 syslog(LOG_INFO, "SSL/TLS using %s on %s (%d of %d bits)",
390 SSL_CIPHER_get_name(SSL_get_current_cipher(newssl)),
391 SSL_CIPHER_get_version(SSL_get_current_cipher(newssl)),
394 pthread_setspecific(ThreadSSL, newssl);
395 syslog(LOG_INFO, "SSL started");
400 // shuts down the TLS connection
402 // WARNING: This may make your session vulnerable to a known plaintext
403 // attack in the current implmentation.
406 if (THREADSSL == NULL) {
410 syslog(LOG_INFO, "Ending SSL/TLS");
411 SSL_shutdown(THREADSSL);
412 SSL_get_SSL_CTX(THREADSSL);
414 pthread_setspecific(ThreadSSL, NULL);
418 // Send binary data to the client encrypted.
419 int client_write_ssl(const StrBuf *Buf) {
426 if (THREADSSL == NULL) return -1;
428 nbytes = nremain = StrLength(Buf);
431 while (nremain > 0) {
432 if (SSL_want_write(THREADSSL)) {
433 if ((SSL_read(THREADSSL, junk, 0)) < 1) {
434 syslog(LOG_WARNING, "SSL_read in client_write: %s", ERR_reason_error_string(ERR_get_error()));
437 retval = SSL_write(THREADSSL, &buf[nbytes - nremain], nremain);
441 errval = SSL_get_error(THREADSSL, retval);
442 if (errval == SSL_ERROR_WANT_READ || errval == SSL_ERROR_WANT_WRITE) {
446 syslog(LOG_WARNING, "SSL_write got error %ld, ret %d", errval, retval);
448 syslog(LOG_WARNING, "errno is %d\n", errno);
459 // read data from the encrypted layer.
460 int client_read_sslbuffer(StrBuf *buf, int timeout) {
461 char sbuf[16384]; // OpenSSL communicates in 16k blocks, so let's speak its native tongue.
464 SSL *pssl = THREADSSL;
466 if (pssl == NULL) return(-1);
469 if (SSL_want_read(pssl)) {
470 if ((SSL_write(pssl, junk, 0)) < 1) {
471 syslog(LOG_WARNING, "SSL_write in client_read");
474 rlen = SSL_read(pssl, sbuf, sizeof(sbuf));
478 errval = SSL_get_error(pssl, rlen);
479 if (errval == SSL_ERROR_WANT_READ || errval == SSL_ERROR_WANT_WRITE) {
483 syslog(LOG_WARNING, "SSL_read got error %ld", errval);
487 StrBufAppendBufPlain(buf, sbuf, rlen, 0);
493 #endif /* HAVE_OPENSSL */