2 * Copyright (c) 1987-2017 by the citadel.org team
4 * This program is open source software; you can redistribute it and/or modify
5 * 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.
16 #include <sys/types.h>
20 #include <openssl/ssl.h>
21 #include <openssl/err.h>
22 #include <openssl/rand.h>
25 #if TIME_WITH_SYS_TIME
26 # include <sys/time.h>
30 # include <sys/time.h>
40 #ifdef HAVE_SYS_SELECT_H
41 #include <sys/select.h>
45 #include <libcitadel.h>
47 #include "serv_crypto.h"
48 #include "sysdep_decls.h"
53 #include "ctdl_module.h"
56 SSL_CTX *ssl_ctx; /* SSL context */
57 pthread_mutex_t **SSLCritters; /* Things needing locking */
59 static unsigned long id_callback(void)
61 return (unsigned long) pthread_self();
64 void destruct_ssl(void)
67 for (a = 0; a < CRYPTO_num_locks(); a++)
74 const SSL_METHOD *ssl_method;
79 EVP_PKEY *req_pkey = NULL;
80 X509_NAME *name = NULL;
83 if (!access(EGD_POOL, F_OK))
87 syslog(LOG_ERR, "PRNG not adequately seeded, won't do SSL/TLS");
90 SSLCritters = malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t *));
92 syslog(LOG_ERR, "citserver: can't allocate memory!!");
93 /* Nothing's been initialized, just die */
98 for (a = 0; a < CRYPTO_num_locks(); a++) {
99 SSLCritters[a] = malloc(sizeof(pthread_mutex_t));
100 if (!SSLCritters[a]) {
101 syslog(LOG_EMERG, "citserver: can't allocate memory!!");
102 /* Nothing's been initialized, just die */
105 pthread_mutex_init(SSLCritters[a], NULL);
110 * Initialize SSL transport layer
113 SSL_load_error_strings();
114 ssl_method = SSLv23_server_method();
115 if (!(ssl_ctx = SSL_CTX_new(ssl_method))) {
116 syslog(LOG_ERR, "SSL_CTX_new failed: %s", ERR_reason_error_string(ERR_get_error()));
119 if (!(SSL_CTX_set_cipher_list(ssl_ctx, CIT_CIPHERS))) {
120 syslog(LOG_ERR, "SSL: No ciphers available");
121 SSL_CTX_free(ssl_ctx);
126 CRYPTO_set_locking_callback(ssl_lock);
127 CRYPTO_set_id_callback(id_callback);
129 /* Get our certificates in order.
130 * First, create the key/cert directory if it's not there already...
132 mkdir(ctdl_key_dir, 0700);
135 * Generate a key pair if we don't have one.
137 if (access(file_crpt_file_key, R_OK) != 0) {
138 syslog(LOG_INFO, "Generating RSA key pair.");
139 rsa = RSA_generate_key(1024, /* modulus size */
140 65537, /* exponent */
141 NULL, /* no callback */
142 NULL); /* no callback */
144 syslog(LOG_ERR, "Key generation failed: %s", ERR_reason_error_string(ERR_get_error()));
147 fp = fopen(file_crpt_file_key, "w");
149 chmod(file_crpt_file_key, 0600);
150 if (PEM_write_RSAPrivateKey(fp, /* the file */
153 NULL, /* no passphr */
155 NULL, /* no callbk */
158 syslog(LOG_ERR, "Cannot write key: %s", ERR_reason_error_string(ERR_get_error()));
159 unlink(file_crpt_file_key);
168 * If there is no certificate file on disk, we will be generating a self-signed certificate
169 * in the next step. Therefore, if we have neither a CSR nor a certificate, generate
170 * the CSR in this step so that the next step may commence.
172 if ( (access(file_crpt_file_cer, R_OK) != 0) && (access(file_crpt_file_csr, R_OK) != 0) ) {
173 syslog(LOG_INFO, "Generating a generic certificate signing request.");
176 * Read our key from the file. No, we don't just keep this
177 * in memory from the above key-generation function, because
178 * there is the possibility that the key was already on disk
179 * and we didn't just generate it now.
181 fp = fopen(file_crpt_file_key, "r");
183 rsa = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
189 /* Create a public key from the private key */
190 if (pk=EVP_PKEY_new(), pk != NULL) {
191 EVP_PKEY_assign_RSA(pk, rsa);
192 if (req = X509_REQ_new(), req != NULL) {
194 /* Set the public key */
195 X509_REQ_set_pubkey(req, pk);
196 X509_REQ_set_version(req, 0L);
198 name = X509_REQ_get_subject_name(req);
200 /* Tell it who we are */
201 X509_NAME_add_entry_by_txt(name, "C", MBSTRING_ASC, (unsigned const char *)"ZZ", -1, -1, 0);
202 X509_NAME_add_entry_by_txt(name, "ST", MBSTRING_ASC, (unsigned const char *)"The World", -1, -1, 0);
203 X509_NAME_add_entry_by_txt(name, "L", MBSTRING_ASC, (unsigned const char *)"My Location", -1, -1, 0);
204 X509_NAME_add_entry_by_txt(name, "O", MBSTRING_ASC, (unsigned const char *)"Generic certificate", -1, -1, 0);
205 X509_NAME_add_entry_by_txt(name, "OU", MBSTRING_ASC, (unsigned const char *)"Citadel server", -1, -1, 0);
206 X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC, (unsigned const char *)"*", -1, -1, 0);
207 X509_REQ_set_subject_name(req, name);
210 if (!X509_REQ_sign(req, pk, EVP_md5())) {
211 syslog(LOG_ERR, "X509_REQ_sign(): error");
214 /* Write it to disk. */
215 fp = fopen(file_crpt_file_csr, "w");
217 chmod(file_crpt_file_csr, 0600);
218 PEM_write_X509_REQ(fp, req);
231 syslog(LOG_ERR, "Unable to read private key.");
237 * Generate a self-signed certificate if we don't have one.
239 if (access(file_crpt_file_cer, R_OK) != 0) {
240 syslog(LOG_INFO, "Generating a generic self-signed certificate.");
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(file_crpt_file_key, "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(file_crpt_file_csr, "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);
274 req_pkey = X509_REQ_get_pubkey(req);
275 X509_set_pubkey(cer, req_pkey);
276 EVP_PKEY_free(req_pkey);
279 if (!X509_sign(cer, pk, EVP_md5())) {
280 syslog(LOG_ERR, "X509_sign(): error");
283 /* Write it to disk. */
284 fp = fopen(file_crpt_file_cer, "w");
286 chmod(file_crpt_file_cer, 0600);
287 PEM_write_X509(fp, cer);
301 * Now try to bind to the key and certificate.
303 SSL_CTX_use_certificate_chain_file(ssl_ctx, file_crpt_file_cer);
304 SSL_CTX_use_PrivateKey_file(ssl_ctx, file_crpt_file_key, SSL_FILETYPE_PEM);
305 if ( !SSL_CTX_check_private_key(ssl_ctx) ) {
306 syslog(LOG_ERR, "Cannot install certificate: %s", ERR_reason_error_string(ERR_get_error()));
309 /* Finally let the server know we're here */
310 CtdlRegisterProtoHook(cmd_stls, "STLS", "Start SSL/TLS session");
311 CtdlRegisterProtoHook(cmd_gtls, "GTLS", "Get SSL/TLS session status");
312 CtdlRegisterSessionHook(endtls, EVT_STOP, PRIO_STOP + 10);
317 * client_write_ssl() Send binary data to the client encrypted.
319 void client_write_ssl(const char *buf, int nbytes)
327 while (nremain > 0) {
328 if (SSL_want_write(CC->ssl)) {
329 if ((SSL_read(CC->ssl, junk, 0)) < 1) {
330 syslog(LOG_DEBUG, "SSL_read in client_write: %s", ERR_reason_error_string(ERR_get_error()));
334 SSL_write(CC->ssl, &buf[nbytes - nremain], nremain);
338 errval = SSL_get_error(CC->ssl, retval);
339 if (errval == SSL_ERROR_WANT_READ ||
340 errval == SSL_ERROR_WANT_WRITE) {
344 syslog(LOG_DEBUG, "SSL_write got error %ld, ret %d", errval, retval);
346 syslog(LOG_DEBUG, "errno is %d", errno);
348 client_write(&buf[nbytes - nremain], nremain);
357 * read data from the encrypted layer.
359 int client_read_sslbuffer(StrBuf *buf, int timeout)
361 char sbuf[16384]; /* OpenSSL communicates in 16k blocks, so let's speak its native tongue. */
366 if (pssl == NULL) return(-1);
369 if (SSL_want_read(pssl)) {
370 if ((SSL_write(pssl, junk, 0)) < 1) {
371 syslog(LOG_DEBUG, "SSL_write in client_read");
374 rlen = SSL_read(pssl, sbuf, sizeof(sbuf));
378 errval = SSL_get_error(pssl, rlen);
379 if (errval == SSL_ERROR_WANT_READ || errval == SSL_ERROR_WANT_WRITE) {
383 syslog(LOG_DEBUG, "SSL_read got error %ld", errval);
387 StrBufAppendBufPlain(buf, sbuf, rlen, 0);
393 int client_readline_sslbuffer(StrBuf *Line, StrBuf *IOBuf, const char **Pos, int timeout)
395 CitContext *CCC = CC;
396 const char *pos = NULL;
399 int nSuccessLess = 0;
400 const char *pch = NULL;
402 if ((Line == NULL) || (Pos == NULL) || (IOBuf == NULL))
412 if ((StrLength(IOBuf) > 0) && (pos != NULL) && (pos < ChrPtr(IOBuf) + StrLength(IOBuf)))
415 pch = strchr(pch, '\n');
418 StrBufAppendBufPlain(Line, pos, StrLength(IOBuf) - (pos - ChrPtr(IOBuf)), 0);
424 if ((pch > ChrPtr(IOBuf)) &&
425 (*(pch - 1) == '\r')) {
428 StrBufAppendBufPlain(Line, pos,
431 if (StrLength(IOBuf) <= (pch - ChrPtr(IOBuf) + 1)) {
437 return StrLength(Line);
442 while ((nSuccessLess < timeout) &&
444 (CCC->ssl != NULL)) {
446 rlen = client_read_sslbuffer(IOBuf, timeout);
451 pLF = strchr(ChrPtr(IOBuf), '\n');
458 if (len > 0 && (*(pLF - 1) == '\r') )
460 StrBufAppendBufPlain(Line, pos, len, 0);
461 if (pLF + 1 >= ChrPtr(IOBuf) + StrLength(IOBuf))
467 return StrLength(Line);
473 int client_read_sslblob(StrBuf *Target, long bytes, int timeout)
478 CitContext *CCC = CC;
480 baselen = StrLength(Target);
482 if (StrLength(CCC->RecvBuf.Buf) > 0)
488 if (CCC->RecvBuf.ReadWritePointer == NULL)
490 CCC->RecvBuf.ReadWritePointer = ChrPtr(CCC->RecvBuf.Buf);
492 pchs = ChrPtr(CCC->RecvBuf.Buf);
493 TotalLen = StrLength(CCC->RecvBuf.Buf);
494 RemainLen = TotalLen - (pchs - CCC->RecvBuf.ReadWritePointer);
495 if (RemainLen > bytes)
501 StrBufAppendBufPlain(Target, CCC->RecvBuf.ReadWritePointer, RemainLen, 0);
502 CCC->RecvBuf.ReadWritePointer += RemainLen;
504 if ((ChrPtr(CCC->RecvBuf.Buf) + StrLength(CCC->RecvBuf.Buf)) <= CCC->RecvBuf.ReadWritePointer)
506 CCC->RecvBuf.ReadWritePointer = NULL;
507 FlushStrBuf(CCC->RecvBuf.Buf);
511 if (StrLength(Target) >= bytes + baselen)
516 CCC->RecvBuf.ReadWritePointer = NULL;
518 while ((StrLength(Target) < bytes + baselen) && (retval >= 0))
520 retval = client_read_sslbuffer(CCC->RecvBuf.Buf, timeout);
522 RemainRead = bytes - (StrLength (Target) - baselen);
523 if (RemainRead < StrLength(CCC->RecvBuf.Buf))
525 StrBufAppendBufPlain(
527 ChrPtr(CCC->RecvBuf.Buf),
529 CCC->RecvBuf.ReadWritePointer = ChrPtr(CCC->RecvBuf.Buf) + RemainRead;
532 StrBufAppendBuf(Target, CCC->RecvBuf.Buf, 0); /* todo: Buf > bytes? */
533 FlushStrBuf(CCC->RecvBuf.Buf);
537 FlushStrBuf(CCC->RecvBuf.Buf);
547 * CtdlStartTLS() starts SSL/TLS encryption for the current session. It
548 * must be supplied with pre-generated strings for responses of "ok," "no
549 * support for TLS," and "error" so that we can use this in any protocol.
551 void CtdlStartTLS(char *ok_response, char *nosup_response, char *error_response)
553 int retval, bits, alg_bits;
556 syslog(LOG_ERR, "SSL failed: no ssl_ctx exists?");
557 if (nosup_response != NULL) cprintf("%s", nosup_response);
560 if (!(CC->ssl = SSL_new(ssl_ctx))) {
561 syslog(LOG_ERR, "SSL_new failed: %s",
562 ERR_reason_error_string(ERR_get_error()));
563 if (error_response != NULL) cprintf("%s", error_response);
566 if (!(SSL_set_fd(CC->ssl, CC->client_socket))) {
567 syslog(LOG_ERR, "SSL_set_fd failed: %s", ERR_reason_error_string(ERR_get_error()));
570 if (error_response != NULL) cprintf("%s", error_response);
573 if (ok_response != NULL) cprintf("%s", ok_response);
574 retval = SSL_accept(CC->ssl);
577 * Can't notify the client of an error here; they will
578 * discover the problem at the SSL layer and should
579 * revert to unencrypted communications.
582 char error_string[128];
584 errval = SSL_get_error(CC->ssl, retval);
585 syslog(LOG_ERR, "SSL_accept failed: retval=%d, errval=%ld, err=%s",
588 ERR_error_string(errval, error_string)
594 BIO_set_close(CC->ssl->rbio, BIO_NOCLOSE);
595 bits = SSL_CIPHER_get_bits(SSL_get_current_cipher(CC->ssl), &alg_bits);
596 syslog(LOG_INFO, "SSL/TLS using %s on %s (%d of %d bits)",
597 SSL_CIPHER_get_name(SSL_get_current_cipher(CC->ssl)),
598 SSL_CIPHER_get_version(SSL_get_current_cipher(CC->ssl)),
600 CC->redirect_ssl = 1;
605 * cmd_stls() starts SSL/TLS encryption for the current session
607 void cmd_stls(char *params)
609 char ok_response[SIZ];
610 char nosup_response[SIZ];
611 char error_response[SIZ];
615 sprintf(ok_response, "%d Begin TLS negotiation now\n", CIT_OK);
616 sprintf(nosup_response, "%d TLS not supported here\n", ERROR + CMD_NOT_SUPPORTED);
617 sprintf(error_response, "%d TLS negotiation error\n", ERROR + INTERNAL_ERROR);
619 CtdlStartTLS(ok_response, nosup_response, error_response);
624 * cmd_gtls() returns status info about the TLS connection
626 void cmd_gtls(char *params)
630 if (!CC->ssl || !CC->redirect_ssl) {
631 cprintf("%d Session is not encrypted.\n", ERROR);
635 SSL_CIPHER_get_bits(SSL_get_current_cipher(CC->ssl),
637 cprintf("%d %s|%s|%d|%d\n", CIT_OK,
638 SSL_CIPHER_get_version(SSL_get_current_cipher(CC->ssl)),
639 SSL_CIPHER_get_name(SSL_get_current_cipher(CC->ssl)),
645 * endtls() shuts down the TLS connection
647 * WARNING: This may make your session vulnerable to a known plaintext
648 * attack in the current implmentation.
653 CC->redirect_ssl = 0;
657 syslog(LOG_INFO, "Ending SSL/TLS");
658 SSL_shutdown(CC->ssl);
661 CC->redirect_ssl = 0;
666 * ssl_lock() callback for OpenSSL mutex locks
668 void ssl_lock(int mode, int n, const char *file, int line)
670 if (mode & CRYPTO_LOCK)
672 pthread_mutex_lock(SSLCritters[n]);
675 pthread_mutex_unlock(SSLCritters[n]);
678 #endif /* HAVE_OPENSSL */