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