Remove dependency on configdb when auto-generating CSR, because it has not been initi...
[citadel.git] / citadel / modules / crypto / serv_crypto.c
1 /*
2  * Copyright (c) 1987-2015 by the citadel.org team
3  *
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.
6  *
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.
11  */
12
13 #include <string.h>
14 #include <unistd.h>
15 #include <sys/stat.h>
16 #include <sys/types.h>
17 #include "sysdep.h"
18
19 #ifdef HAVE_OPENSSL
20 #include <openssl/ssl.h>
21 #include <openssl/err.h>
22 #include <openssl/rand.h>
23 #endif
24
25 #if TIME_WITH_SYS_TIME
26 # include <sys/time.h>
27 # include <time.h>
28 #else
29 # if HAVE_SYS_TIME_H
30 #  include <sys/time.h>
31 # else
32 #  include <time.h>
33 # endif
34 #endif
35
36 #ifdef HAVE_PTHREAD_H
37 #include <pthread.h>
38 #endif
39
40 #ifdef HAVE_SYS_SELECT_H
41 #include <sys/select.h>
42 #endif
43
44 #include <stdio.h>
45 #include <libcitadel.h>
46 #include "server.h"
47 #include "serv_crypto.h"
48 #include "sysdep_decls.h"
49 #include "citadel.h"
50 #include "config.h"
51
52
53 #include "ctdl_module.h"
54 /* TODO: should we use the standard module init stuff to start this? */
55 /* TODO: should we register an event handler to call destruct_ssl? */
56
57 #ifdef HAVE_OPENSSL
58 SSL_CTX *ssl_ctx;               /* SSL context */
59 pthread_mutex_t **SSLCritters;  /* Things needing locking */
60
61 static unsigned long id_callback(void)
62 {
63         return (unsigned long) pthread_self();
64 }
65
66 void destruct_ssl(void)
67 {
68         int a;
69         for (a = 0; a < CRYPTO_num_locks(); a++) 
70                 free(SSLCritters[a]);
71         free (SSLCritters);
72 }
73
74 void init_ssl(void)
75 {
76         const SSL_METHOD *ssl_method;
77         DH *dh;
78         RSA *rsa=NULL;
79         X509_REQ *req = NULL;
80         X509 *cer = NULL;
81         EVP_PKEY *pk = NULL;
82         EVP_PKEY *req_pkey = NULL;
83         X509_NAME *name = NULL;
84         FILE *fp;
85
86         if (!access(EGD_POOL, F_OK))
87                 RAND_egd(EGD_POOL);
88
89         if (!RAND_status()) {
90                 syslog(LOG_CRIT, "PRNG not adequately seeded, won't do SSL/TLS");
91                 return;
92         }
93         SSLCritters =
94             malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t *));
95         if (!SSLCritters) {
96                 syslog(LOG_EMERG, "citserver: can't allocate memory!!");
97                 /* Nothing's been initialized, just die */
98                 exit(1);
99         } else {
100                 int a;
101
102                 for (a = 0; a < CRYPTO_num_locks(); a++) {
103                         SSLCritters[a] = malloc(sizeof(pthread_mutex_t));
104                         if (!SSLCritters[a]) {
105                                 syslog(LOG_EMERG, "citserver: can't allocate memory!!");
106                                 /* Nothing's been initialized, just die */
107                                 exit(1);
108                         }
109                         pthread_mutex_init(SSLCritters[a], NULL);
110                 }
111         }
112
113         /*
114          * Initialize SSL transport layer
115          */
116         SSL_library_init();
117         SSL_load_error_strings();
118         ssl_method = SSLv23_server_method();
119         if (!(ssl_ctx = SSL_CTX_new(ssl_method))) {
120                 syslog(LOG_CRIT, "SSL_CTX_new failed: %s", ERR_reason_error_string(ERR_get_error()));
121                 return;
122         }
123         if (!(SSL_CTX_set_cipher_list(ssl_ctx, CIT_CIPHERS))) {
124                 syslog(LOG_CRIT, "SSL: No ciphers available");
125                 SSL_CTX_free(ssl_ctx);
126                 ssl_ctx = NULL;
127                 return;
128         }
129 #if 0
130 #if SSLEAY_VERSION_NUMBER >= 0x00906000L
131         SSL_CTX_set_mode(ssl_ctx, SSL_CTX_get_mode(ssl_ctx) |
132                          SSL_MODE_AUTO_RETRY);
133 #endif
134 #endif
135
136         CRYPTO_set_locking_callback(ssl_lock);
137         CRYPTO_set_id_callback(id_callback);
138
139         /* Load DH parameters into the context */
140         dh = DH_new();
141         if (!dh) {
142                 syslog(LOG_CRIT, "init_ssl() can't allocate a DH object: %s", ERR_reason_error_string(ERR_get_error()));
143                 SSL_CTX_free(ssl_ctx);
144                 ssl_ctx = NULL;
145                 return;
146         }
147         if (!(BN_hex2bn(&(dh->p), DH_P))) {
148                 syslog(LOG_CRIT, "init_ssl() can't assign DH_P: %s", ERR_reason_error_string(ERR_get_error()));
149                 SSL_CTX_free(ssl_ctx);
150                 ssl_ctx = NULL;
151                 return;
152         }
153         if (!(BN_hex2bn(&(dh->g), DH_G))) {
154                 syslog(LOG_CRIT, "init_ssl() can't assign DH_G: %s", ERR_reason_error_string(ERR_get_error()));
155                 SSL_CTX_free(ssl_ctx);
156                 ssl_ctx = NULL;
157                 return;
158         }
159         dh->length = DH_L;
160         SSL_CTX_set_tmp_dh(ssl_ctx, dh);
161         DH_free(dh);
162
163         /* Get our certificates in order.
164          * First, create the key/cert directory if it's not there already...
165          */
166         mkdir(ctdl_key_dir, 0700);
167
168         /*
169          * Generate a key pair if we don't have one.
170          */
171         if (access(file_crpt_file_key, R_OK) != 0) {
172                 syslog(LOG_INFO, "Generating RSA key pair.");
173                 rsa = RSA_generate_key(1024,    /* modulus size */
174                                         65537,  /* exponent */
175                                         NULL,   /* no callback */
176                                         NULL);  /* no callback */
177                 if (rsa == NULL) {
178                         syslog(LOG_CRIT, "Key generation failed: %s", ERR_reason_error_string(ERR_get_error()));
179                 }
180                 if (rsa != NULL) {
181                         fp = fopen(file_crpt_file_key, "w");
182                         if (fp != NULL) {
183                                 chmod(file_crpt_file_key, 0600);
184                                 if (PEM_write_RSAPrivateKey(fp, /* the file */
185                                                         rsa,    /* the key */
186                                                         NULL,   /* no enc */
187                                                         NULL,   /* no passphr */
188                                                         0,      /* no passphr */
189                                                         NULL,   /* no callbk */
190                                                         NULL    /* no callbk */
191                                 ) != 1) {
192                                         syslog(LOG_CRIT, "Cannot write key: %s", ERR_reason_error_string(ERR_get_error()));
193                                         unlink(file_crpt_file_key);
194                                 }
195                                 fclose(fp);
196                         }
197                         RSA_free(rsa);
198                 }
199         }
200
201         /*
202          * If there is no certificate file on disk, we will be generating a self-signed certificate
203          * in the next step.  Therefore, if we have neither a CSR nor a certificate, generate
204          * the CSR in this step so that the next step may commence.
205          */
206         if ( (access(file_crpt_file_cer, R_OK) != 0) && (access(file_crpt_file_csr, R_OK) != 0) ) {
207                 syslog(LOG_INFO, "Generating a generic certificate signing request.");
208
209                 /*
210                  * Read our key from the file.  No, we don't just keep this
211                  * in memory from the above key-generation function, because
212                  * there is the possibility that the key was already on disk
213                  * and we didn't just generate it now.
214                  */
215                 fp = fopen(file_crpt_file_key, "r");
216                 if (fp) {
217                         rsa = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
218                         fclose(fp);
219                 }
220
221                 if (rsa) {
222
223                         /* Create a public key from the private key */
224                         if (pk=EVP_PKEY_new(), pk != NULL) {
225                                 EVP_PKEY_assign_RSA(pk, rsa);
226                                 if (req = X509_REQ_new(), req != NULL) {
227
228                                         /* Set the public key */
229                                         X509_REQ_set_pubkey(req, pk);
230                                         X509_REQ_set_version(req, 0L);
231
232                                         name = X509_REQ_get_subject_name(req);
233
234                                         /* Tell it who we are */
235                                         X509_NAME_add_entry_by_txt(name, "C", MBSTRING_ASC, (unsigned const char *)"ZZ", -1, -1, 0);
236                                         X509_NAME_add_entry_by_txt(name, "ST", MBSTRING_ASC, (unsigned const char *)"The World", -1, -1, 0);
237                                         X509_NAME_add_entry_by_txt(name, "L", MBSTRING_ASC, (unsigned const char *)"My Location", -1, -1, 0);
238                                         X509_NAME_add_entry_by_txt(name, "O", MBSTRING_ASC, (unsigned const char *)"Generic certificate", -1, -1, 0);
239                                         X509_NAME_add_entry_by_txt(name, "OU", MBSTRING_ASC, (unsigned const char *)"Citadel server", -1, -1, 0);
240                                         X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC, (unsigned const char *)"*", -1, -1, 0);
241                                         X509_REQ_set_subject_name(req, name);
242
243                                         /* Sign the CSR */
244                                         if (!X509_REQ_sign(req, pk, EVP_md5())) {
245                                                 syslog(LOG_CRIT, "X509_REQ_sign(): error");
246                                         }
247                                         else {
248                                                 /* Write it to disk. */ 
249                                                 fp = fopen(file_crpt_file_csr, "w");
250                                                 if (fp != NULL) {
251                                                         chmod(file_crpt_file_csr, 0600);
252                                                         PEM_write_X509_REQ(fp, req);
253                                                         fclose(fp);
254                                                 }
255                                         }
256
257                                         X509_REQ_free(req);
258                                 }
259                         }
260
261                         RSA_free(rsa);
262                 }
263
264                 else {
265                         syslog(LOG_CRIT, "Unable to read private key.");
266                 }
267         }
268
269
270
271         /*
272          * Generate a self-signed certificate if we don't have one.
273          */
274         if (access(file_crpt_file_cer, R_OK) != 0) {
275                 syslog(LOG_INFO, "Generating a generic self-signed certificate.");
276
277                 /* Same deal as before: always read the key from disk because
278                  * it may or may not have just been generated.
279                  */
280                 fp = fopen(file_crpt_file_key, "r");
281                 if (fp) {
282                         rsa = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
283                         fclose(fp);
284                 }
285
286                 /* This also holds true for the CSR. */
287                 req = NULL;
288                 cer = NULL;
289                 pk = NULL;
290                 if (rsa) {
291                         if (pk=EVP_PKEY_new(), pk != NULL) {
292                                 EVP_PKEY_assign_RSA(pk, rsa);
293                         }
294
295                         fp = fopen(file_crpt_file_csr, "r");
296                         if (fp) {
297                                 req = PEM_read_X509_REQ(fp, NULL, NULL, NULL);
298                                 fclose(fp);
299                         }
300
301                         if (req) {
302                                 if (cer = X509_new(), cer != NULL) {
303
304                                         ASN1_INTEGER_set(X509_get_serialNumber(cer), 0);
305                                         X509_set_issuer_name(cer, req->req_info->subject);
306                                         X509_set_subject_name(cer, req->req_info->subject);
307                                         X509_gmtime_adj(X509_get_notBefore(cer),0);
308                                         X509_gmtime_adj(X509_get_notAfter(cer),(long)60*60*24*SIGN_DAYS);
309                                         req_pkey = X509_REQ_get_pubkey(req);
310                                         X509_set_pubkey(cer, req_pkey);
311                                         EVP_PKEY_free(req_pkey);
312                                         
313                                         /* Sign the cert */
314                                         if (!X509_sign(cer, pk, EVP_md5())) {
315                                                 syslog(LOG_CRIT, "X509_sign(): error");
316                                         }
317                                         else {
318                                                 /* Write it to disk. */ 
319                                                 fp = fopen(file_crpt_file_cer, "w");
320                                                 if (fp != NULL) {
321                                                         chmod(file_crpt_file_cer, 0600);
322                                                         PEM_write_X509(fp, cer);
323                                                         fclose(fp);
324                                                 }
325                                         }
326                                         X509_free(cer);
327                                 }
328                         }
329
330                         RSA_free(rsa);
331                 }
332         }
333
334
335         /*
336          * Now try to bind to the key and certificate.
337          */
338         SSL_CTX_use_certificate_chain_file(ssl_ctx, file_crpt_file_cer);
339         SSL_CTX_use_PrivateKey_file(ssl_ctx, file_crpt_file_key, SSL_FILETYPE_PEM);
340         if ( !SSL_CTX_check_private_key(ssl_ctx) ) {
341                 syslog(LOG_CRIT, "Cannot install certificate: %s", ERR_reason_error_string(ERR_get_error()));
342         }
343
344         /* Finally let the server know we're here */
345         CtdlRegisterProtoHook(cmd_stls, "STLS", "Start SSL/TLS session");
346         CtdlRegisterProtoHook(cmd_gtls, "GTLS",
347                               "Get SSL/TLS session status");
348         CtdlRegisterSessionHook(endtls, EVT_STOP, PRIO_STOP + 10);
349 }
350
351
352 /*
353  * client_write_ssl() Send binary data to the client encrypted.
354  */
355 void client_write_ssl(const char *buf, int nbytes)
356 {
357         int retval;
358         int nremain;
359         char junk[1];
360
361         nremain = nbytes;
362
363         while (nremain > 0) {
364                 if (SSL_want_write(CC->ssl)) {
365                         if ((SSL_read(CC->ssl, junk, 0)) < 1) {
366                                 syslog(LOG_DEBUG, "SSL_read in client_write: %s", ERR_reason_error_string(ERR_get_error()));
367                         }
368                 }
369                 retval =
370                     SSL_write(CC->ssl, &buf[nbytes - nremain], nremain);
371                 if (retval < 1) {
372                         long errval;
373
374                         errval = SSL_get_error(CC->ssl, retval);
375                         if (errval == SSL_ERROR_WANT_READ ||
376                             errval == SSL_ERROR_WANT_WRITE) {
377                                 sleep(1);
378                                 continue;
379                         }
380                         syslog(LOG_DEBUG, "SSL_write got error %ld, ret %d", errval, retval);
381                         if (retval == -1)
382                                 syslog(LOG_DEBUG, "errno is %d", errno);
383                         endtls();
384                         client_write(&buf[nbytes - nremain], nremain);
385                         return;
386                 }
387                 nremain -= retval;
388         }
389 }
390
391
392 /*
393  * read data from the encrypted layer.
394  */
395 int client_read_sslbuffer(StrBuf *buf, int timeout)
396 {
397         char sbuf[16384]; /* OpenSSL communicates in 16k blocks, so let's speak its native tongue. */
398         int rlen;
399         char junk[1];
400         SSL *pssl = CC->ssl;
401
402         if (pssl == NULL) return(-1);
403
404         while (1) {
405                 if (SSL_want_read(pssl)) {
406                         if ((SSL_write(pssl, junk, 0)) < 1) {
407                                 syslog(LOG_DEBUG, "SSL_write in client_read");
408                         }
409                 }
410                 rlen = SSL_read(pssl, sbuf, sizeof(sbuf));
411                 if (rlen < 1) {
412                         long errval;
413
414                         errval = SSL_get_error(pssl, rlen);
415                         if (errval == SSL_ERROR_WANT_READ || errval == SSL_ERROR_WANT_WRITE) {
416                                 sleep(1);
417                                 continue;
418                         }
419                         syslog(LOG_DEBUG, "SSL_read got error %ld", errval);
420                         endtls();
421                         return (-1);
422                 }
423                 StrBufAppendBufPlain(buf, sbuf, rlen, 0);
424                 return rlen;
425         }
426         return (0);
427 }
428
429 int client_readline_sslbuffer(StrBuf *Line, StrBuf *IOBuf, const char **Pos, int timeout)
430 {
431         CitContext *CCC = CC;
432         const char *pos = NULL;
433         const char *pLF;
434         int len, rlen;
435         int nSuccessLess = 0;
436         const char *pch = NULL;
437         
438         if ((Line == NULL) ||
439             (Pos == NULL) ||
440             (IOBuf == NULL))
441         {
442                 if (Pos != NULL)
443                         *Pos = NULL;
444 //              *Error = ErrRBLF_PreConditionFailed;
445                 return -1;
446         }
447
448         pos = *Pos;
449         if ((StrLength(IOBuf) > 0) && 
450             (pos != NULL) && 
451             (pos < ChrPtr(IOBuf) + StrLength(IOBuf))) 
452         {
453                 pch = pos;
454                 pch = strchr(pch, '\n');
455                 
456                 if (pch == NULL) {
457                         StrBufAppendBufPlain(Line, pos, 
458                                              StrLength(IOBuf) - (pos - ChrPtr(IOBuf)), 0);
459                         FlushStrBuf(IOBuf);
460                         *Pos = NULL;
461                 }
462                 else {
463                         int n = 0;
464                         if ((pch > ChrPtr(IOBuf)) && 
465                             (*(pch - 1) == '\r')) {
466                                 n = 1;
467                         }
468                         StrBufAppendBufPlain(Line, pos, 
469                                              (pch - pos - n), 0);
470
471                         if (StrLength(IOBuf) <= (pch - ChrPtr(IOBuf) + 1)) {
472                                 FlushStrBuf(IOBuf);
473                                 *Pos = NULL;
474                         }
475                         else 
476                                 *Pos = pch + 1;
477                         return StrLength(Line);
478                 }
479         }
480
481         pLF = NULL;
482         while ((nSuccessLess < timeout) && 
483                (pLF == NULL) &&
484                (CCC->ssl != NULL)) {
485
486                 rlen = client_read_sslbuffer(IOBuf, timeout);
487                 if (rlen < 1) {
488 //                      *Error = strerror(errno);
489 //                      close(*fd);
490 //                      *fd = -1;
491                         return -1;
492                 }
493                 else if (rlen > 0) {
494                         pLF = strchr(ChrPtr(IOBuf), '\n');
495                 }
496         }
497         *Pos = NULL;
498         if (pLF != NULL) {
499                 pos = ChrPtr(IOBuf);
500                 len = pLF - pos;
501                 if (len > 0 && (*(pLF - 1) == '\r') )
502                         len --;
503                 StrBufAppendBufPlain(Line, pos, len, 0);
504                 if (pLF + 1 >= ChrPtr(IOBuf) + StrLength(IOBuf))
505                 {
506                         FlushStrBuf(IOBuf);
507                 }
508                 else 
509                         *Pos = pLF + 1;
510                 return StrLength(Line);
511         }
512 //      *Error = ErrRBLF_NotEnoughSentFromServer;
513         return -1;
514 }
515
516
517
518 int client_read_sslblob(StrBuf *Target, long bytes, int timeout)
519 {
520         long baselen;
521         long RemainRead;
522         int retval = 0;
523         CitContext *CCC = CC;
524
525         baselen = StrLength(Target);
526
527         if (StrLength(CCC->RecvBuf.Buf) > 0)
528         {
529                 long RemainLen;
530                 long TotalLen;
531                 const char *pchs;
532
533                 if (CCC->RecvBuf.ReadWritePointer == NULL)
534                         CCC->RecvBuf.ReadWritePointer = ChrPtr(CCC->RecvBuf.Buf);
535                 pchs = ChrPtr(CCC->RecvBuf.Buf);
536                 TotalLen = StrLength(CCC->RecvBuf.Buf);
537                 RemainLen = TotalLen - (pchs - CCC->RecvBuf.ReadWritePointer);
538                 if (RemainLen > bytes)
539                         RemainLen = bytes;
540                 if (RemainLen > 0)
541                 {
542                         StrBufAppendBufPlain(Target, 
543                                              CCC->RecvBuf.ReadWritePointer, 
544                                              RemainLen, 0);
545                         CCC->RecvBuf.ReadWritePointer += RemainLen;
546                 }
547                 if ((ChrPtr(CCC->RecvBuf.Buf) + StrLength(CCC->RecvBuf.Buf)) <= CCC->RecvBuf.ReadWritePointer)
548                 {
549                         CCC->RecvBuf.ReadWritePointer = NULL;
550                         FlushStrBuf(CCC->RecvBuf.Buf);
551                 }
552         }
553
554         if (StrLength(Target) >= bytes + baselen)
555                 return 1;
556
557         CCC->RecvBuf.ReadWritePointer = NULL;
558
559         while ((StrLength(Target) < bytes + baselen) &&
560                (retval >= 0))
561         {
562                 retval = client_read_sslbuffer(CCC->RecvBuf.Buf, timeout);
563                 if (retval >= 0) {
564                         RemainRead = bytes - (StrLength (Target) - baselen);
565                         if (RemainRead < StrLength(CCC->RecvBuf.Buf))
566                         {
567                                 StrBufAppendBufPlain(
568                                         Target, 
569                                         ChrPtr(CCC->RecvBuf.Buf), 
570                                         RemainRead, 0);
571                                 CCC->RecvBuf.ReadWritePointer = ChrPtr(CCC->RecvBuf.Buf) + RemainRead;
572                                 break;
573                         }
574                         StrBufAppendBuf(Target, CCC->RecvBuf.Buf, 0); /* todo: Buf > bytes? */
575                         FlushStrBuf(CCC->RecvBuf.Buf);
576                 }
577                 else 
578                 {
579                         FlushStrBuf(CCC->RecvBuf.Buf);
580                         return -1;
581         
582                 }
583         }
584         return 1;
585 }
586
587
588 /*
589  * CtdlStartTLS() starts SSL/TLS encryption for the current session.  It
590  * must be supplied with pre-generated strings for responses of "ok," "no
591  * support for TLS," and "error" so that we can use this in any protocol.
592  */
593 void CtdlStartTLS(char *ok_response, char *nosup_response,
594                         char *error_response) {
595
596         int retval, bits, alg_bits;
597
598         if (!ssl_ctx) {
599                 syslog(LOG_CRIT, "SSL failed: no ssl_ctx exists?");
600                 if (nosup_response != NULL) cprintf("%s", nosup_response);
601                 return;
602         }
603         if (!(CC->ssl = SSL_new(ssl_ctx))) {
604                 syslog(LOG_CRIT, "SSL_new failed: %s",
605                                 ERR_reason_error_string(ERR_get_error()));
606                 if (error_response != NULL) cprintf("%s", error_response);
607                 return;
608         }
609         if (!(SSL_set_fd(CC->ssl, CC->client_socket))) {
610                 syslog(LOG_CRIT, "SSL_set_fd failed: %s", ERR_reason_error_string(ERR_get_error()));
611                 SSL_free(CC->ssl);
612                 CC->ssl = NULL;
613                 if (error_response != NULL) cprintf("%s", error_response);
614                 return;
615         }
616         if (ok_response != NULL) cprintf("%s", ok_response);
617         retval = SSL_accept(CC->ssl);
618         if (retval < 1) {
619                 /*
620                  * Can't notify the client of an error here; they will
621                  * discover the problem at the SSL layer and should
622                  * revert to unencrypted communications.
623                  */
624                 long errval;
625                 char error_string[128];
626
627                 errval = SSL_get_error(CC->ssl, retval);
628                 syslog(LOG_CRIT, "SSL_accept failed: retval=%d, errval=%ld, err=%s",
629                         retval,
630                         errval,
631                         ERR_error_string(errval, error_string)
632                 );
633                 SSL_free(CC->ssl);
634                 CC->ssl = NULL;
635                 return;
636         }
637         BIO_set_close(CC->ssl->rbio, BIO_NOCLOSE);
638         bits = SSL_CIPHER_get_bits(SSL_get_current_cipher(CC->ssl), &alg_bits);
639         syslog(LOG_INFO, "SSL/TLS using %s on %s (%d of %d bits)",
640                 SSL_CIPHER_get_name(SSL_get_current_cipher(CC->ssl)),
641                 SSL_CIPHER_get_version(SSL_get_current_cipher(CC->ssl)),
642                 bits, alg_bits);
643         CC->redirect_ssl = 1;
644 }
645
646
647 /*
648  * cmd_stls() starts SSL/TLS encryption for the current session
649  */
650 void cmd_stls(char *params)
651 {
652         char ok_response[SIZ];
653         char nosup_response[SIZ];
654         char error_response[SIZ];
655
656         unbuffer_output();
657
658         sprintf(ok_response,
659                 "%d Begin TLS negotiation now\n",
660                 CIT_OK);
661         sprintf(nosup_response,
662                 "%d TLS not supported here\n",
663                 ERROR + CMD_NOT_SUPPORTED);
664         sprintf(error_response,
665                 "%d TLS negotiation error\n",
666                 ERROR + INTERNAL_ERROR);
667
668         CtdlStartTLS(ok_response, nosup_response, error_response);
669 }
670
671
672 /*
673  * cmd_gtls() returns status info about the TLS connection
674  */
675 void cmd_gtls(char *params)
676 {
677         int bits, alg_bits;
678
679         if (!CC->ssl || !CC->redirect_ssl) {
680                 cprintf("%d Session is not encrypted.\n", ERROR);
681                 return;
682         }
683         bits =
684             SSL_CIPHER_get_bits(SSL_get_current_cipher(CC->ssl),
685                                 &alg_bits);
686         cprintf("%d %s|%s|%d|%d\n", CIT_OK,
687                 SSL_CIPHER_get_version(SSL_get_current_cipher(CC->ssl)),
688                 SSL_CIPHER_get_name(SSL_get_current_cipher(CC->ssl)),
689                 alg_bits, bits);
690 }
691
692
693 /*
694  * endtls() shuts down the TLS connection
695  *
696  * WARNING:  This may make your session vulnerable to a known plaintext
697  * attack in the current implmentation.
698  */
699 void endtls(void)
700 {
701         if (!CC->ssl) {
702                 CC->redirect_ssl = 0;
703                 return;
704         }
705
706         syslog(LOG_INFO, "Ending SSL/TLS");
707         SSL_shutdown(CC->ssl);
708         SSL_free(CC->ssl);
709         CC->ssl = NULL;
710         CC->redirect_ssl = 0;
711 }
712
713
714 /*
715  * ssl_lock() callback for OpenSSL mutex locks
716  */
717 void ssl_lock(int mode, int n, const char *file, int line)
718 {
719         if (mode & CRYPTO_LOCK)
720                 pthread_mutex_lock(SSLCritters[n]);
721         else
722                 pthread_mutex_unlock(SSLCritters[n]);
723 }
724 #endif                          /* HAVE_OPENSSL */