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>
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++)
73 void generate_key(char *keyfilename)
79 unsigned long e = RSA_F4;
82 if (access(file_crpt_file_key, R_OK) == 0) {
86 syslog(LOG_INFO, "crypto: generating RSA key pair");
90 ret = BN_set_word(bne,e);
96 ret = RSA_generate_key_ex(rsa, bits, bne, NULL);
101 // write the key file
102 fp = fopen(keyfilename, "w");
104 chmod(file_crpt_file_key, 0600);
105 if (PEM_write_RSAPrivateKey(fp, /* the file */
108 NULL, /* no passphr */
110 NULL, /* no callbk */
113 syslog(LOG_ERR, "crypto: cannot write key: %s", ERR_reason_error_string(ERR_get_error()));
114 unlink(file_crpt_file_key);
130 const SSL_METHOD *ssl_method;
132 X509_REQ *req = NULL;
135 EVP_PKEY *req_pkey = NULL;
136 X509_NAME *name = NULL;
139 SSLCritters = malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t *));
141 syslog(LOG_ERR, "crypto: can't allocate memory!");
142 exit(CTDLEXIT_CRYPTO);
146 for (a = 0; a < CRYPTO_num_locks(); a++) {
147 SSLCritters[a] = malloc(sizeof(pthread_mutex_t));
148 if (!SSLCritters[a]) {
149 syslog(LOG_ERR, "crypto: can't allocate memory!!");
150 exit(CTDLEXIT_CRYPTO);
152 pthread_mutex_init(SSLCritters[a], NULL);
157 * Initialize SSL transport layer
160 SSL_load_error_strings();
161 ssl_method = SSLv23_server_method();
162 if (!(ssl_ctx = SSL_CTX_new(ssl_method))) {
163 syslog(LOG_ERR, "crypto: SSL_CTX_new failed: %s", ERR_reason_error_string(ERR_get_error()));
166 if (!(SSL_CTX_set_cipher_list(ssl_ctx, CIT_CIPHERS))) {
167 syslog(LOG_ERR, "crypto: No ciphers available");
168 SSL_CTX_free(ssl_ctx);
173 CRYPTO_set_locking_callback(ssl_lock);
174 CRYPTO_set_id_callback(id_callback);
176 mkdir(ctdl_key_dir, 0700); // If the keys directory does not exist, create it
177 generate_key(file_crpt_file_key); // If a private key does not exist, create it
180 * If there is no certificate file on disk, we will be generating a self-signed certificate
181 * in the next step. Therefore, if we have neither a CSR nor a certificate, generate
182 * the CSR in this step so that the next step may commence.
184 if ( (access(file_crpt_file_cer, R_OK) != 0) && (access(file_crpt_file_csr, R_OK) != 0) ) {
185 syslog(LOG_INFO, "crypto: generating a generic certificate signing request.");
188 * Read our key from the file. No, we don't just keep this
189 * in memory from the above key-generation function, because
190 * there is the possibility that the key was already on disk
191 * and we didn't just generate it now.
193 fp = fopen(file_crpt_file_key, "r");
195 rsa = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
201 /* Create a public key from the private key */
202 if (pk=EVP_PKEY_new(), pk != NULL) {
203 EVP_PKEY_assign_RSA(pk, rsa);
204 if (req = X509_REQ_new(), req != NULL) {
206 /* Set the public key */
207 X509_REQ_set_pubkey(req, pk);
208 X509_REQ_set_version(req, 0L);
210 name = X509_REQ_get_subject_name(req);
212 /* Tell it who we are */
213 X509_NAME_add_entry_by_txt(name, "C", MBSTRING_ASC, (unsigned const char *)"ZZ", -1, -1, 0);
214 X509_NAME_add_entry_by_txt(name, "ST", MBSTRING_ASC, (unsigned const char *)"The World", -1, -1, 0);
215 X509_NAME_add_entry_by_txt(name, "L", MBSTRING_ASC, (unsigned const char *)"My Location", -1, -1, 0);
216 X509_NAME_add_entry_by_txt(name, "O", MBSTRING_ASC, (unsigned const char *)"Generic certificate", -1, -1, 0);
217 X509_NAME_add_entry_by_txt(name, "OU", MBSTRING_ASC, (unsigned const char *)"Citadel server", -1, -1, 0);
218 X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC, (unsigned const char *)"*", -1, -1, 0);
219 X509_REQ_set_subject_name(req, name);
222 if (!X509_REQ_sign(req, pk, EVP_md5())) {
223 syslog(LOG_ERR, "crypto: X509_REQ_sign(): error");
226 /* Write it to disk. */
227 fp = fopen(file_crpt_file_csr, "w");
229 chmod(file_crpt_file_csr, 0600);
230 PEM_write_X509_REQ(fp, req);
243 syslog(LOG_ERR, "crypto: unable to read private key.");
249 * Generate a self-signed certificate if we don't have one.
251 if (access(file_crpt_file_cer, R_OK) != 0) {
252 syslog(LOG_INFO, "crypto: generating a generic self-signed certificate.");
254 /* Same deal as before: always read the key from disk because
255 * it may or may not have just been generated.
257 fp = fopen(file_crpt_file_key, "r");
259 rsa = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
263 /* This also holds true for the CSR. */
268 if (pk=EVP_PKEY_new(), pk != NULL) {
269 EVP_PKEY_assign_RSA(pk, rsa);
272 fp = fopen(file_crpt_file_csr, "r");
274 req = PEM_read_X509_REQ(fp, NULL, NULL, NULL);
279 if (cer = X509_new(), cer != NULL) {
280 ASN1_INTEGER_set(X509_get_serialNumber(cer), 0);
281 X509_set_issuer_name(cer, X509_REQ_get_subject_name(req));
282 X509_set_subject_name(cer, X509_REQ_get_subject_name(req));
283 X509_gmtime_adj(X509_get_notBefore(cer),0);
284 X509_gmtime_adj(X509_get_notAfter(cer),(long)60*60*24*SIGN_DAYS);
285 req_pkey = X509_REQ_get_pubkey(req);
286 X509_set_pubkey(cer, req_pkey);
287 EVP_PKEY_free(req_pkey);
290 if (!X509_sign(cer, pk, EVP_md5())) {
291 syslog(LOG_ERR, "crypto: X509_sign() error");
294 /* Write it to disk. */
295 fp = fopen(file_crpt_file_cer, "w");
297 chmod(file_crpt_file_cer, 0600);
298 PEM_write_X509(fp, cer);
312 * Now try to bind to the key and certificate.
314 SSL_CTX_use_certificate_chain_file(ssl_ctx, file_crpt_file_cer);
315 SSL_CTX_use_PrivateKey_file(ssl_ctx, file_crpt_file_key, SSL_FILETYPE_PEM);
316 if ( !SSL_CTX_check_private_key(ssl_ctx) ) {
317 syslog(LOG_ERR, "crypto: cannot install certificate: %s", ERR_reason_error_string(ERR_get_error()));
320 /* Finally let the server know we're here */
321 CtdlRegisterProtoHook(cmd_stls, "STLS", "Start SSL/TLS session");
322 CtdlRegisterProtoHook(cmd_gtls, "GTLS", "Get SSL/TLS session status");
323 CtdlRegisterSessionHook(endtls, EVT_STOP, PRIO_STOP + 10);
328 * client_write_ssl() Send binary data to the client encrypted.
330 void client_write_ssl(const char *buf, int nbytes)
338 while (nremain > 0) {
339 if (SSL_want_write(CC->ssl)) {
340 if ((SSL_read(CC->ssl, junk, 0)) < 1) {
341 syslog(LOG_DEBUG, "crypto: SSL_read in client_write: %s", ERR_reason_error_string(ERR_get_error()));
345 SSL_write(CC->ssl, &buf[nbytes - nremain], nremain);
349 errval = SSL_get_error(CC->ssl, retval);
350 if (errval == SSL_ERROR_WANT_READ ||
351 errval == SSL_ERROR_WANT_WRITE) {
355 syslog(LOG_DEBUG, "crypto: SSL_write got error %ld, ret %d", errval, retval);
357 syslog(LOG_DEBUG, "crypto: errno is %d", errno);
360 client_write(&buf[nbytes - nremain], nremain);
369 * read data from the encrypted layer.
371 int client_read_sslbuffer(StrBuf *buf, int timeout)
373 char sbuf[16384]; /* OpenSSL communicates in 16k blocks, so let's speak its native tongue. */
378 if (pssl == NULL) return(-1);
381 if (SSL_want_read(pssl)) {
382 if ((SSL_write(pssl, junk, 0)) < 1) {
383 syslog(LOG_DEBUG, "crypto: SSL_write in client_read");
386 rlen = SSL_read(pssl, sbuf, sizeof(sbuf));
390 errval = SSL_get_error(pssl, rlen);
391 if (errval == SSL_ERROR_WANT_READ || errval == SSL_ERROR_WANT_WRITE) {
395 syslog(LOG_DEBUG, "crypto: SSL_read got error %ld", errval);
399 StrBufAppendBufPlain(buf, sbuf, rlen, 0);
405 int client_readline_sslbuffer(StrBuf *Line, StrBuf *IOBuf, const char **Pos, int timeout)
407 CitContext *CCC = CC;
408 const char *pos = NULL;
411 int nSuccessLess = 0;
412 const char *pch = NULL;
414 if ((Line == NULL) || (Pos == NULL) || (IOBuf == NULL))
424 if ((StrLength(IOBuf) > 0) && (pos != NULL) && (pos < ChrPtr(IOBuf) + StrLength(IOBuf)))
427 pch = strchr(pch, '\n');
430 StrBufAppendBufPlain(Line, pos, StrLength(IOBuf) - (pos - ChrPtr(IOBuf)), 0);
436 if ((pch > ChrPtr(IOBuf)) &&
437 (*(pch - 1) == '\r')) {
440 StrBufAppendBufPlain(Line, pos,
443 if (StrLength(IOBuf) <= (pch - ChrPtr(IOBuf) + 1)) {
449 return StrLength(Line);
454 while ((nSuccessLess < timeout) &&
456 (CCC->ssl != NULL)) {
458 rlen = client_read_sslbuffer(IOBuf, timeout);
463 pLF = strchr(ChrPtr(IOBuf), '\n');
470 if (len > 0 && (*(pLF - 1) == '\r') )
472 StrBufAppendBufPlain(Line, pos, len, 0);
473 if (pLF + 1 >= ChrPtr(IOBuf) + StrLength(IOBuf))
479 return StrLength(Line);
485 int client_read_sslblob(StrBuf *Target, long bytes, int timeout)
490 CitContext *CCC = CC;
492 baselen = StrLength(Target);
494 if (StrLength(CCC->RecvBuf.Buf) > 0)
500 if (CCC->RecvBuf.ReadWritePointer == NULL)
502 CCC->RecvBuf.ReadWritePointer = ChrPtr(CCC->RecvBuf.Buf);
504 pchs = ChrPtr(CCC->RecvBuf.Buf);
505 TotalLen = StrLength(CCC->RecvBuf.Buf);
506 RemainLen = TotalLen - (pchs - CCC->RecvBuf.ReadWritePointer);
507 if (RemainLen > bytes)
513 StrBufAppendBufPlain(Target, CCC->RecvBuf.ReadWritePointer, RemainLen, 0);
514 CCC->RecvBuf.ReadWritePointer += RemainLen;
516 if ((ChrPtr(CCC->RecvBuf.Buf) + StrLength(CCC->RecvBuf.Buf)) <= CCC->RecvBuf.ReadWritePointer)
518 CCC->RecvBuf.ReadWritePointer = NULL;
519 FlushStrBuf(CCC->RecvBuf.Buf);
523 if (StrLength(Target) >= bytes + baselen)
528 CCC->RecvBuf.ReadWritePointer = NULL;
530 while ((StrLength(Target) < bytes + baselen) && (retval >= 0))
532 retval = client_read_sslbuffer(CCC->RecvBuf.Buf, timeout);
534 RemainRead = bytes - (StrLength (Target) - baselen);
535 if (RemainRead < StrLength(CCC->RecvBuf.Buf))
537 StrBufAppendBufPlain(
539 ChrPtr(CCC->RecvBuf.Buf),
541 CCC->RecvBuf.ReadWritePointer = ChrPtr(CCC->RecvBuf.Buf) + RemainRead;
544 StrBufAppendBuf(Target, CCC->RecvBuf.Buf, 0); /* todo: Buf > bytes? */
545 FlushStrBuf(CCC->RecvBuf.Buf);
549 FlushStrBuf(CCC->RecvBuf.Buf);
559 * CtdlStartTLS() starts SSL/TLS encryption for the current session. It
560 * must be supplied with pre-generated strings for responses of "ok," "no
561 * support for TLS," and "error" so that we can use this in any protocol.
563 void CtdlStartTLS(char *ok_response, char *nosup_response, char *error_response)
565 int retval, bits, alg_bits;
568 syslog(LOG_ERR, "crypto: SSL failed: no ssl_ctx exists?");
569 if (nosup_response != NULL) cprintf("%s", nosup_response);
572 if (!(CC->ssl = SSL_new(ssl_ctx))) {
573 syslog(LOG_ERR, "crypto: SSL_new failed: %s", ERR_reason_error_string(ERR_get_error()));
574 if (error_response != NULL) {
575 cprintf("%s", error_response);
579 if (!(SSL_set_fd(CC->ssl, CC->client_socket))) {
580 syslog(LOG_ERR, "crypto: SSL_set_fd failed: %s", ERR_reason_error_string(ERR_get_error()));
583 if (error_response != NULL) cprintf("%s", error_response);
586 if (ok_response != NULL) cprintf("%s", ok_response);
587 retval = SSL_accept(CC->ssl);
590 * Can't notify the client of an error here; they will
591 * discover the problem at the SSL layer and should
592 * revert to unencrypted communications.
595 char error_string[128];
597 errval = SSL_get_error(CC->ssl, retval);
598 syslog(LOG_ERR, "crypto: SSL_accept failed: retval=%d, errval=%ld, err=%s",
601 ERR_error_string(errval, error_string)
607 // BIO_set_close(CC->ssl->rbio, BIO_NOCLOSE); not needed anymore in openssl 1.1 ?
608 bits = SSL_CIPHER_get_bits(SSL_get_current_cipher(CC->ssl), &alg_bits);
609 syslog(LOG_INFO, "crypto: SSL/TLS using %s on %s (%d of %d bits)",
610 SSL_CIPHER_get_name(SSL_get_current_cipher(CC->ssl)),
611 SSL_CIPHER_get_version(SSL_get_current_cipher(CC->ssl)),
614 CC->redirect_ssl = 1;
619 * cmd_stls() starts SSL/TLS encryption for the current session
621 void cmd_stls(char *params)
623 char ok_response[SIZ];
624 char nosup_response[SIZ];
625 char error_response[SIZ];
629 sprintf(ok_response, "%d Begin TLS negotiation now\n", CIT_OK);
630 sprintf(nosup_response, "%d TLS not supported here\n", ERROR + CMD_NOT_SUPPORTED);
631 sprintf(error_response, "%d TLS negotiation error\n", ERROR + INTERNAL_ERROR);
633 CtdlStartTLS(ok_response, nosup_response, error_response);
638 * cmd_gtls() returns status info about the TLS connection
640 void cmd_gtls(char *params)
644 if (!CC->ssl || !CC->redirect_ssl) {
645 cprintf("%d Session is not encrypted.\n", ERROR);
649 SSL_CIPHER_get_bits(SSL_get_current_cipher(CC->ssl),
651 cprintf("%d %s|%s|%d|%d\n", CIT_OK,
652 SSL_CIPHER_get_version(SSL_get_current_cipher(CC->ssl)),
653 SSL_CIPHER_get_name(SSL_get_current_cipher(CC->ssl)),
659 * endtls() shuts down the TLS connection
661 * WARNING: This may make your session vulnerable to a known plaintext
662 * attack in the current implmentation.
667 CC->redirect_ssl = 0;
671 syslog(LOG_INFO, "crypto: ending SSL/TLS");
672 SSL_shutdown(CC->ssl);
675 CC->redirect_ssl = 0;
680 * ssl_lock() callback for OpenSSL mutex locks
682 void ssl_lock(int mode, int n, const char *file, int line)
684 if (mode & CRYPTO_LOCK)
686 pthread_mutex_lock(SSLCritters[n]);
689 pthread_mutex_unlock(SSLCritters[n]);
692 #endif /* HAVE_OPENSSL */