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