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