More removal of $Id$ tags
[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         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                 CtdlLogPrintf(CTDL_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                 CtdlLogPrintf(CTDL_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                                 CtdlLogPrintf(CTDL_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                 CtdlLogPrintf(CTDL_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                 CtdlLogPrintf(CTDL_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                 CtdlLogPrintf(CTDL_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                 CtdlLogPrintf(CTDL_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                 CtdlLogPrintf(CTDL_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                 CtdlLogPrintf(CTDL_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                         CtdlLogPrintf(CTDL_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                                         CtdlLogPrintf(CTDL_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                 CtdlLogPrintf(CTDL_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                                                 CtdlLogPrintf(CTDL_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                         CtdlLogPrintf(CTDL_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                 CtdlLogPrintf(CTDL_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                                                 CtdlLogPrintf(CTDL_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                 CtdlLogPrintf(CTDL_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                                 CtdlLogPrintf(CTDL_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                         CtdlLogPrintf(CTDL_DEBUG, "SSL_write got error %ld, ret %d\n", errval, retval);
421                         if (retval == -1)
422                                 CtdlLogPrintf(CTDL_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                                 CtdlLogPrintf(CTDL_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                         CtdlLogPrintf(CTDL_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, retlen;
475         int nSuccessLess = 0;
476         const char *pch = NULL;
477         
478         retlen = 0;
479         if ((Line == NULL) ||
480             (Pos == NULL) ||
481             (IOBuf == NULL))
482         {
483                 if (Pos != NULL)
484                         *Pos = NULL;
485 //              *Error = ErrRBLF_PreConditionFailed;
486                 return -1;
487         }
488
489         pos = *Pos;
490         if ((StrLength(IOBuf) > 0) && 
491             (pos != NULL) && 
492             (pos < ChrPtr(IOBuf) + StrLength(IOBuf))) 
493         {
494                 pch = pos;
495                 pch = strchr(pch, '\n');
496                 
497                 if (pch == NULL) {
498                         StrBufAppendBufPlain(Line, pos, 
499                                              StrLength(IOBuf) - (pos - ChrPtr(IOBuf)), 0);
500                         FlushStrBuf(IOBuf);
501                         pos = *Pos = NULL;
502                 }
503                 else {
504                         int n = 0;
505                         if ((pch > ChrPtr(IOBuf)) && 
506                             (*(pch - 1) == '\r')) {
507                                 n = 1;
508                         }
509                         StrBufAppendBufPlain(Line, pos, 
510                                              (pch - pos - n), 0);
511
512                         if (StrLength(IOBuf) <= (pch - ChrPtr(IOBuf) + 1)) {
513                                 FlushStrBuf(IOBuf);
514                                 pos = *Pos = NULL;
515                         }
516                         else 
517                                 *Pos = pch + 1;
518                         return StrLength(Line);
519                 }
520         }
521
522         pLF = NULL;
523         while ((nSuccessLess < timeout) && 
524                (pLF == NULL) &&
525                (CCC->ssl != NULL)) {
526
527                 rlen = client_read_sslbuffer(IOBuf, timeout);
528                 if (rlen < 1) {
529 //                      *Error = strerror(errno);
530 //                      close(*fd);
531 //                      *fd = -1;
532                         return -1;
533                 }
534                 else if (rlen > 0) {
535                         pLF = strchr(ChrPtr(IOBuf), '\n');
536                 }
537         }
538         *Pos = NULL;
539         if (pLF != NULL) {
540                 pos = ChrPtr(IOBuf);
541                 len = pLF - pos;
542                 if (len > 0 && (*(pLF - 1) == '\r') )
543                         len --;
544                 StrBufAppendBufPlain(Line, pos, len, 0);
545                 if (pLF + 1 >= ChrPtr(IOBuf) + StrLength(IOBuf))
546                 {
547                         FlushStrBuf(IOBuf);
548                 }
549                 else 
550                         *Pos = pLF + 1;
551                 return StrLength(Line);
552         }
553 //      *Error = ErrRBLF_NotEnoughSentFromServer;
554         return -1;
555 }
556
557
558
559 int client_read_sslblob(StrBuf *Target, long bytes, int timeout)
560 {
561         long baselen;
562         long RemainRead;
563         int retval = 0;
564         CitContext *CCC = CC;
565
566         baselen = StrLength(Target);
567
568         if (StrLength(CCC->ReadBuf) > 0)
569         {
570                 long RemainLen;
571                 long TotalLen;
572                 const char *pchs;
573
574                 if (CCC->Pos == NULL)
575                         CCC->Pos = ChrPtr(CCC->ReadBuf);
576                 pchs = ChrPtr(CCC->ReadBuf);
577                 TotalLen = StrLength(CCC->ReadBuf);
578                 RemainLen = TotalLen - (pchs - CCC->Pos);
579                 if (RemainLen > bytes)
580                         RemainLen = bytes;
581                 if (RemainLen > 0)
582                 {
583                         StrBufAppendBufPlain(Target, 
584                                              CCC->Pos, 
585                                              RemainLen, 0);
586                         CCC->Pos += RemainLen;
587                 }
588                 if ((ChrPtr(CCC->ReadBuf) + StrLength(CCC->ReadBuf)) <= CCC->Pos)
589                 {
590                         CCC->Pos = NULL;
591                         FlushStrBuf(CCC->ReadBuf);
592                 }
593         }
594
595         if (StrLength(Target) >= bytes + baselen)
596                 return 1;
597
598         CCC->Pos = NULL;
599
600         while ((StrLength(Target) < bytes + baselen) &&
601                (retval >= 0))
602         {
603                 retval = client_read_sslbuffer(CCC->ReadBuf, timeout);
604                 if (retval >= 0) {
605                         RemainRead = bytes - (StrLength (Target) - baselen);
606                         if (RemainRead > StrLength(CCC->ReadBuf))
607                         {
608                                 StrBufAppendBufPlain(
609                                         Target, 
610                                         ChrPtr(CCC->ReadBuf), 
611                                         RemainRead, 0);
612                                 CCC->Pos = ChrPtr(CCC->ReadBuf) + RemainRead;
613                                 break;
614                         }
615                         StrBufAppendBuf(Target, CCC->ReadBuf, 0); /* todo: Buf > bytes? */
616                         FlushStrBuf(CCC->ReadBuf);
617                 }
618                 else 
619                 {
620                         FlushStrBuf(CCC->ReadBuf);
621                         return -1;
622         
623                 }
624         }
625         return 1;
626 }
627
628
629 /*
630  * CtdlStartTLS() starts SSL/TLS encryption for the current session.  It
631  * must be supplied with pre-generated strings for responses of "ok," "no
632  * support for TLS," and "error" so that we can use this in any protocol.
633  */
634 void CtdlStartTLS(char *ok_response, char *nosup_response,
635                         char *error_response) {
636
637         int retval, bits, alg_bits;
638
639         if (!ssl_ctx) {
640                 CtdlLogPrintf(CTDL_CRIT, "SSL failed: no ssl_ctx exists?\n");
641                 if (nosup_response != NULL) cprintf("%s", nosup_response);
642                 return;
643         }
644         if (!(CC->ssl = SSL_new(ssl_ctx))) {
645                 CtdlLogPrintf(CTDL_CRIT, "SSL_new failed: %s\n",
646                                 ERR_reason_error_string(ERR_get_error()));
647                 if (error_response != NULL) cprintf("%s", error_response);
648                 return;
649         }
650         if (!(SSL_set_fd(CC->ssl, CC->client_socket))) {
651                 CtdlLogPrintf(CTDL_CRIT, "SSL_set_fd failed: %s\n",
652                         ERR_reason_error_string(ERR_get_error()));
653                 SSL_free(CC->ssl);
654                 CC->ssl = NULL;
655                 if (error_response != NULL) cprintf("%s", error_response);
656                 return;
657         }
658         if (ok_response != NULL) cprintf("%s", ok_response);
659         retval = SSL_accept(CC->ssl);
660         if (retval < 1) {
661                 /*
662                  * Can't notify the client of an error here; they will
663                  * discover the problem at the SSL layer and should
664                  * revert to unencrypted communications.
665                  */
666                 long errval;
667                 char error_string[128];
668
669                 errval = SSL_get_error(CC->ssl, retval);
670                 CtdlLogPrintf(CTDL_CRIT, "SSL_accept failed: retval=%d, errval=%ld, err=%s\n",
671                         retval,
672                         errval,
673                         ERR_error_string(errval, error_string)
674                 );
675                 SSL_free(CC->ssl);
676                 CC->ssl = NULL;
677                 return;
678         }
679         BIO_set_close(CC->ssl->rbio, BIO_NOCLOSE);
680         bits = SSL_CIPHER_get_bits(SSL_get_current_cipher(CC->ssl), &alg_bits);
681         CtdlLogPrintf(CTDL_INFO, "SSL/TLS using %s on %s (%d of %d bits)\n",
682                 SSL_CIPHER_get_name(SSL_get_current_cipher(CC->ssl)),
683                 SSL_CIPHER_get_version(SSL_get_current_cipher(CC->ssl)),
684                 bits, alg_bits);
685         CC->redirect_ssl = 1;
686 }
687
688
689 /*
690  * cmd_stls() starts SSL/TLS encryption for the current session
691  */
692 void cmd_stls(char *params)
693 {
694         char ok_response[SIZ];
695         char nosup_response[SIZ];
696         char error_response[SIZ];
697
698         unbuffer_output();
699
700         sprintf(ok_response,
701                 "%d Begin TLS negotiation now\n",
702                 CIT_OK);
703         sprintf(nosup_response,
704                 "%d TLS not supported here\n",
705                 ERROR + CMD_NOT_SUPPORTED);
706         sprintf(error_response,
707                 "%d TLS negotiation error\n",
708                 ERROR + INTERNAL_ERROR);
709
710         CtdlStartTLS(ok_response, nosup_response, error_response);
711 }
712
713
714 /*
715  * cmd_gtls() returns status info about the TLS connection
716  */
717 void cmd_gtls(char *params)
718 {
719         int bits, alg_bits;
720
721         if (!CC->ssl || !CC->redirect_ssl) {
722                 cprintf("%d Session is not encrypted.\n", ERROR);
723                 return;
724         }
725         bits =
726             SSL_CIPHER_get_bits(SSL_get_current_cipher(CC->ssl),
727                                 &alg_bits);
728         cprintf("%d %s|%s|%d|%d\n", CIT_OK,
729                 SSL_CIPHER_get_version(SSL_get_current_cipher(CC->ssl)),
730                 SSL_CIPHER_get_name(SSL_get_current_cipher(CC->ssl)),
731                 alg_bits, bits);
732 }
733
734
735 /*
736  * endtls() shuts down the TLS connection
737  *
738  * WARNING:  This may make your session vulnerable to a known plaintext
739  * attack in the current implmentation.
740  */
741 void endtls(void)
742 {
743         if (!CC->ssl) {
744                 CC->redirect_ssl = 0;
745                 return;
746         }
747
748         CtdlLogPrintf(CTDL_INFO, "Ending SSL/TLS\n");
749         SSL_shutdown(CC->ssl);
750         SSL_free(CC->ssl);
751         CC->ssl = NULL;
752         CC->redirect_ssl = 0;
753 }
754
755
756 /*
757  * ssl_lock() callback for OpenSSL mutex locks
758  */
759 void ssl_lock(int mode, int n, const char *file, int line)
760 {
761         if (mode & CRYPTO_LOCK)
762                 pthread_mutex_lock(SSLCritters[n]);
763         else
764                 pthread_mutex_unlock(SSLCritters[n]);
765 }
766 #endif                          /* HAVE_OPENSSL */