2 * Copyright (c) 1987-2018 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>
31 #ifdef HAVE_SYS_SELECT_H
32 #include <sys/select.h>
36 #include <libcitadel.h>
38 #include "serv_crypto.h"
39 #include "sysdep_decls.h"
44 #include "ctdl_module.h"
47 SSL_CTX *ssl_ctx; /* SSL context */
48 pthread_mutex_t **SSLCritters; /* Things needing locking */
50 static unsigned long id_callback(void)
52 return (unsigned long) pthread_self();
55 void destruct_ssl(void)
58 for (a = 0; a < CRYPTO_num_locks(); a++)
64 void generate_key(char *keyfilename)
70 unsigned long e = RSA_F4;
73 if (access(keyfilename, R_OK) == 0) {
77 syslog(LOG_INFO, "crypto: generating RSA key pair");
81 ret = BN_set_word(bne,e);
87 ret = RSA_generate_key_ex(rsa, bits, bne, NULL);
93 fp = fopen(keyfilename, "w");
95 chmod(keyfilename, 0600);
96 if (PEM_write_RSAPrivateKey(fp, /* the file */
99 NULL, /* no passphr */
101 NULL, /* no callbk */
104 syslog(LOG_ERR, "crypto: cannot write key: %s", ERR_reason_error_string(ERR_get_error()));
119 const SSL_METHOD *ssl_method;
121 X509_REQ *req = NULL;
124 EVP_PKEY *req_pkey = NULL;
125 X509_NAME *name = NULL;
128 SSLCritters = malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t *));
130 syslog(LOG_ERR, "crypto: can't allocate memory!");
131 exit(CTDLEXIT_CRYPTO);
135 for (a = 0; a < CRYPTO_num_locks(); a++) {
136 SSLCritters[a] = malloc(sizeof(pthread_mutex_t));
137 if (!SSLCritters[a]) {
138 syslog(LOG_ERR, "crypto: can't allocate memory!!");
139 exit(CTDLEXIT_CRYPTO);
141 pthread_mutex_init(SSLCritters[a], NULL);
146 * Initialize SSL transport layer
149 SSL_load_error_strings();
150 ssl_method = SSLv23_server_method();
151 if (!(ssl_ctx = SSL_CTX_new(ssl_method))) {
152 syslog(LOG_ERR, "crypto: SSL_CTX_new failed: %s", ERR_reason_error_string(ERR_get_error()));
155 if (!(SSL_CTX_set_cipher_list(ssl_ctx, CIT_CIPHERS))) {
156 syslog(LOG_ERR, "crypto: No ciphers available");
157 SSL_CTX_free(ssl_ctx);
162 CRYPTO_set_locking_callback(ssl_lock);
163 CRYPTO_set_id_callback(id_callback);
165 mkdir(ctdl_key_dir, 0700); // If the keys directory does not exist, create it
166 generate_key(file_crpt_file_key); // If a private key does not exist, create it
169 * If there is no certificate file on disk, we will be generating a self-signed certificate
170 * in the next step. Therefore, if we have neither a CSR nor a certificate, generate
171 * the CSR in this step so that the next step may commence.
173 if ( (access(file_crpt_file_cer, R_OK) != 0) && (access(file_crpt_file_csr, R_OK) != 0) ) {
174 syslog(LOG_INFO, "crypto: generating a generic certificate signing request.");
177 * Read our key from the file. No, we don't just keep this
178 * in memory from the above key-generation function, because
179 * there is the possibility that the key was already on disk
180 * and we didn't just generate it now.
182 fp = fopen(file_crpt_file_key, "r");
184 rsa = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
190 /* Create a public key from the private key */
191 if (pk=EVP_PKEY_new(), pk != NULL) {
192 EVP_PKEY_assign_RSA(pk, rsa);
193 if (req = X509_REQ_new(), req != NULL) {
195 /* Set the public key */
196 X509_REQ_set_pubkey(req, pk);
197 X509_REQ_set_version(req, 0L);
199 name = X509_REQ_get_subject_name(req);
201 /* Tell it who we are */
202 X509_NAME_add_entry_by_txt(name, "C", MBSTRING_ASC, (unsigned const char *)"ZZ", -1, -1, 0);
203 X509_NAME_add_entry_by_txt(name, "ST", MBSTRING_ASC, (unsigned const char *)"The World", -1, -1, 0);
204 X509_NAME_add_entry_by_txt(name, "L", MBSTRING_ASC, (unsigned const char *)"My Location", -1, -1, 0);
205 X509_NAME_add_entry_by_txt(name, "O", MBSTRING_ASC, (unsigned const char *)"Generic certificate", -1, -1, 0);
206 X509_NAME_add_entry_by_txt(name, "OU", MBSTRING_ASC, (unsigned const char *)"Citadel server", -1, -1, 0);
207 X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC, (unsigned const char *)"*", -1, -1, 0);
208 X509_REQ_set_subject_name(req, name);
211 if (!X509_REQ_sign(req, pk, EVP_md5())) {
212 syslog(LOG_ERR, "crypto: X509_REQ_sign(): error");
215 /* Write it to disk. */
216 fp = fopen(file_crpt_file_csr, "w");
218 chmod(file_crpt_file_csr, 0600);
219 PEM_write_X509_REQ(fp, req);
232 syslog(LOG_ERR, "crypto: unable to read private key.");
238 * Generate a self-signed certificate if we don't have one.
240 if (access(file_crpt_file_cer, R_OK) != 0) {
241 syslog(LOG_INFO, "crypto: generating a generic self-signed certificate.");
243 /* Same deal as before: always read the key from disk because
244 * it may or may not have just been generated.
246 fp = fopen(file_crpt_file_key, "r");
248 rsa = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
252 /* This also holds true for the CSR. */
257 if (pk=EVP_PKEY_new(), pk != NULL) {
258 EVP_PKEY_assign_RSA(pk, rsa);
261 fp = fopen(file_crpt_file_csr, "r");
263 req = PEM_read_X509_REQ(fp, NULL, NULL, NULL);
268 if (cer = X509_new(), cer != NULL) {
269 ASN1_INTEGER_set(X509_get_serialNumber(cer), 0);
270 X509_set_issuer_name(cer, X509_REQ_get_subject_name(req));
271 X509_set_subject_name(cer, X509_REQ_get_subject_name(req));
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, "crypto: 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, "crypto: 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, "crypto: 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, "crypto: SSL_write got error %ld, ret %d", errval, retval);
346 syslog(LOG_DEBUG, "crypto: errno is %d", errno);
349 client_write(&buf[nbytes - nremain], nremain);
358 * read data from the encrypted layer.
360 int client_read_sslbuffer(StrBuf *buf, int timeout)
362 char sbuf[16384]; /* OpenSSL communicates in 16k blocks, so let's speak its native tongue. */
367 if (pssl == NULL) return(-1);
370 if (SSL_want_read(pssl)) {
371 if ((SSL_write(pssl, junk, 0)) < 1) {
372 syslog(LOG_DEBUG, "crypto: SSL_write in client_read");
375 rlen = SSL_read(pssl, sbuf, sizeof(sbuf));
379 errval = SSL_get_error(pssl, rlen);
380 if (errval == SSL_ERROR_WANT_READ || errval == SSL_ERROR_WANT_WRITE) {
384 syslog(LOG_DEBUG, "crypto: SSL_read got error %ld", errval);
388 StrBufAppendBufPlain(buf, sbuf, rlen, 0);
394 int client_readline_sslbuffer(StrBuf *Line, StrBuf *IOBuf, const char **Pos, int timeout)
396 CitContext *CCC = CC;
397 const char *pos = NULL;
400 int nSuccessLess = 0;
401 const char *pch = NULL;
403 if ((Line == NULL) || (Pos == NULL) || (IOBuf == NULL))
413 if ((StrLength(IOBuf) > 0) && (pos != NULL) && (pos < ChrPtr(IOBuf) + StrLength(IOBuf)))
416 pch = strchr(pch, '\n');
419 StrBufAppendBufPlain(Line, pos, StrLength(IOBuf) - (pos - ChrPtr(IOBuf)), 0);
425 if ((pch > ChrPtr(IOBuf)) &&
426 (*(pch - 1) == '\r')) {
429 StrBufAppendBufPlain(Line, pos,
432 if (StrLength(IOBuf) <= (pch - ChrPtr(IOBuf) + 1)) {
438 return StrLength(Line);
443 while ((nSuccessLess < timeout) &&
445 (CCC->ssl != NULL)) {
447 rlen = client_read_sslbuffer(IOBuf, timeout);
452 pLF = strchr(ChrPtr(IOBuf), '\n');
459 if (len > 0 && (*(pLF - 1) == '\r') )
461 StrBufAppendBufPlain(Line, pos, len, 0);
462 if (pLF + 1 >= ChrPtr(IOBuf) + StrLength(IOBuf))
468 return StrLength(Line);
474 int client_read_sslblob(StrBuf *Target, long bytes, int timeout)
479 CitContext *CCC = CC;
481 baselen = StrLength(Target);
483 if (StrLength(CCC->RecvBuf.Buf) > 0)
489 if (CCC->RecvBuf.ReadWritePointer == NULL)
491 CCC->RecvBuf.ReadWritePointer = ChrPtr(CCC->RecvBuf.Buf);
493 pchs = ChrPtr(CCC->RecvBuf.Buf);
494 TotalLen = StrLength(CCC->RecvBuf.Buf);
495 RemainLen = TotalLen - (pchs - CCC->RecvBuf.ReadWritePointer);
496 if (RemainLen > bytes)
502 StrBufAppendBufPlain(Target, CCC->RecvBuf.ReadWritePointer, RemainLen, 0);
503 CCC->RecvBuf.ReadWritePointer += RemainLen;
505 if ((ChrPtr(CCC->RecvBuf.Buf) + StrLength(CCC->RecvBuf.Buf)) <= CCC->RecvBuf.ReadWritePointer)
507 CCC->RecvBuf.ReadWritePointer = NULL;
508 FlushStrBuf(CCC->RecvBuf.Buf);
512 if (StrLength(Target) >= bytes + baselen)
517 CCC->RecvBuf.ReadWritePointer = NULL;
519 while ((StrLength(Target) < bytes + baselen) && (retval >= 0))
521 retval = client_read_sslbuffer(CCC->RecvBuf.Buf, timeout);
523 RemainRead = bytes - (StrLength (Target) - baselen);
524 if (RemainRead < StrLength(CCC->RecvBuf.Buf))
526 StrBufAppendBufPlain(
528 ChrPtr(CCC->RecvBuf.Buf),
530 CCC->RecvBuf.ReadWritePointer = ChrPtr(CCC->RecvBuf.Buf) + RemainRead;
533 StrBufAppendBuf(Target, CCC->RecvBuf.Buf, 0); /* todo: Buf > bytes? */
534 FlushStrBuf(CCC->RecvBuf.Buf);
538 FlushStrBuf(CCC->RecvBuf.Buf);
548 * CtdlStartTLS() starts SSL/TLS encryption for the current session. It
549 * must be supplied with pre-generated strings for responses of "ok," "no
550 * support for TLS," and "error" so that we can use this in any protocol.
552 void CtdlStartTLS(char *ok_response, char *nosup_response, char *error_response)
554 int retval, bits, alg_bits;
557 syslog(LOG_ERR, "crypto: SSL failed: no ssl_ctx exists?");
558 if (nosup_response != NULL) cprintf("%s", nosup_response);
561 if (!(CC->ssl = SSL_new(ssl_ctx))) {
562 syslog(LOG_ERR, "crypto: SSL_new failed: %s", ERR_reason_error_string(ERR_get_error()));
563 if (error_response != NULL) {
564 cprintf("%s", error_response);
568 if (!(SSL_set_fd(CC->ssl, CC->client_socket))) {
569 syslog(LOG_ERR, "crypto: SSL_set_fd failed: %s", ERR_reason_error_string(ERR_get_error()));
572 if (error_response != NULL) cprintf("%s", error_response);
575 if (ok_response != NULL) cprintf("%s", ok_response);
576 retval = SSL_accept(CC->ssl);
579 * Can't notify the client of an error here; they will
580 * discover the problem at the SSL layer and should
581 * revert to unencrypted communications.
584 char error_string[128];
586 errval = SSL_get_error(CC->ssl, retval);
587 syslog(LOG_ERR, "crypto: SSL_accept failed: retval=%d, errval=%ld, err=%s",
590 ERR_error_string(errval, error_string)
596 // BIO_set_close(CC->ssl->rbio, BIO_NOCLOSE); not needed anymore in openssl 1.1 ?
597 bits = SSL_CIPHER_get_bits(SSL_get_current_cipher(CC->ssl), &alg_bits);
598 syslog(LOG_INFO, "crypto: SSL/TLS using %s on %s (%d of %d bits)",
599 SSL_CIPHER_get_name(SSL_get_current_cipher(CC->ssl)),
600 SSL_CIPHER_get_version(SSL_get_current_cipher(CC->ssl)),
603 CC->redirect_ssl = 1;
608 * cmd_stls() starts SSL/TLS encryption for the current session
610 void cmd_stls(char *params)
612 char ok_response[SIZ];
613 char nosup_response[SIZ];
614 char error_response[SIZ];
618 sprintf(ok_response, "%d Begin TLS negotiation now\n", CIT_OK);
619 sprintf(nosup_response, "%d TLS not supported here\n", ERROR + CMD_NOT_SUPPORTED);
620 sprintf(error_response, "%d TLS negotiation error\n", ERROR + INTERNAL_ERROR);
622 CtdlStartTLS(ok_response, nosup_response, error_response);
627 * cmd_gtls() returns status info about the TLS connection
629 void cmd_gtls(char *params)
633 if (!CC->ssl || !CC->redirect_ssl) {
634 cprintf("%d Session is not encrypted.\n", ERROR);
638 SSL_CIPHER_get_bits(SSL_get_current_cipher(CC->ssl),
640 cprintf("%d %s|%s|%d|%d\n", CIT_OK,
641 SSL_CIPHER_get_version(SSL_get_current_cipher(CC->ssl)),
642 SSL_CIPHER_get_name(SSL_get_current_cipher(CC->ssl)),
648 * endtls() shuts down the TLS connection
650 * WARNING: This may make your session vulnerable to a known plaintext
651 * attack in the current implmentation.
656 CC->redirect_ssl = 0;
660 syslog(LOG_INFO, "crypto: ending SSL/TLS");
661 SSL_shutdown(CC->ssl);
664 CC->redirect_ssl = 0;
669 * ssl_lock() callback for OpenSSL mutex locks
671 void ssl_lock(int mode, int n, const char *file, int line)
673 if (mode & CRYPTO_LOCK)
675 pthread_mutex_lock(SSLCritters[n]);
678 pthread_mutex_unlock(SSLCritters[n]);
681 #endif /* HAVE_OPENSSL */