6df7507f34a90399e6640879a57c84017beb1edc
[ckermit.git] / ck_ssl.c
1 char *cksslv = "SSL/TLS support, 9.0.232, 5 Feb 2015";
2 /*
3   C K _ S S L . C --  OpenSSL Interface for C-Kermit
4
5   Copyright (C) 1985, 2015,
6     Trustees of Columbia University in the City of New York.
7     All rights reserved.  See the C-Kermit COPYING.TXT file or the
8     copyright text in the ckcmai.c module for disclaimer and permissions.
9
10     Author:  Jeffrey E Altman (jaltman@secure-endpoints.com)
11                Secure Endpoints Inc., New York City
12
13   Provides:
14
15   . Telnet Auth SSL option compatible with Tim Hudson's hack.
16   . Telnet START_TLS option
17   . Configuration of certificate and key files
18   . Certificate verification and revocation list checks
19   . Client certificate to user id routine
20
21   Note: This code is written to be compatible with OpenSSL 0.9.6[abcdefgh]
22   and 0.9.7 beta 5 and later, and (since July 2012) 1.0.x.
23   It will also compile with version 0.9.5 although that is discouraged
24   due to security weaknesses in that release.
25 */
26
27 #include "ckcsym.h"
28 #include "ckcdeb.h"
29
30 #ifdef CK_SSL
31 #include "ckcnet.h"
32 #include "ckuath.h"
33
34 #include <stdlib.h>
35 #include <string.h>
36 #ifdef UNIX
37 #include <netinet/in.h>
38 #ifndef FREEBSD4
39 #include <arpa/inet.h>
40 #endif /* FREEBSD4 */
41 #endif /* UNIX */
42
43 #ifdef DEC_TCPIP
44 #include <time.h>
45 #include <inet.h>
46 #endif /* DEC_TCPIP */
47
48 #ifdef OS2
49 extern char exedir[];
50 #ifdef NT
51 char * GetAppData(int);
52 #endif
53 #endif /* OS2 */
54
55 extern int quiet;                       /* fdc - Mon Nov 28 11:44:15 2005 */
56
57 static int ssl_installed = 1;
58 #endif /* CK_SSL */
59 int
60 ck_ssh_is_installed()
61 {
62 #ifdef SSHBUILTIN
63 #ifdef SSLDLL
64 #ifdef NT
65     extern HINSTANCE hCRYPTO;
66 #else /* NT */
67     extern HMODULE hCRYPTO;
68 #endif /* NT */
69     debug(F111,"ck_ssh_is_installed","hCRYPTO",hCRYPTO);
70     return(ssl_installed && (hCRYPTO != NULL));
71 #else /* SSLDLL */
72     return(ssl_installed);
73 #endif /* SSLDLL */
74 #else
75     return 0;
76 #endif
77 }
78
79 int
80 #ifdef CK_ANSIC
81 ck_ssleay_is_installed(void)
82 #else
83 ck_ssleay_is_installed()
84 #endif
85 {
86 #ifdef CK_SSL
87 #ifdef SSLDLL
88 #ifdef NT
89     extern HINSTANCE hSSL, hCRYPTO;
90 #else /* NT */
91     extern HMODULE hSSL, hCRYPTO;
92 #endif /* NT */
93     debug(F111,"ck_ssleay_is_installed","hSSL",hSSL);
94     debug(F111,"ck_ssleay_is_installed","hCRYPTO",hCRYPTO);
95     return(ssl_installed && (hSSL != NULL) && (hCRYPTO != NULL));
96 #else /* SSLDLL */
97     return(ssl_installed);
98 #endif /* SSLDLL */
99 #else /* CK_SSL */
100     return(0);
101 #endif /* CK_SSL */
102 }
103
104 #ifdef CK_SSL
105 #include "ckcker.h"
106 #include "ckucmd.h"                             /* For struct keytab */
107 #include "ckctel.h"
108 #include "ck_ssl.h"
109 #ifdef UNIX
110 #include <pwd.h>                    /* Password file for home directory */
111 #endif /* UNIX */
112 #ifdef OS2
113 #include <process.h>
114 #endif /* OS2 */
115 #ifdef OS2ONLY
116 #include "ckotcp.h"
117 #endif /* OS2ONLY */
118
119 #ifdef SSLDLL
120 int ssl_finished_messages = 0;
121 #else /* SSLDLL */
122 #ifdef OPENSSL_VERSION_NUMBER
123 int ssl_finished_messages = (OPENSSL_VERSION_NUMBER >= 0x0090581fL);
124 #else
125 !ERROR This module requires OpenSSL 0.9.5a or higher
126 #endif /* OPENSSL_VERSION_NUMBER */
127 #endif /* SSLDLL */
128
129 static int auth_ssl_valid = 0;
130 static char *auth_ssl_name = 0;    /* this holds the oneline name */
131 char ssl_err[SSL_ERR_BFSZ]="";
132
133 BIO *bio_err=NULL;
134 X509_STORE *crl_store = NULL;
135
136 #ifndef NOFTP
137 #ifndef SYSFTP
138 SSL *ssl_ftp_con             = NULL;
139 SSL_CTX *ssl_ftp_ctx         = NULL;
140 SSL *ssl_ftp_data_con        = NULL;
141 int ssl_ftp_active_flag      = 0;
142 int ssl_ftp_data_active_flag = 0;
143 #endif /* SYSFTP */
144 #endif /* NOFTP */
145
146 #ifndef NOHTTP
147 SSL *tls_http_con            = NULL;
148 SSL_CTX *tls_http_ctx        = NULL;
149 int tls_http_active_flag     = 0;
150 int ssl_http_initialized = 0;
151 #endif /* NOHTTP */
152
153 SSL_CTX *ssl_ctx = NULL;
154 SSL *ssl_con = NULL;
155 int ssl_debug_flag = 0;
156 int ssl_verbose_flag = 0;
157 int ssl_only_flag = 0;
158 int ssl_raw_flag = 0;
159 int ssl_active_flag = 0;
160 int ssl_verify_flag = SSL_VERIFY_PEER;
161 int ssl_certsok_flag = 0;
162 char *ssl_rsa_cert_file = NULL;
163 char *ssl_rsa_cert_chain_file = NULL;
164 char *ssl_rsa_key_file = NULL;
165 char *ssl_dsa_cert_file = NULL;
166 char *ssl_dsa_cert_chain_file = NULL;
167 char *ssl_dh_key_file = NULL;
168 char *ssl_crl_file = NULL;
169 char *ssl_crl_dir = NULL;
170 char *ssl_verify_file = NULL;
171 char *ssl_verify_dir = NULL;
172 char *ssl_dh_param_file = NULL;
173 char *ssl_cipher_list = NULL;
174 char *ssl_rnd_file = NULL;
175
176 SSL_CTX *tls_ctx = NULL;
177 SSL *tls_con = NULL;
178 int tls_only_flag = 0;
179 int tls_raw_flag = 0;
180 int tls_active_flag = 0;
181
182 int ssl_initialized = 0;
183 int ssl_verify_depth = -1; /* used to track depth in verify routines */
184
185 /* compile this set to 1 to negotiate SSL/TLS but not actually start it */
186 int ssl_dummy_flag=0;
187
188 extern int inserver;
189 extern int debses;
190 extern int accept_complete;
191 extern char szHostName[], szUserNameRequested[], szUserNameAuthenticated[];
192
193 _PROTOTYP(int X509_to_user,(X509 *, char *, int));
194
195 static int verbosity = 0;               /* Message control */
196 static VOID
197 setverbosity() {
198     verbosity = ssl_verbose_flag;
199     if (quiet) verbosity = 0;
200 }
201
202 int
203 #ifdef CK_ANSIC
204 ssl_server_verify_callback(int ok, X509_STORE_CTX * ctx)
205 #else /* CK_ANSIC */
206 ssl_server_verify_callback(ok, ctx)
207 int ok;
208 X509_STORE_CTX *ctx;
209 #endif /* CK_ANSIC */
210 {
211     static char *saved_subject=NULL;
212     char *subject=NULL, *issuer=NULL;
213     int depth,error;
214     X509 *xs = NULL;
215
216     if ( ssl_certsok_flag )
217         return(1);
218
219     setverbosity();
220
221     error=X509_STORE_CTX_get_error(ctx);
222     depth=X509_STORE_CTX_get_error_depth(ctx);
223     xs=X509_STORE_CTX_get_current_cert(ctx);
224
225     if (depth==0) {
226         /* clear things */
227         if (saved_subject!=NULL) {
228             free(saved_subject);
229             saved_subject=NULL;
230         }
231         if (auth_ssl_name!=NULL) {
232             free(auth_ssl_name);
233             auth_ssl_name=NULL;
234         }
235     }
236
237
238     if (ssl_debug_flag && !inserver) {
239         printf("ssl:server_verify_callback:depth=%d ok=%d err=%d-%s\r\n",
240             depth,ok,error,X509_verify_cert_error_string(error));
241     }
242
243     /* first thing is to have a meaningful name for the current
244      * certificate that is being verified ... and if we cannot
245      * determine that then something is seriously wrong!
246      */
247     makestr(&subject,
248             (char *)X509_NAME_oneline(X509_get_subject_name(xs),NULL,0));
249     makestr(&issuer,
250             (char *)X509_NAME_oneline(X509_get_issuer_name(xs),NULL,0));
251     if (!subject || !subject[0] || !issuer || !issuer[0]) {
252         ok = 0;
253         goto return_time;
254     }
255
256     if (verbosity && !inserver && depth != ssl_verify_depth) {
257         printf("[%d] Certificate Subject:\r\n%s\r\n",depth,subject);
258         printf("[%d] Certificate Issuer:\r\n%s\r\n",depth,issuer);
259         ssl_verify_depth = depth;
260     }
261
262     /* make sure that the certificate that has been presented */
263     /* has not been revoked (if we have been given a CRL.     */
264     ok =  ssl_verify_crl(ok, ctx);
265
266     /* if we have any form of error in secure mode we reject the connection */
267     if (error!=X509_V_OK) {
268         if (inserver) {
269 #ifdef CKSYSLOG
270             if (ckxsyslog >= SYSLG_LI && ckxlogging) {
271                 cksyslog(SYSLG_LI, 0,
272                           "X.509 Certificate verify failure",
273                           (char *) subject,
274                           (char *)X509_verify_cert_error_string(error)
275                           );
276             }
277 #endif /* CKSYSLOG */
278
279         } else {
280             if ( ssl_verify_flag &
281                  (SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT))
282                 printf("Error: ");
283             else
284                 printf("Warning: ");
285             switch (error) {
286             case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
287                 printf("Certificate is self signed.\r\n");
288                 break;
289             case X509_V_ERR_CERT_HAS_EXPIRED:
290                 printf("Certificate has expired.\r\n");
291                 break;
292             case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:
293                 printf(
294   "Certificate issuer's certificate isn't available locally.\r\n");
295                 break;
296             case X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE:
297                 printf("Unable to verify leaf signature.\r\n");
298                 break;
299             case X509_V_ERR_CERT_REVOKED:
300                 printf("Certificate revoked.\r\n");
301                 break;
302             default:
303                 printf("Error %d while verifying certificate.\r\n",
304                        ctx->error);
305                 break;
306             }
307         }
308         ok = !(ssl_verify_flag & SSL_VERIFY_FAIL_IF_NO_PEER_CERT);
309     } else {
310         /* if we got all the way to the top of the tree then
311          * we *can* use this certificate for a username to
312          * match ... in all other cases we must not!
313          */
314         auth_ssl_name = saved_subject;
315         saved_subject = NULL;
316     }
317
318   return_time:
319
320     /* save the name if at least the first level is okay */
321     if (depth == 0 && ok)
322         makestr(&saved_subject,subject);
323
324     /* clean up things */
325     if (subject!=NULL)
326         free(subject);
327     if (issuer!=NULL)
328         free(issuer);
329
330     return ok;
331 }
332
333 int
334 #ifdef CK_ANSIC
335 ssl_client_verify_callback(int ok, X509_STORE_CTX * ctx)
336 #else
337 ssl_client_verify_callback(ok, ctx)
338 int ok;
339 X509_STORE_CTX *ctx;
340 #endif
341 {
342     char subject[256]="", issuer[256]="";
343     int depth, error, len;
344     X509 *xs;
345
346     setverbosity();
347
348     xs=X509_STORE_CTX_get_current_cert(ctx);
349     error=X509_STORE_CTX_get_error(ctx);
350     depth=X509_STORE_CTX_get_error_depth(ctx);
351
352     if ( ssl_debug_flag )
353         printf("ssl:client_verify_callback:depth=%d ok=%d err=%d-%s\r\n",
354                 depth,ok,error,X509_verify_cert_error_string(error));
355
356     if ( ssl_certsok_flag ) {
357         ok = 1;
358     }
359
360     /* first thing is to have a meaningful name for the current
361      * certificate that is being verified ... and if we cannot
362      * determine that then something is seriously wrong!
363      */
364 #ifdef XN_FLAG_SEP_MULTILINE
365     X509_NAME_print_ex(bio_err,X509_get_subject_name(xs),4,
366                         XN_FLAG_SEP_MULTILINE);
367     len = BIO_read(bio_err,subject,256);
368     subject[len < 256 ? len : 255] = '\0';
369     if (!subject[0]) {
370         ERR_print_errors(bio_err);
371         len = BIO_read(bio_err,ssl_err,SSL_ERR_BFSZ);
372         ssl_err[len < SSL_ERR_BFSZ ? len : SSL_ERR_BFSZ] = '\0';
373         uq_ok("X.509 Subject Name unavailable", ssl_err, 1, NULL, 0);
374         ok=0;
375         goto return_time;
376     }
377
378     X509_NAME_print_ex(bio_err,X509_get_issuer_name(xs),4,
379                         XN_FLAG_SEP_MULTILINE);
380     len = BIO_read(bio_err,issuer,256);
381     issuer[len < 256 ? len : 255] = '\0';
382     if (!issuer[0]) {
383         ERR_print_errors(bio_err);
384         len = BIO_read(bio_err,ssl_err,SSL_ERR_BFSZ);
385         ssl_err[len < SSL_ERR_BFSZ ? len : SSL_ERR_BFSZ] = '\0';
386         uq_ok("X.509 Issuer Name unavailable", ssl_err, 1, NULL, 0);
387         ok=0;
388         goto return_time;
389     }
390 #else /* XN_FLAG_SEP_MULTILINE */
391     X509_NAME_oneline(X509_get_subject_name(xs),subject,256);
392     if (!subject[0]) {
393         int len;
394         ERR_print_errors(bio_err);
395         len = BIO_read(bio_err,ssl_err,SSL_ERR_BFSZ);
396         ssl_err[len < SSL_ERR_BFSZ ? len : SSL_ERR_BFSZ] = '\0';
397         uq_ok("X.509 Subject Name unavailable", ssl_err, 1, NULL, 0);
398         ok=0;
399         goto return_time;
400     }
401
402     X509_NAME_oneline(X509_get_issuer_name(xs),issuer,256);
403     if (!issuer[0]) {
404         int len;
405         ERR_print_errors(bio_err);
406         len = BIO_read(bio_err,ssl_err,SSL_ERR_BFSZ);
407         ssl_err[len < SSL_ERR_BFSZ ? len : SSL_ERR_BFSZ] = '\0';
408         uq_ok("X.509 Issuer Name unavailable", ssl_err, 1, NULL, 0);
409         ok=0;
410         goto return_time;
411     }
412 #endif /* XN_FLAG_SEP_MULTILINE */
413
414     if (verbosity && depth != ssl_verify_depth) {
415         printf("[%d] Certificate Subject:\r\n%s\r\n",depth,subject);
416         printf("[%d] Certificate Issuer:\r\n%s\r\n",depth,issuer);
417         ssl_verify_depth = depth;
418     }
419
420     ok = ssl_verify_crl(ok, ctx);
421
422     if ( !ok ) {
423         char prefix[1024];
424         /* if the server is using a self signed certificate then
425          * we need to decide if that is good enough for us to
426          * accept ...
427          */
428
429         switch ( error ) {
430         case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT: {
431             if (ssl_verify_flag & SSL_VERIFY_FAIL_IF_NO_PEER_CERT) {
432                 /* make 100% sure that in secure more we drop the
433                  * connection if the server does not have a
434                  * real certificate!
435                  */
436                 ckmakxmsg(prefix,1024,
437                            "Error: Server has a self-signed certificate\n",
438                            "[",ckitoa(depth),"] Certificate Subject=\n",subject,
439                            "\n[",ckitoa(depth),"] Certificate Issuer=\n",issuer,
440                            NULL,NULL,NULL);
441
442                 uq_ok(prefix, "Rejecting Connection", 1, NULL, 0);
443
444                 /* sometimes it is really handy to be able to debug things
445                 * and still get a connection!
446                 */
447                 if (ssl_debug_flag) {
448                     printf("SSL: debug -> ignoring cert required!\r\n");
449                     ok=1;
450                 } else {
451                     ok=0;
452                 }
453                 goto return_time;
454             } else if (ssl_verify_flag != SSL_VERIFY_NONE) {
455                 ckmakxmsg(prefix,1024,
456                            "Warning: Server has a self-signed certificate\n",
457                            "[",ckitoa(depth),"] Certificate Subject=\n",subject,
458                            "\n[",ckitoa(depth),"] Certificate Issuer=\n",issuer,
459                            NULL,NULL,NULL);
460
461                 ok = uq_ok(prefix,
462                            "Continue? (Y/N) ",
463                            3, NULL, 0);
464                 if ( ok < 0 )
465                     ok = 0;
466                 goto return_time;
467             }
468         }
469         case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
470             if (ssl_verify_flag & SSL_VERIFY_FAIL_IF_NO_PEER_CERT) {
471                 /* make 100% sure that in secure more we drop the
472                  * connection if the server does not have a
473                  * real certificate!
474                  */
475                 ckmakxmsg(prefix,1024,
476                            "Error: ",
477                            (char *)X509_verify_cert_error_string(error),
478                            "\nCertificate Issuer=\n",issuer,
479                            NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL);
480                 uq_ok(prefix, "Rejecting Connection", 1, NULL, 0);
481
482                 /* sometimes it is really handy to be able to debug things
483                 * and still get a connection!
484                 */
485                 if (ssl_debug_flag) {
486                     printf("SSL: debug -> ignoring cert required!\r\n");
487                     ok=1;
488                 } else {
489                     ok=0;
490                 }
491                 goto return_time;
492             } else if (ssl_verify_flag != SSL_VERIFY_NONE) {
493                 ckmakxmsg(prefix,1024,
494                            "Warning: ",
495                            (char *)X509_verify_cert_error_string(error),
496                            "\nCertificate Issuer=\n",issuer,
497                            NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL);
498                 ok = uq_ok(prefix, "Continue (Y/N)", 3, NULL, 0);
499                 goto return_time;
500             }
501             break;
502         case X509_V_ERR_CERT_NOT_YET_VALID:
503         case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
504             if (ssl_verify_flag & SSL_VERIFY_FAIL_IF_NO_PEER_CERT) {
505                 int len;
506                 /* make 100% sure that in secure more we drop the
507                  * connection if the server does not have a
508                  * real certificate!
509                  */
510                 ASN1_TIME_print(bio_err,X509_get_notBefore(xs));
511                 len = BIO_read(bio_err,ssl_err,SSL_ERR_BFSZ);
512                 ssl_err[len < SSL_ERR_BFSZ ? len : SSL_ERR_BFSZ] = '\0';
513                 ckmakxmsg(prefix,1024,
514                            "Error: ",
515                            (char *)X509_verify_cert_error_string(error),
516                            "\nCertificate Subject=\n",subject,
517                            "\nnotBefore=",ssl_err,
518                            NULL,NULL,NULL,NULL,NULL,NULL);
519                 uq_ok(prefix, "Rejecting Connection", 1, NULL, 0);
520                 /* sometimes it is really handy to be able to debug things
521                 * and still get a connection!
522                 */
523                 if (ssl_debug_flag) {
524                     printf("SSL: debug -> ignoring cert required!\r\n");
525                     ok=1;
526                 } else {
527                     ok=0;
528                 }
529                 goto return_time;
530             } else if (ssl_verify_flag != SSL_VERIFY_NONE) {
531                 int len;
532                 ASN1_TIME_print(bio_err,X509_get_notBefore(xs));
533                 len = BIO_read(bio_err,ssl_err,SSL_ERR_BFSZ);
534                 ssl_err[len < SSL_ERR_BFSZ ? len : SSL_ERR_BFSZ] = '\0';
535                 ckmakxmsg(prefix,1024,
536                            "Warning: ",
537                            (char *)X509_verify_cert_error_string(error),
538                            "\nCertificate Subject=\n",subject,
539                            "\n    notBefore=",ssl_err,
540                            NULL,NULL,NULL,NULL,NULL,NULL);
541                 ok = uq_ok(prefix, "Continue (Y/N)", 3, NULL, 0);
542             }
543             break;
544         case X509_V_ERR_CERT_HAS_EXPIRED:
545         case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
546             if (ssl_verify_flag & SSL_VERIFY_FAIL_IF_NO_PEER_CERT) {
547                 int len;
548                 /* make 100% sure that in secure more we drop the
549                  * connection if the server does not have a
550                  * real certificate!
551                  */
552                 ASN1_TIME_print(bio_err,X509_get_notAfter(xs));
553                 len = BIO_read(bio_err,ssl_err,SSL_ERR_BFSZ);
554                 ssl_err[len < SSL_ERR_BFSZ ? len : SSL_ERR_BFSZ] = '\0';
555
556                 ckmakxmsg(prefix,1024,
557                            "Error: ",
558                            (char *)X509_verify_cert_error_string(error),
559                            "\nCertificate Subject=\n",subject,
560                            "\n    notAfter=",ssl_err,
561                            NULL,NULL,NULL,NULL,NULL,NULL);
562                 uq_ok(prefix, "Rejecting Connection", 1, NULL, 0);
563    
564                 /* sometimes it is really handy to be able to debug things
565                 * and still get a connection!
566                 */
567                 if (ssl_debug_flag) {
568                     printf("SSL: debug -> ignoring cert required!\r\n");
569                     ok=1;
570                 } else {
571                     ok=0;
572                 }
573                 goto return_time;
574             } else if (ssl_verify_flag != SSL_VERIFY_NONE) {
575                 int len;
576                 ASN1_TIME_print(bio_err,X509_get_notAfter(xs));
577                 len = BIO_read(bio_err,ssl_err,SSL_ERR_BFSZ);
578                 ssl_err[len < SSL_ERR_BFSZ ? len : SSL_ERR_BFSZ] = '\0';
579                 ckmakxmsg(prefix,1024,
580                            "Warning: ",
581                            (char *)X509_verify_cert_error_string(error),
582                            "\nCertificate Subject=\n",subject,
583                            "\n    notAfter=",ssl_err,
584                            NULL,NULL,NULL,NULL,NULL,NULL);
585                 ok = uq_ok(prefix, "Continue (Y/N)", 3, NULL, 0);
586             }
587             break;
588         case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN:
589         case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:
590             /*
591              * When an SSL server sends its certificates to the client there
592              * are two" conventions": one is to send the complete certificate
593              * chain and the other is to send the whole chain apart from the
594              * root.
595              *
596              * You don't usually need the root because the root is normally
597              * stored and trusted locally.
598              *
599              * So if you get the whole chain it will complain about the self
600              * signed certificate whereas if the root is missing it says it
601              * can't find the issuer certificate.
602              */
603             if (ssl_verify_flag & SSL_VERIFY_FAIL_IF_NO_PEER_CERT) {
604                 /* make 100% sure that in secure more we drop the
605                  * connection if the server does not have a
606                  * real certificate!
607                  */
608                 ckmakxmsg(prefix,1024,
609                            "Error: ",
610                            (char *)X509_verify_cert_error_string(error),
611                            "\nCertificate Issuer=\n",issuer,
612                            NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL);
613                 uq_ok(prefix, "Rejecting Connection", 1, NULL, 0);
614                 /* sometimes it is really handy to be able to debug things
615                 * and still get a connection!
616                 */
617                 if (ssl_debug_flag) {
618                     printf("SSL: debug -> ignoring cert required!\r\n");
619                     ok=1;
620                 } else {
621                     ok=0;
622                 }
623                 goto return_time;
624             } else if (ssl_verify_flag != SSL_VERIFY_NONE) {
625                 ckmakxmsg(prefix,1024,
626                            "Warning: ",
627                            (char *)X509_verify_cert_error_string(error),
628                            "\nCertificate Issuer=\n",issuer,
629                            NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL);
630                 ok = uq_ok(prefix, "Continue (Y/N)", 3, NULL, 0);
631 #ifdef NT
632                 if (ok) {
633                     /* if the user decides to accept the certificate
634                      * offer to store it for future connections in 
635                      * the user's private store
636                      */
637                     ok = uq_ok(
638   "Do you wish to store the certificate to verify future connections?",
639                                "Continue (Y/N)", 3, NULL, 0);
640                     if (ok)
641                         ck_X509_save_cert_to_user_store(xs);
642                 }
643 #endif /* NT */
644             }
645             break;
646         case X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE:
647         case X509_V_ERR_UNABLE_TO_GET_CRL:
648         case X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE:
649         case X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE:
650         case X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY:
651         case X509_V_ERR_CERT_SIGNATURE_FAILURE:
652         case X509_V_ERR_CRL_SIGNATURE_FAILURE:
653         case X509_V_ERR_CRL_NOT_YET_VALID:
654         case X509_V_ERR_CRL_HAS_EXPIRED:
655         case X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD:
656         case X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD:
657         case X509_V_ERR_OUT_OF_MEM:
658         case X509_V_ERR_CERT_CHAIN_TOO_LONG:
659         case X509_V_ERR_CERT_REVOKED:
660         case X509_V_ERR_APPLICATION_VERIFICATION:
661         default:
662             if (ssl_verify_flag & SSL_VERIFY_FAIL_IF_NO_PEER_CERT) {
663                 /* make 100% sure that in secure mode we drop the
664                  * connection if the server does not have a
665                  * real certificate!
666                  */
667                 ckmakxmsg(prefix,1024,
668                            "Error: ",
669                            (char *)X509_verify_cert_error_string(error),
670                            "\nCertificate Subject=\n",subject,
671                            NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL);
672                 uq_ok(prefix, "Rejecting Connection", 1, NULL, 0);
673
674                 /* sometimes it is really handy to be able to debug things
675                 * and still get a connection!
676                 */
677                 if (ssl_debug_flag) {
678                     printf("SSL: debug -> ignoring cert required!\r\n");
679                     ok=1;
680                 } else {
681                     ok=0;
682                 }
683                 goto return_time;
684             } else if (ssl_verify_flag != SSL_VERIFY_NONE) {
685                 ckmakxmsg(prefix,1024,
686                            "Warning: ",
687                            (char *)X509_verify_cert_error_string(error),
688                            "\nCertificate Subject=\n",subject,
689                            NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL);
690                 ok = uq_ok(prefix, "Continue (Y/N)", 3, NULL, 0);
691             }
692             break;
693         }
694     }
695
696   return_time:
697     if ( ssl_debug_flag )
698         printf("ssl:client_verify_callback => ok: %d\r\n",ok);
699     return ok;
700 }
701
702 VOID
703 #ifdef CK_ANSIC
704 ssl_client_info_callback(const SSL *s, int where, int ret)
705 #else
706 ssl_client_info_callback(s,where,ret)
707 const SSL *s;
708 int where;
709 int ret;
710 #endif /* CK_ANSIC */
711 {
712     if (inserver || !ssl_debug_flag)
713         return;
714
715     setverbosity();
716
717     switch ( where ) {
718     case SSL_CB_CONNECT_LOOP:
719         printf("SSL_connect:%s %s\r\n",
720                 SSL_state_string((SSL *)s),SSL_state_string_long((SSL *)s));
721         break;
722     case SSL_CB_CONNECT_EXIT:
723         if (ret == 0) {
724             printf("SSL_connect:failed in %s %s\r\n",
725                     SSL_state_string((SSL *)s),SSL_state_string_long((SSL *)s));
726         } else if (ret < 0) {
727             printf("SSL_connect:error in %s %s\r\n",
728                     SSL_state_string((SSL *)s),SSL_state_string_long((SSL *)s));
729         }
730         break;
731     case SSL_CB_ACCEPT_LOOP:
732         printf("SSL_accept:%s %s\r\n",
733                 SSL_state_string((SSL *)s),SSL_state_string_long((SSL *)s));
734         break;
735     case SSL_CB_ACCEPT_EXIT:
736         if (ret == 0) {
737             printf("SSL_accept:failed in %s %s\r\n",
738                     SSL_state_string((SSL *)s),SSL_state_string_long((SSL *)s));
739         } else if (ret < 0) {
740             printf("SSL_accept:error in %s %s\r\n",
741                     SSL_state_string((SSL *)s),SSL_state_string_long((SSL *)s));
742         }
743         break;
744     case SSL_CB_READ_ALERT:
745         printf("SSL_read_alert\r\n");
746         break;
747     case SSL_CB_WRITE_ALERT:
748         printf("SSL_write_alert\r\n");
749         break;
750     case SSL_CB_HANDSHAKE_START:
751         printf("SSL_handshake:%s %s\r\n",
752                 SSL_state_string((SSL *)s),SSL_state_string_long((SSL *)s));
753         break;
754     case SSL_CB_HANDSHAKE_DONE:
755         printf("SSL_handshake:%s %s\r\n",
756                 SSL_state_string((SSL *)s),SSL_state_string_long((SSL *)s));
757         break;
758     }
759 }
760
761 #ifdef USE_CERT_CB
762 /* Return 1, client cert is available */
763 /* Return 0, no client cert is available */
764 /* Return -1, callback must be called again. SSL_want_x509_lookup() == 1 */
765 int
766 #ifdef CK_ANSIC
767 ssl_client_cert_callback(SSL * s, X509 ** x509, EVP_PKEY ** pkey)
768 #else /* CK_ANSIC */
769 ssl_client_cert_callback(s, x509, pkey)
770     SSL * s;
771     X509 ** x509;
772     EVP_PKEY ** pkey;
773 #endif /* CK_ANSIC */
774 {
775     setverbosity();
776
777     if ( ssl_debug_flag ) {
778         const char * cipher_list=SSL_get_cipher(s);
779         printf("ssl_client_cert_callback called (%s)\r\n",
780                 cipher_list?cipher_list:"UNKNOWN");
781     }
782 #ifdef COMMENT
783     if ( s == tls_con ) {
784         if (tls_load_certs(tls_cts,tls_con,0)) {
785             *x509 = SSL_get_certificate(s);
786             *pkey = SSL_get_privatekey(s);
787             return(1);
788         }
789     } else if ( s == ssl_con ) {
790         if (tls_load_certs(ssl_ctx,ssl_con,0)) {
791             *x509 = SSL_get_certificate(s);
792             *pkey = SSL_get_privatekey(s);
793             return(1);
794         }
795     }
796     return(0);
797 #else /* COMMENT */
798     return(0);
799 #endif /* COMMENT */
800 }
801 #endif /* USE_CERT_CB */
802
803 #ifndef MS_CALLBACK
804 #define MS_CALLBACK
805 #endif /* MS_CALLBACK */
806
807 static RSA MS_CALLBACK *
808 #ifdef CK_ANSIC
809 tmp_rsa_cb(SSL * s, int export, int keylength)
810 #else /* CK_ANSIC */
811 tmp_rsa_cb(s,export,keylength)
812 SSL *s;
813 int export;
814 int keylength;
815 #endif /* CK_ANSIC */
816 {
817     static RSA *rsa_tmp=NULL;
818
819 #ifndef NO_RSA
820     if (rsa_tmp == NULL)
821     {
822         if (ssl_debug_flag)
823             printf("Generating temporary (%d bit) RSA key...\r\n",keylength);
824
825         rsa_tmp=RSA_generate_key(keylength,RSA_F4,NULL,NULL);
826
827         if (ssl_debug_flag)
828             printf("\r\n");
829     }
830 #else /* NO_RSA */
831     if (ssl_debug_flag)
832         printf("Unable to generate temporary RSA key...\r\n");
833 #endif
834     return(rsa_tmp);
835 }
836
837
838 #ifndef NO_DH
839 static unsigned char dh512_p[]={
840     0xE9,0x4E,0x3A,0x64,0xFA,0x65,0x5F,0xA6,0x44,0xC7,0xFC,0xF1,
841     0x16,0x8B,0x11,0x11,0x7A,0xF0,0xB2,0x49,0x80,0x56,0xA3,0xF8,
842     0x0F,0x7D,0x01,0x68,0x5D,0xF6,0x8A,0xEA,0x8C,0xDD,0x01,0xDC,
843     0x43,0x18,0xE0,0xC4,0x89,0x80,0xE6,0x2D,0x44,0x77,0x45,0xFD,
844     0xBA,0xFC,0x43,0x35,0x12,0xC0,0xED,0x32,0xD3,0x16,0xEF,0x51,
845     0x09,0x44,0xA2,0xDB,
846 };
847 static unsigned char dh512_g[]={
848     0x05,
849 };
850
851 static unsigned char dh768_p[]={
852     0x8B,0x2A,0x8C,0x6C,0x0F,0x87,0xC7,0x34,0xEE,0x2E,0xFB,0x60,
853     0x94,0xB3,0xBF,0x95,0xBA,0x84,0x74,0x86,0xEA,0xE0,0xA4,0x33,
854     0xE0,0x8F,0x7C,0x79,0x5C,0x62,0xE2,0x91,0xC5,0x6D,0x68,0xB9,
855     0x6C,0x5E,0x4E,0x94,0x0C,0x8E,0x56,0x8E,0xEB,0x98,0x7C,0x6E,
856     0x0E,0xF2,0xD5,0xAA,0x22,0x27,0x3F,0x0F,0xAF,0x10,0xB5,0x0B,
857     0x16,0xCC,0x05,0x27,0xBB,0x58,0x6D,0x61,0x4B,0x2B,0xAB,0xDC,
858     0x6A,0x15,0xBC,0x36,0x75,0x4D,0xEC,0xAB,0xFA,0xB6,0xE1,0xB1,
859     0x13,0x70,0xD8,0x77,0xCD,0x5E,0x51,0x77,0x81,0x0D,0x77,0x43,
860 };
861 static unsigned char dh768_g[]={
862     0x05,
863 };
864
865 static unsigned char dh1024_p[]={
866     0xA4,0x75,0xCF,0x35,0x00,0xAF,0x3C,0x17,0xCE,0xB0,0xD0,0x52,
867     0x43,0xA0,0x0E,0xFA,0xA2,0xC9,0xBE,0x0B,0x76,0x7A,0xD9,0x2E,
868     0xF4,0x97,0xAC,0x02,0x24,0x69,0xF6,0x36,0x4F,0xAB,0xCC,0x43,
869     0xC1,0x74,0xFF,0xA3,0xD4,0x04,0x0F,0x11,0x2B,0x6D,0x8C,0x47,
870     0xC9,0xCF,0x40,0x93,0x9B,0x7D,0x1E,0x52,0x85,0xB2,0x17,0x55,
871     0x9C,0xF2,0x41,0x02,0x2A,0x9D,0x5F,0x24,0x22,0xC6,0x04,0xC4,
872     0xAB,0x92,0x6D,0xC7,0xC8,0xF3,0x41,0x58,0x6C,0x86,0xFD,0xB8,
873     0x0F,0x2D,0xDD,0xBF,0xA8,0x40,0x0C,0x58,0xC8,0xF2,0x3F,0x18,
874     0xEF,0xF1,0x93,0x3E,0xBA,0x16,0x41,0xBE,0x32,0x6C,0xC5,0x63,
875     0xFF,0x8A,0x02,0x3D,0xAC,0xD5,0x5A,0x49,0x64,0x34,0x14,0x2E,
876     0xFB,0x2E,0xE7,0x39,0x1A,0x0F,0x3C,0x33,
877 };
878 static unsigned char dh1024_g[]={
879     0x05,
880 };
881
882 static unsigned char dh1536_p[]={
883     0xA3,0x2B,0x75,0x0E,0x7B,0x31,0x82,0xCA,0xF2,0xFC,0xF3,0x3D,
884     0xCE,0x5F,0xCD,0x5B,0x95,0xF6,0x2F,0xA4,0x5D,0x08,0x26,0xD2,
885     0x5F,0xC0,0x3F,0xC5,0xD8,0xA2,0xFE,0x83,0x26,0xBC,0xEB,0x7D,
886     0xF0,0x4E,0xD2,0xA6,0xBB,0x3C,0x88,0x63,0xCE,0x98,0xDE,0x08,
887     0xE2,0xE1,0xAF,0xE2,0x38,0xA8,0xFA,0x68,0x76,0x8D,0xBF,0xDF,
888     0xBB,0x30,0x15,0xFE,0xBD,0x22,0xCC,0x03,0x4E,0x5E,0x33,0xA3,
889     0x6D,0xD6,0x68,0x12,0x97,0x17,0x4B,0xB5,0x84,0x5F,0x5F,0xA3,
890     0x5C,0x2F,0xA4,0x10,0xC1,0xAD,0xBF,0xAC,0x30,0xCA,0x47,0x64,
891     0x63,0xFE,0xEE,0xEE,0xA1,0x64,0x73,0x70,0xAA,0xF9,0xFE,0xC6,
892     0xAD,0x5E,0xF6,0xF3,0x9C,0xDF,0x34,0x53,0x34,0x72,0xA6,0xA4,
893     0xBB,0x81,0x5A,0x43,0x41,0xFD,0x41,0x05,0x5B,0x77,0x7B,0x84,
894     0x03,0xFA,0x8A,0xFA,0xF7,0x8E,0x0F,0xCB,0x51,0xA2,0xB8,0x45,
895     0xFF,0x59,0x42,0xEF,0xCF,0xF6,0x25,0x37,0xE2,0x6D,0xFF,0x69,
896     0x11,0xF5,0x77,0x59,0x79,0x1C,0x5F,0x05,0xFC,0x7A,0x65,0x81,
897     0x03,0x4A,0x78,0xC6,0xE9,0x48,0x73,0xF6,0x10,0xBC,0x99,0x1C,
898     0xEE,0x44,0x2F,0x8B,0x70,0xCA,0xA8,0xB6,0x02,0x83,0x3E,0x0B,
899 };
900 static unsigned char dh1536_g[]={
901     0x05,
902 };
903
904 static unsigned char dh2048_p[]={
905     0xFA,0x4E,0xE4,0x3B,0xFA,0xC1,0x87,0xDD,0xE7,0xC6,0x8B,0xE6,
906     0x13,0x85,0xBC,0x9B,0x2B,0x8B,0x5B,0x46,0xBB,0x8B,0x86,0x6D,
907     0xD7,0xB6,0xD5,0x49,0xC5,0x54,0xF2,0x3E,0xD2,0x39,0x64,0x9B,
908     0x0E,0x33,0x39,0x8F,0xFA,0xFA,0xD9,0x78,0xED,0x34,0x82,0x29,
909     0x37,0x58,0x4D,0x5D,0x40,0xCB,0x69,0xE3,0x8A,0x9F,0x17,0x0C,
910     0x01,0x23,0x6B,0x05,0x01,0xAF,0x33,0xDE,0xDF,0x1A,0xBB,0x7B,
911     0x6A,0x9F,0xD8,0xED,0x8D,0x5E,0x44,0x19,0x5B,0xE0,0xB6,0x23,
912     0xF9,0x7A,0x96,0x6E,0x94,0x33,0x31,0x49,0xBA,0x84,0xD5,0x12,
913     0xD7,0x6D,0xDC,0x35,0x54,0x64,0xA3,0xD8,0x04,0x26,0xC5,0xAF,
914     0x7F,0xE3,0xFE,0x6F,0xBE,0xD5,0x17,0x72,0x4B,0xA6,0xD0,0xA7,
915     0x5F,0x18,0xF5,0xF0,0x2D,0x11,0x9A,0xF6,0xD5,0x3B,0x6C,0x61,
916     0x3C,0x6F,0x8E,0x09,0x4F,0x2C,0xE1,0x26,0x06,0x51,0xB3,0x19,
917     0x85,0x85,0x13,0xF9,0xC2,0x6E,0x80,0x28,0x9E,0x8A,0xA0,0x01,
918     0x46,0xD1,0x85,0x44,0x8C,0xE6,0xEE,0x7E,0x1E,0x17,0x3D,0xBA,
919     0x54,0xFF,0xE8,0x0E,0xDD,0x51,0xF3,0x74,0x7F,0x0D,0x0B,0xAB,
920     0xCA,0x84,0x8D,0x24,0x5D,0x56,0xD4,0x47,0x02,0xFC,0x93,0x9F,
921     0xAE,0x9B,0x5C,0xDB,0x63,0xEB,0x65,0x01,0x38,0xC2,0x7B,0x30,
922     0x1E,0x17,0x1C,0x75,0xF5,0x16,0x3B,0x4F,0x5F,0x41,0x32,0xB5,
923     0xFF,0x9E,0x61,0xFD,0xD2,0x62,0x6E,0xFD,0x8A,0x28,0x93,0x59,
924     0x2D,0x70,0x14,0x4D,0xE1,0x86,0xD5,0x90,0xB4,0xDF,0x72,0x71,
925     0xE0,0xB4,0xD0,0xD6,0x82,0x3A,0x4A,0x04,0x58,0x32,0x0B,0xD3,
926     0x51,0x13,0x32,0x63,
927 };
928 static unsigned char dh2048_g[]={
929     0x02,
930 };
931
932 static DH *
933 get_dh512()
934 {
935     DH *dh=NULL;
936
937     if ((dh=DH_new()) == NULL)
938         return(NULL);
939     dh->p=BN_bin2bn(dh512_p,sizeof(dh512_p),NULL);
940     dh->g=BN_bin2bn(dh512_g,sizeof(dh512_g),NULL);
941     if ((dh->p == NULL) || (dh->g == NULL))
942         return(NULL);
943     return(dh);
944 }
945
946 static DH *
947 get_dh768()
948 {
949     DH *dh=NULL;
950
951     if ((dh=DH_new()) == NULL)
952         return(NULL);
953     dh->p=BN_bin2bn(dh768_p,sizeof(dh768_p),NULL);
954     dh->g=BN_bin2bn(dh768_g,sizeof(dh768_g),NULL);
955     if ((dh->p == NULL) || (dh->g == NULL))
956         return(NULL);
957     return(dh);
958 }
959
960 static DH *
961 get_dh1024()
962 {
963     DH *dh=NULL;
964
965     if ((dh=DH_new()) == NULL)
966         return(NULL);
967     dh->p=BN_bin2bn(dh1024_p,sizeof(dh1024_p),NULL);
968     dh->g=BN_bin2bn(dh1024_g,sizeof(dh1024_g),NULL);
969     if ((dh->p == NULL) || (dh->g == NULL))
970         return(NULL);
971     return(dh);
972 }
973
974 static DH *
975 get_dh1536()
976 {
977     DH *dh=NULL;
978
979     if ((dh=DH_new()) == NULL)
980         return(NULL);
981     dh->p=BN_bin2bn(dh1536_p,sizeof(dh1536_p),NULL);
982     dh->g=BN_bin2bn(dh1536_g,sizeof(dh1536_g),NULL);
983     if ((dh->p == NULL) || (dh->g == NULL))
984         return(NULL);
985     return(dh);
986 }
987
988 static DH *
989 get_dh2048()
990 {
991     DH *dh=NULL;
992
993     if ((dh=DH_new()) == NULL)
994         return(NULL);
995     dh->p=BN_bin2bn(dh2048_p,sizeof(dh2048_p),NULL);
996     dh->g=BN_bin2bn(dh2048_g,sizeof(dh2048_g),NULL);
997     if ((dh->p == NULL) || (dh->g == NULL))
998         return(NULL);
999     return(dh);
1000 }
1001 #endif /* NO_DH */
1002
1003 static DH MS_CALLBACK *
1004 #ifdef CK_ANSIC
1005 tmp_dh_cb(SSL * s, int export, int keylength)
1006 #else /* CK_ANSIC */
1007 tmp_dh_cb(s,export,keylength)
1008 SSL *s;
1009 int export;
1010 int keylength;
1011 #endif /* CK_ANSIC */
1012 {
1013     static DH *dh_tmp=NULL;
1014     BIO *bio=NULL;
1015
1016 #ifndef NO_DH
1017     if (dh_tmp == NULL)
1018     {
1019         if (ssl_dh_param_file  &&
1020              (bio=BIO_new_file(ssl_dh_param_file,"r")) != NULL)
1021             dh_tmp=PEM_read_bio_DHparams(bio,NULL,NULL,NULL);
1022         if (bio != NULL)
1023             BIO_free(bio);
1024
1025         if ( dh_tmp == NULL ) {
1026             if ( keylength < 768 )
1027                 dh_tmp = get_dh512();
1028             else if ( keylength < 1024 )
1029                 dh_tmp = get_dh768();
1030             else if ( keylength < 1536 )
1031                 dh_tmp = get_dh1024();
1032             else if ( keylength < 2048 )
1033                 dh_tmp = get_dh1536();
1034             else
1035                 dh_tmp = get_dh2048();
1036         }
1037     }
1038 #else /* NO_DH */
1039     if (ssl_debug_flag)
1040         printf("DH not supported...\r\n");
1041 #endif /* NO_DH */
1042     return(dh_tmp);
1043 }
1044
1045 static void
1046 ssl_display_comp(SSL * ssl)
1047 {
1048     if ( quiet )                        /* fdc - Mon Nov 28 11:44:15 2005 */
1049         return;
1050
1051     if ( !ck_ssleay_is_installed() )
1052         return;
1053
1054     if (ssl == NULL)
1055         return;
1056
1057     if (ssl->expand == NULL || ssl->expand->meth == NULL)
1058         printf("Compression: None\r\n");
1059     else {
1060         printf("Compression: %s\r\n",ssl->expand->meth->name);
1061     }
1062 }
1063
1064 int
1065 #ifdef CK_ANSIC
1066 ssl_display_connect_details(SSL * ssl_con, int server, int verbose)
1067 #else /* CK_ANSIC */
1068 ssl_display_connect_details(ssl_con,server,verbose)
1069 SSL *ssl_con;
1070 int server;
1071 int verbose;
1072 #endif /* CK_ANSIC */
1073 {
1074     X509 *peer;
1075     SSL_CIPHER * cipher;
1076     const char *cipher_list;
1077     char buf[512]="";
1078
1079     if ( quiet )                        /* fdc - Mon Nov 28 11:44:15 2005 */
1080         return(0);
1081
1082     if ( !ck_ssleay_is_installed() )
1083         return(0);
1084
1085     if ( inserver && !tn_deb )
1086         return(0);
1087
1088     /* the cipher list *can* be NULL ... useless but it happens! */
1089     cipher = SSL_get_current_cipher(ssl_con);
1090     cipher_list = SSL_CIPHER_get_name(cipher);
1091     SSL_CIPHER_description(cipher,buf,sizeof(buf));
1092     if (cipher_list==NULL)
1093         cipher_list="<NULL>";
1094     printf("[TLS - %s",buf);
1095     ssl_display_comp(ssl_con);
1096
1097     if ( server ) {
1098         cipher_list=SSL_get_shared_ciphers(ssl_con,buf,512);
1099         if (cipher_list==NULL)
1100             cipher_list="<NULL>";
1101         printf("[TLS - shared ciphers=%s]\r\n",
1102                 cipher_list);
1103         }       
1104     if ( server || tn_deb ) {
1105         peer=SSL_get_peer_certificate(ssl_con);
1106         if (peer != NULL) {
1107             X509_NAME_oneline(X509_get_subject_name(peer),buf,512);
1108             printf("[TLS - subject=%s]\r\n",buf);
1109             X509_NAME_oneline(X509_get_issuer_name(peer),buf,512);
1110             printf("[TLS - issuer=%s]\r\n",buf);
1111             /* X509_free(peer); */
1112         } else if (!tls_is_krb5(0)) {
1113             if ( !sstelnet && !tcp_incoming ) {
1114                 printf("[TLS - No certificate provided.]\r\n");
1115                 printf(
1116      "[TLS - The identity of the host could not be verified.]\r\n");
1117             }
1118         }
1119     }
1120     return(0);
1121 }
1122
1123 /*
1124  * Use SSL_CTX_set_default_passwd_cb_userdata(SSL_CTX *, void * userdata)
1125  * to set the value of the userdata.  We are going to use it to store the
1126  * prompt.
1127  */
1128
1129 int
1130 #ifdef CK_ANSIC
1131 ssl_passwd_callback(char *buf, int len, int rwflag, VOID * userdata)
1132 #else /* CK_ANSIC */
1133 ssl_passwd_callback(buf,len,rwflag,userdata)
1134     char * buf; int len; int rwflag; VOID *userdata;
1135 #endif /* CK_ANSIC */
1136 {
1137     extern char pwbuf[];
1138     extern int  pwflg, pwcrypt;
1139     int   ok;
1140     char *prompt=NULL;
1141
1142     if ( pwbuf[0] && pwflg ) {
1143         int n;
1144         n = ckstrncpy(buf,pwbuf,len);
1145 #ifdef OS2
1146         if ( pwcrypt )
1147             ck_encrypt((char *)buf);
1148 #endif /* OS2 */
1149         return(n);
1150     }
1151
1152     if ( userdata == NULL )
1153         prompt="Enter certificate passphrase: ";
1154     else
1155         prompt=(char*)userdata;
1156     ok = uq_txt(NULL,prompt,2,NULL,buf,len,NULL,DEFAULT_UQ_TIMEOUT);
1157     return(ok > 0 ? strlen(buf) : 0);
1158 }
1159
1160
1161 /* Attempts to load certificate data into the TLS context structures */
1162 /* Returns 1 on success; 0 on failure */
1163 int
1164 tls_load_certs(SSL_CTX * ctx, SSL * con, int server)
1165 {
1166     int rc = 1;
1167
1168     if ( !ck_ssleay_is_installed() )
1169         return(0);
1170
1171     debug(F110,"tls_load_certs","SSL_CTX",0);
1172     debug(F110,"tls_load_certs","SSL",0);
1173     debug(F110,"tls_load_certs","server",0);
1174
1175     if ( con ) {
1176         if (ssl_rsa_cert_file) {
1177             if ( ssl_debug_flag )
1178                 printf("Loading RSA certificate into SSL\r\n");
1179
1180             rc = SSL_use_certificate_file(con, ssl_rsa_cert_file,
1181                                                X509_FILETYPE_PEM);
1182             if (!rc)
1183             {
1184                 if ( !quiet || ssl_debug_flag )
1185                     printf("Error loading certificate from %s\r\n",
1186                             ssl_rsa_cert_file);
1187             } else {
1188                 if (!ssl_rsa_key_file || !ssl_rsa_key_file[0])
1189                     makestr(&ssl_rsa_key_file,ssl_rsa_cert_file);
1190
1191                 rc = SSL_use_PrivateKey_file(con, ssl_rsa_key_file,
1192                                                   X509_FILETYPE_PEM);
1193                 if (!rc)
1194                     rc = SSL_use_PrivateKey_file(con, ssl_rsa_cert_file,
1195                                                       X509_FILETYPE_PEM);
1196                 if (!rc)
1197                 {
1198                     if ( !quiet || ssl_debug_flag )
1199                         printf("Error loading key from %s\r\n",
1200                                 ssl_rsa_key_file);
1201                 } else {
1202                     rc = SSL_check_private_key(con);
1203                     if (!rc)
1204                     {
1205                         if ( ssl_debug_flag )
1206                             printf(
1207                 "Private key does not match the certificate public key\r\n");
1208                     }
1209                 }
1210             }
1211         }
1212
1213         if (ssl_dsa_cert_file) {
1214             if ( ssl_debug_flag )
1215                 printf("Loading DSA certificate into SSL\r\n");
1216
1217             rc = SSL_use_certificate_file(con, ssl_dsa_cert_file,
1218                                                X509_FILETYPE_PEM);
1219             if (!rc)
1220             {
1221                 if ( ssl_debug_flag ) {
1222                     printf("Error loading certificate from %s\r\n",
1223                             ssl_dsa_cert_file);
1224                 }
1225             } else {
1226                 if (!ssl_dh_key_file || !ssl_dh_key_file[0])
1227                     makestr(&ssl_dh_key_file,ssl_dsa_cert_file);
1228                 rc = SSL_use_PrivateKey_file(con, ssl_dh_key_file,
1229                                                   X509_FILETYPE_PEM);
1230                 if (!rc)
1231                     rc = SSL_use_PrivateKey_file(con, ssl_dsa_cert_file,
1232                                                       X509_FILETYPE_PEM);
1233                 if (!rc)
1234                 {
1235                     if ( !quiet || ssl_debug_flag ) {
1236                         printf("Error loading key from %s\r\n",
1237                                 ssl_dh_key_file);
1238                     }
1239                 } else {
1240                     rc = SSL_check_private_key(con);
1241                     if (!rc)
1242                     {
1243                         if ( ssl_debug_flag )
1244                             printf(
1245                    "Private key does not match the certificate public key\n");
1246                     }
1247                 }
1248             }
1249         }
1250     } else {
1251         if (ssl_rsa_cert_file) {
1252             if ( ssl_debug_flag )
1253                 printf("Loading RSA certificate into SSL\r\n");
1254
1255             rc = SSL_CTX_use_certificate_file(ctx, ssl_rsa_cert_file,
1256                                        X509_FILETYPE_PEM);
1257             if (!rc)
1258             {
1259                 if ( !quiet || ssl_debug_flag )
1260                     printf("Error loading certificate from %s\r\n",
1261                             ssl_rsa_cert_file);
1262             } else {
1263                 if (!ssl_rsa_key_file || !ssl_rsa_key_file[0])
1264                     makestr(&ssl_rsa_key_file,ssl_rsa_cert_file);
1265
1266                 rc = SSL_CTX_use_PrivateKey_file(ctx, ssl_rsa_key_file,
1267                                                   X509_FILETYPE_PEM);
1268                 if (!rc)
1269                   rc = SSL_CTX_use_PrivateKey_file(ctx, ssl_rsa_cert_file,
1270                                                    X509_FILETYPE_PEM);
1271                 if (!rc) {
1272                     if ( ssl_debug_flag )
1273                       printf("Error loading key from %s\r\n",ssl_rsa_key_file);
1274                 } else {
1275                     rc = SSL_CTX_check_private_key(ctx);
1276                     if (!rc) {
1277                         if ( ssl_debug_flag )
1278                           printf(
1279                 "Private key does not match the certificate public key\r\n");
1280                     }
1281                 }
1282             }
1283         }
1284         if (ssl_dsa_cert_file) {
1285             if ( ssl_debug_flag )
1286               printf("Loading DSA certificate into SSL\r\n");
1287
1288             rc = SSL_CTX_use_certificate_file(ctx, ssl_dsa_cert_file,
1289                                               X509_FILETYPE_PEM);
1290             if (!rc) {
1291                 if ( ssl_debug_flag ) {
1292                     printf("Error loading certificate from %s\r\n",
1293                            ssl_dsa_cert_file);
1294                 }
1295             } else {
1296                 if (!ssl_dh_key_file || !ssl_dh_key_file[0])
1297                     makestr(&ssl_dh_key_file,ssl_dsa_cert_file);
1298                 rc = SSL_CTX_use_PrivateKey_file(ctx, ssl_dh_key_file,
1299                                                   X509_FILETYPE_PEM);
1300                 if (!rc)
1301                   rc = SSL_CTX_use_PrivateKey_file(ctx, ssl_dsa_cert_file,
1302                                                       X509_FILETYPE_PEM);
1303                 if (!rc) {
1304                     if ( ssl_debug_flag )
1305                       printf("Error loading key from %s\r\n",ssl_dh_key_file);
1306                 } else {
1307                     rc = SSL_CTX_check_private_key(ctx);
1308                     if (!rc) {
1309                         if ( ssl_debug_flag )
1310                           printf(
1311                    "Private key does not match the certificate public key\n");
1312                     }
1313                 }
1314             }
1315         }
1316     }
1317
1318     if (ssl_rsa_cert_chain_file && server) {
1319         int skip1st = 0;
1320         if (ssl_debug_flag)
1321             printf("Loading RSA Certificate Chain into SSL\r\n");
1322         if (!ckstrcmp(ssl_rsa_cert_chain_file,ssl_rsa_cert_file,-1,
1323 #ifdef OS2
1324                        0
1325 #else
1326                        1
1327 #endif /* OS2 */
1328                        ))
1329             skip1st = 1;
1330         rc = SSL_CTX_use_certificate_chain_file(ctx,ssl_rsa_cert_chain_file);
1331         if (!rc && ssl_debug_flag)
1332                 printf("Error loading RSA Certificate Chain into SSL\r\n");
1333     }
1334     if (ssl_dsa_cert_chain_file && server) {
1335         int skip1st = 0;
1336         if (ssl_debug_flag)
1337             printf("Loading DSA Certificate Chain into SSL\r\n");
1338         if (!ckstrcmp(ssl_dsa_cert_chain_file,ssl_dsa_cert_file,-1,
1339 #ifdef OS2
1340                        0
1341 #else
1342                        1
1343 #endif /* OS2 */
1344                        ))
1345             skip1st = 1;
1346         rc = SSL_CTX_use_certificate_chain_file(ctx,ssl_dsa_cert_chain_file);
1347         if (!rc && ssl_debug_flag)
1348                 printf("Error loading DSA Certificate Chain into SSL\r\n");
1349     }
1350     return(rc);
1351 }
1352
1353 VOID
1354 #ifdef CK_ANSIC
1355 ssl_once_init(void)
1356 #else
1357 ssl_once_init()
1358 #endif /* CK_ANSIC */
1359 {
1360     COMP_METHOD * cm;
1361     char * s;
1362
1363     if ( !ck_ssleay_is_installed() )
1364         return;
1365 /*
1366   Pre-OpenSSL 1.0.0 comment:
1367   OpenSSL does not provide for ABI compatibility between releases prior
1368   to version 1.0.0.  If the version does not match, it is not safe to
1369   assume that any function you call takes the same parameters or does
1370   the same thing with them.  Removing this test prior to the OpenSSL 1.0.0
1371   release will result in an increase in unexplained or incorrect behaviors.
1372   The test should be revised once OpenSSL 1.0.0 is released and we see what
1373   its claims are as to ABI compatibility.
1374 */
1375 /*
1376   Post-OpenSSL 1.0.0 comment:
1377   OpenSSL does not provide for ABI compatibility between releases prior
1378   to version 1.0.0.  After 1.0, the following holds:
1379
1380   Changes to last letter: security and bugfix only, no new features.
1381   E.g.  1.0.0->1.0.0a
1382   Changes to last number: new ABI compatible features.
1383   E.g. 1.0.0->1.0.1
1384   Changes to middle number: major release, ABI compatibility not guaranteed.
1385   E.g. 1.0.0->1.1.0
1386
1387   (per Dr. Stephen Henson)
1388 */
1389     debug(F111,"Kermit built for OpenSSL",OPENSSL_VERSION_TEXT,SSLEAY_VERSION_NUMBER);
1390 #ifndef OS2ONLY
1391     debug(F111,"OpenSSL Library",SSLeay_version(SSLEAY_VERSION),
1392            SSLeay());
1393     debug(F110,"OpenSSL Library",SSLeay_version(SSLEAY_BUILT_ON),0);
1394     debug(F110,"OpenSSL Library",SSLeay_version(SSLEAY_CFLAGS),0);
1395     debug(F110,"OpenSSL Library",SSLeay_version(SSLEAY_PLATFORM),0);
1396
1397     /* The following test is suggested by Richard Levitte */
1398     /* if (((OPENSSL_VERSION_NUMBER ^ SSLeay()) & 0xffffff0f) */
1399     /* Modified by Adam Friedlander for OpenSSL >= 1.0.0 */
1400     if (OPENSSL_VERSION_NUMBER > SSLeay()
1401          || ((OPENSSL_VERSION_NUMBER ^ SSLeay()) & COMPAT_VERSION_MASK)
1402 #ifdef OS2
1403          || ckstrcmp(OPENSSL_VERSION_TEXT,(char *)SSLeay_version(SSLEAY_VERSION),-1,1)
1404 #endif /* OS2 */
1405          ) {
1406         ssl_installed = 0;
1407         debug(F111,"OpenSSL Version does not match.  Built with",
1408                SSLeay_version(SSLEAY_VERSION),SSLEAY_VERSION_NUMBER);
1409         printf("?OpenSSL libraries do not match required version:\r\n");
1410         printf("  . C-Kermit built with %s\r\n",OPENSSL_VERSION_TEXT);
1411         printf("  . Version found  %s\r\n",SSLeay_version(SSLEAY_VERSION));
1412 #ifdef OPENSSL_100
1413         printf("  OpenSSL versions 1.0.0 or newer must be the same\r\n");
1414         printf("  major and minor version number, and Kermit may not\r\n");
1415         printf("  be used with a version of OpenSSL older than the one\r\n");
1416         printf("  supplied at compile time.\r\n");
1417 #else
1418         printf("  OpenSSL versions prior to 1.0.0 must be the same.\r\n");
1419 #endif /* OPENSSL_100 */
1420
1421         s = "R";
1422 #ifdef SOLARIS
1423         printf("  Set CD_LIBRARY_PATH for %s.\r\n",OPENSSL_VERSION_TEXT);
1424         s = " Or r";
1425 #endif  /* SOLARIS */
1426
1427 #ifdef HPUX
1428         printf("  Set SHLIB_PATH for %s.\r\n",OPENSSL_VERSION_TEXT);
1429         s = " Or r";
1430 #endif  /* HPUX */
1431
1432 #ifdef AIX
1433         printf("  Set LIBPATH for %s.\r\n",OPENSSL_VERSION_TEXT);
1434         s = " Or r";
1435 #endif  /* AIX */
1436
1437 #ifdef LINUX
1438         printf("  Set LD_LIBRARY_PATH for %s.\r\n",OPENSSL_VERSION_TEXT);
1439         s = " Or r";
1440 #endif  /* LINUX */
1441
1442         printf(" %sebuild C-Kermit from source on this computer to make \
1443 versions agree.\r\n",s);
1444
1445 #ifdef KTARGET
1446         {
1447             char * s;
1448             s = KTARGET;
1449             if (!s) s = "";
1450             if (!*s) s = "(unknown)";
1451             printf("  C-Kermit makefile target: %s\r\n",s);
1452         }
1453 #endif  /* KTARGET */
1454         printf("  Or if that is what you did then try to find out why\r\n");
1455         printf("  the program loader (image activator) is choosing a\r\n");
1456         printf("  different OpenSSL library than the one specified in \
1457 the build.\r\n\r\n");
1458         printf("  All SSL/TLS features disabled.\r\n\r\n");
1459         bleep(BP_FAIL);
1460 #ifdef SSLDLL
1461         ck_ssl_unloaddll();
1462         ck_crypto_unloaddll();
1463 #endif /* SSLDLL */
1464         return;
1465     }
1466 #endif /* OS2ONLY */
1467
1468     /* init things so we will get meaningful error messages
1469      * rather than numbers
1470      */
1471     SSL_load_error_strings();
1472
1473 #ifdef SSHBUILTIN
1474     OPENSSL_add_all_algorithms_noconf();
1475 #else
1476     /* SSL_library_init() only loads those ciphers needs for SSL  */
1477     /* These happen to be a similar set to those required for SSH */
1478     /* but they are not a complete set of ciphers provided by the */
1479     /* crypto library.                                            */
1480     SSL_library_init();
1481 #endif /* SSHBUILTIN */
1482
1483 #ifdef ZLIB
1484     cm = COMP_zlib();
1485     if (cm != NULL && cm->type != NID_undef) {
1486         SSL_COMP_add_compression_method(0xe0, cm); /* EAY's ZLIB ID */
1487     }
1488 #endif /* ZLIB */
1489     cm = COMP_rle();
1490     if (cm != NULL && cm->type != NID_undef)
1491         SSL_COMP_add_compression_method(0xe1, cm); /* EAY's RLE ID */
1492
1493     /* Ensure the Random number generator has enough entropy */
1494     if ( !RAND_status() ) {
1495         char buffer[256]="";
1496         char randombytes[256];
1497         int rc1 = -1, rc2 = 1;  /* assume failure and success */
1498
1499         debug(F110,"ssl_once_init","!RAND_status()",0);
1500
1501         if ( ssl_rnd_file == NULL ) {
1502             debug(F110,"ssl_rnd_file","ssl_rnd_file is NULL",0);
1503             RAND_file_name(buffer,256);
1504             if ( buffer[0] )
1505                 makestr(&ssl_rnd_file, buffer);
1506             else
1507                 makestr(&ssl_rnd_file,".rnd");
1508         }
1509         debug(F110,"ssl_rnd_file",ssl_rnd_file,0);
1510
1511         rc1 = RAND_egd(ssl_rnd_file);
1512         debug(F111,"ssl_once_init","RAND_egd()",rc1);
1513         if ( rc1 <= 0 ) {
1514             rc2 = RAND_load_file(ssl_rnd_file, -1);
1515             debug(F111,"ssl_once_init","RAND_load_file()",rc1);
1516         }
1517
1518         if ( rc1 <= 0 && !rc2 )
1519         {
1520             time_t t = time(NULL);
1521             int tlen = sizeof(time_t);
1522             int pid = getpid();
1523             int plen = sizeof(int);
1524             int n;
1525 #ifndef RAND_MAX
1526 #define RAND_MAX 0x7FFF
1527 #endif
1528             debug(F110,"ssl_once_init","calling RAND_seed()",0);
1529
1530             RAND_seed((unsigned char *)&t, tlen);
1531             RAND_seed((unsigned char *)&pid, plen);
1532
1533             srand((unsigned int)t);
1534             sprintf(buffer, "%.0f", (((double)(rand()%RAND_MAX)/RAND_MAX)*
1535                                       (sizeof(randombytes)-128-1)));
1536             n = (atoi(buffer)+1)%(sizeof(randombytes)-128-1);
1537             RAND_seed(randombytes, 128);
1538         }
1539
1540         if ( !RAND_status() ) {
1541             debug(F110,"ssl_once_init","Unable to initialize PRNG",0);
1542             printf(" Unable to load 'random state'\n");
1543             printf(" SSL and TLS are unavailble.\n");
1544             printf(" Use SET AUTH SSL RANDOM-FILE <file> command to provide random data.\n");
1545             printf(" Specified file will be overwritten with new random data after use.\n");
1546             return;
1547         }
1548
1549         if ( ssl_rnd_file ) {
1550             int rc = RAND_write_file(ssl_rnd_file);
1551             debug(F111,"ssl_once_init","RAND_write_file()",rc);
1552         }
1553     }
1554
1555 #ifdef NT
1556     // Initialize additional OID types for use when saving certs to a file
1557     OBJ_create("2.99999.3","SET.ex3","SET x509v3 extension 3");
1558 #endif /* NT */
1559
1560     /* make sure we have somewhere we can log errors to */
1561     bio_err=BIO_new(BIO_s_mem());
1562
1563     debug(F100,"ssl_once_init() complete","",0);
1564 }
1565
1566 int
1567 #ifdef CK_ANSIC
1568 ssl_tn_init(int mode)
1569 #else
1570 ssl_tn_init(mode) int mode;
1571 #endif /* CK_ANSIC */
1572 {
1573 #ifdef KRB5
1574     extern char * k5_keytab;
1575     extern char * krb5_d_srv;
1576 #endif /* KRB5 */
1577     static int last_ssl_mode = -1;
1578     SSL * ssl_conx=NULL, * tls_conx=NULL;
1579
1580     ssl_initialized = 0;
1581
1582     if ( !ck_ssleay_is_installed() )
1583         return(0);
1584
1585     debug(F111,"ssl_tn_init","mode",mode);
1586
1587     if (ssl_debug_flag)
1588         printf("SSL_DEBUG_FLAG on\r\n");
1589
1590     if (last_ssl_mode != mode) {
1591         if (ssl_ctx) {
1592             SSL_CTX_free(ssl_ctx);
1593             ssl_ctx = NULL;
1594         }
1595         if (tls_ctx) {
1596             SSL_CTX_free(tls_ctx);
1597             tls_ctx = NULL;
1598         }
1599     }
1600
1601     if ( (last_ssl_mode != mode) || !ssl_ctx || !tls_ctx ) {
1602         if ( mode == SSL_CLIENT ) {
1603             ssl_ctx=(SSL_CTX *)SSL_CTX_new(SSLv23_client_method());
1604             /* This can fail because we do not have RSA available */
1605             if ( !ssl_ctx ) {
1606                 debug(F110,"ssl_tn_init","SSLv23_client_method failed",0);
1607                 ssl_ctx=(SSL_CTX *)SSL_CTX_new(SSLv3_client_method());
1608             }
1609             if ( !ssl_ctx ) {
1610                 debug(F110,"ssl_tn_init","SSLv3_client_method failed",0);
1611                 last_ssl_mode = -1;
1612                 return(0);
1613             }
1614             /*
1615               TLS 1.0 is the new default as of 5 Feb 2015.
1616               Previously this was commented out because 
1617               "too many web servers still do not support TLSv1".
1618               Now we try TLS 1.0 first, falling back to SSL 2.3
1619               and SSL 3.0 in that order.  Maybe there should be
1620               an option not to fall back.
1621             */ 
1622             tls_ctx=(SSL_CTX *)SSL_CTX_new(TLSv1_client_method());
1623             if ( tls_ctx ) {
1624                 debug(F110,"ssl_tn_init","TLSv1_client_method OK",0);
1625             } else {
1626                 debug(F110,"ssl_tn_init","TLSv1_client_method failed",0);
1627                 /* This can fail because we do not have RSA available */
1628                 tls_ctx=(SSL_CTX *)SSL_CTX_new(SSLv23_client_method());
1629                 if ( !tls_ctx ) {
1630                     debug(F110,"ssl_tn_init","SSLv23_client_method OK",0);
1631                 } else {
1632                     debug(F110,"ssl_tn_init","SSLv23_client_method failed",0);
1633                     tls_ctx=(SSL_CTX *)SSL_CTX_new(SSLv3_client_method());
1634                     if ( !tls_ctx ) {
1635                         debug(F110,
1636                               "ssl_tn_init","TLSv1_client_method failed",0);
1637                         debug(F110,
1638                               "ssl_tn_init","All SSL client methods failed",0);
1639                         last_ssl_mode = -1;
1640                         return(0);
1641                     }
1642                 }
1643             }
1644 #ifdef USE_CERT_CB
1645             SSL_CTX_set_client_cert_cb(ssl_ctx,ssl_client_cert_callback);
1646             SSL_CTX_set_client_cert_cb(tls_ctx,ssl_client_cert_callback);
1647 #endif /* USE_CERT_CB */
1648         } else if (mode == SSL_SERVER) {
1649             /* We are a server */
1650             ssl_ctx=(SSL_CTX *)SSL_CTX_new(SSLv23_server_method());
1651             /* This can fail because we do not have RSA available */
1652             if ( !ssl_ctx ) {
1653                 debug(F110,"ssl_tn_init","SSLv23_server_method failed",0);
1654                 ssl_ctx=(SSL_CTX *)SSL_CTX_new(SSLv3_server_method());
1655             }
1656             if ( !ssl_ctx ) {
1657                 debug(F110,"ssl_tn_init","SSLv3_server_method failed",0);
1658                 last_ssl_mode = -1;
1659                 return(0);
1660             }
1661 #ifdef COMMENT
1662             tls_ctx=(SSL_CTX *)SSL_CTX_new(TLSv1_server_method());
1663 #else /* COMMENT */
1664             tls_ctx=(SSL_CTX *)SSL_CTX_new(SSLv23_server_method());
1665             /* This can fail because we do not have RSA available */
1666             if ( !tls_ctx ) {
1667                 debug(F110,"ssl_tn_init","SSLv23_server_method failed",0);
1668                 tls_ctx=(SSL_CTX *)SSL_CTX_new(TLSv1_server_method());
1669             }
1670 #endif /* COMMENT */
1671             if ( !tls_ctx ) {
1672                 debug(F110,"ssl_tn_init","TLSv1_server_method failed",0);
1673                 last_ssl_mode = -1;
1674                 return(0);
1675             }
1676         } else /* Unknown mode */
1677             return(0);
1678
1679         if ( !inserver ) {
1680             SSL_CTX_set_default_passwd_cb(ssl_ctx,
1681                                    (pem_password_cb *)ssl_passwd_callback);
1682             SSL_CTX_set_default_passwd_cb(tls_ctx,
1683                                    (pem_password_cb *)ssl_passwd_callback);
1684         }
1685
1686         /* for SSL switch on all the interoperability and bug
1687          * workarounds so that we will communicate with people
1688          * that cannot read poorly written specs :-)
1689          * for TLS be sure to prevent use of SSLv2
1690          */
1691         SSL_CTX_set_options(ssl_ctx,SSL_OP_ALL|SSL_OP_NO_SSLv2);
1692         SSL_CTX_set_options(tls_ctx,
1693                  SSL_OP_NO_SSLv2|SSL_OP_SINGLE_DH_USE|SSL_OP_EPHEMERAL_RSA);
1694
1695         SSL_CTX_set_info_callback(ssl_ctx,ssl_client_info_callback);
1696         SSL_CTX_set_info_callback(tls_ctx,ssl_client_info_callback);
1697
1698 #ifndef COMMENT
1699         /* Set the proper caching mode */
1700         if ( mode == SSL_SERVER ) {
1701             SSL_CTX_set_session_cache_mode(ssl_ctx,SSL_SESS_CACHE_SERVER);
1702             SSL_CTX_set_session_cache_mode(tls_ctx,SSL_SESS_CACHE_SERVER);
1703         } else {
1704             SSL_CTX_set_session_cache_mode(ssl_ctx,SSL_SESS_CACHE_CLIENT);
1705             SSL_CTX_set_session_cache_mode(tls_ctx,SSL_SESS_CACHE_CLIENT);
1706         }
1707         SSL_CTX_set_session_id_context(ssl_ctx,(CHAR *)"1",1);
1708         SSL_CTX_set_session_id_context(tls_ctx,(CHAR *)"2",1);
1709 #else /* COMMENT */
1710         SSL_CTX_set_session_cache_mode(ssl_ctx,SSL_SESS_CACHE_OFF);
1711         SSL_CTX_set_session_cache_mode(tls_ctx,SSL_SESS_CACHE_OFF);
1712 #endif /* COMMENT */
1713     }
1714
1715     /* The server uses defaults for the certificate files. */
1716     /* The client does not.                                */
1717     if (mode == SSL_SERVER) {
1718         char cert_filepath[1024];
1719         const char * defdir = NULL;
1720         DH * dh = NULL;
1721
1722         defdir = getenv("SSL_CERT_DIR");
1723         if ( !defdir ) {
1724 #ifdef OS2
1725             defdir = exedir;
1726 #else /* OS2 */
1727             defdir = X509_get_default_cert_dir();
1728 #endif /* OS2 */
1729             debug(F110,"ssl_tn_init - setting default directory to",defdir,0);
1730         }
1731         if ( !defdir )
1732             defdir = "";
1733
1734         if (!ssl_rsa_cert_file) {
1735             /* we need to know the fullpath to the location of the
1736             * certificate that we will be running with as we cannot
1737             * be sure of the cwd when we are launched
1738             */
1739             sprintf(cert_filepath,"%s/%s",defdir,"telnetd-rsa.pem");
1740             if (zchki(cert_filepath) > 0)
1741                 makestr(&ssl_rsa_cert_file,cert_filepath);
1742         }
1743         if (ssl_rsa_cert_file && !ssl_rsa_key_file) {
1744             /* we need to know the fullpath to the location of the
1745             * certificate that we will be running with as we cannot
1746             * be sure of the cwd when we are launched
1747             */
1748             sprintf(cert_filepath,"%s/%s",defdir,"telnetd-rsa-key.pem");
1749             if (zchki(cert_filepath) > 0)
1750                 makestr(&ssl_rsa_key_file,cert_filepath);
1751         }
1752         if (!ssl_dsa_cert_file) {
1753             /* we need to know the fullpath to the location of the
1754             * certificate that we will be running with as we cannot
1755             * be sure of the cwd when we are launched
1756             */
1757             sprintf(cert_filepath,"%s/%s",defdir,"telnetd-dsa.pem");
1758             if (zchki(cert_filepath) > 0)
1759                 makestr(&ssl_dsa_cert_file,cert_filepath);
1760         }
1761         if (ssl_dsa_cert_file && !ssl_dh_key_file) {
1762             /* we need to know the fullpath to the location of the
1763             * certificate that we will be running with as we cannot
1764             * be sure of the cwd when we are launched
1765             */
1766             sprintf(cert_filepath,"%s/%s",defdir,"telnetd-dsa-key.pem");
1767             if (zchki(cert_filepath) > 0)
1768                 makestr(&ssl_dh_key_file,cert_filepath);
1769         }
1770         if (!ssl_crl_dir) {
1771             /* we need to know the fullpath to the location of the
1772             * certificate that we will be running with as we cannot
1773             * be sure of the cwd when we are launched
1774             */
1775             sprintf(cert_filepath,"%s/crl",defdir);
1776             if (zchki(cert_filepath) > 0)
1777                 makestr(&ssl_crl_dir,cert_filepath);
1778         }
1779
1780         if (ssl_only_flag && !tls_load_certs(ssl_ctx,ssl_con,1)) {
1781             debug(F110,"ssl_tn_init","Unable to load SSL certs",0);
1782             last_ssl_mode = -1;
1783             return(0);
1784         }
1785         if (tls_only_flag && !tls_load_certs(tls_ctx,tls_con,1)) {
1786             debug(F110,"ssl_tn_init","Unable to load TLS certs",0);
1787             last_ssl_mode = -1;
1788             return(0);
1789         }
1790
1791         if ( (last_ssl_mode != mode) || !ssl_ctx || !tls_ctx ) {
1792             /* we may require a temp 512 bit RSA key because of the
1793              * wonderful way export things work ... if so we generate
1794              * one now!
1795              */
1796
1797             SSL_CTX_set_tmp_rsa_callback(ssl_ctx, tmp_rsa_cb);
1798             SSL_CTX_set_tmp_dh_callback( ssl_ctx, tmp_dh_cb);
1799             SSL_CTX_set_tmp_rsa_callback(tls_ctx, tmp_rsa_cb);
1800             SSL_CTX_set_tmp_dh_callback( tls_ctx, tmp_dh_cb);
1801
1802             dh = tmp_dh_cb(NULL,0,512);
1803             SSL_CTX_set_tmp_dh(ssl_ctx,dh);
1804             SSL_CTX_set_tmp_dh(tls_ctx,dh);
1805
1806             /* The following code is only called if we are using a
1807              * certificate with an RSA public key and where the
1808              * certificate has a key length less than 512 bits or is
1809              * marked for signing only.  This is so we can support
1810              * the greatest legal privacy level with exportable clients.
1811              */
1812
1813             if (SSL_CTX_need_tmp_RSA(ssl_ctx) ||
1814                  SSL_CTX_need_tmp_RSA(tls_ctx))
1815             {
1816                 RSA *rsa;
1817
1818                 if ( ssl_debug_flag )
1819                     printf("Generating temp (512 bit) RSA key ...\r\n");
1820                 rsa=RSA_generate_key(512,RSA_F4,NULL,NULL);
1821                 if ( ssl_debug_flag )
1822                     printf("Generation of temp (512 bit) RSA key done\r\n");
1823
1824                 if (SSL_CTX_need_tmp_RSA(ssl_ctx)) {
1825                     if (!SSL_CTX_set_tmp_rsa(ssl_ctx,rsa)) {
1826                         if ( ssl_debug_flag )
1827                             printf(
1828   "Failed to assign generated temp RSA key to SSL!\r\n");
1829                     }
1830                 }
1831                 if (SSL_CTX_need_tmp_RSA(tls_ctx)) {
1832                     if (!SSL_CTX_set_tmp_rsa(tls_ctx,rsa)) {
1833                         if ( ssl_debug_flag )
1834                             printf(
1835   "Failed to assign generated temp RSA key to TLS!\r\n");
1836                     }
1837                 }
1838                 RSA_free(rsa);
1839                 if ( ssl_debug_flag )
1840                     printf("Assigned temp (512 bit) RSA key\r\n");
1841             }
1842         }
1843     }
1844
1845     /* make sure we will find certificates in the standard
1846      * location ... otherwise we don't look anywhere for
1847      * these things which is going to make client certificate
1848      * exchange rather useless :-)
1849      * In OS2, default values for ssl_verify_file and ssl_verify_path.
1850      */
1851
1852 #ifdef OS2
1853 #ifdef NT
1854     {
1855         /* The defaults in the SSL crypto library are not appropriate for OS/2 */
1856         char path[CKMAXPATH];
1857
1858         ckmakmsg(path,CKMAXPATH,exedir,"certs",NULL,NULL);
1859         if (isdir(path) && 
1860             SSL_CTX_load_verify_locations(tls_ctx,NULL,path) == 1)  {
1861             debug(F110,"ssl_tn_init certificate verify dir",path,0);
1862             if (ssl_debug_flag)
1863                 printf("  Certificate Verification Directory: %s\r\n",path);
1864             SSL_CTX_load_verify_locations(ssl_ctx,NULL,path);
1865         }
1866         ckmakmsg(path,CKMAXPATH,GetAppData(1),"kermit 95/certs",NULL,NULL);
1867         if (isdir(path) &&
1868             SSL_CTX_load_verify_locations(tls_ctx,NULL,path) == 1)  {
1869             debug(F110,"ssl_tn_init certificate verify dir",path,0);
1870             if (ssl_debug_flag)
1871                 printf("  Certificate Verification Directory: %s\r\n",path);
1872             SSL_CTX_load_verify_locations(ssl_ctx,NULL,path);
1873         }
1874         ckmakmsg(path,CKMAXPATH,GetAppData(0),"kermit 95/certs",NULL,NULL);
1875         if (isdir(path) &&
1876             SSL_CTX_load_verify_locations(tls_ctx,NULL,path) == 1)  {
1877             debug(F110,"ssl_tn_init certificate verify dir",path,0);
1878             if (ssl_debug_flag)
1879                 printf("  Certificate Verification Directory: %s\r\n",path);
1880             SSL_CTX_load_verify_locations(ssl_ctx,NULL,path);
1881         }
1882         ckmakmsg(path,CKMAXPATH,exedir,"ca_certs.pem",NULL,NULL);
1883         if (zchki(path) > 0 && 
1884             SSL_CTX_load_verify_locations(tls_ctx,path,NULL) == 1) {
1885             debug(F110,"ssl_tn_init certificate verify file",path,0);
1886             if (ssl_debug_flag)
1887                 printf("  Certificate Verification File: %s\r\n",path);
1888             SSL_CTX_load_verify_locations(ssl_ctx,path,NULL);
1889         }
1890         ckmakmsg(path,CKMAXPATH,GetAppData(1),"kermit 95/ca_certs.pem",NULL,NULL);
1891         if (zchki(path) > 0 && 
1892             SSL_CTX_load_verify_locations(tls_ctx,path,NULL) == 1) {
1893             debug(F110,"ssl_tn_init certificate verify file",path,0);
1894             if (ssl_debug_flag)
1895                 printf("  Certificate Verification File: %s\r\n",path);
1896             SSL_CTX_load_verify_locations(ssl_ctx,path,NULL);
1897         }
1898         ckmakmsg(path,CKMAXPATH,GetAppData(0),"kermit 95/ca_certs.pem",NULL,NULL);
1899         if (zchki(path) > 0 && 
1900             SSL_CTX_load_verify_locations(tls_ctx,path,NULL) == 1) {
1901             debug(F110,"ssl_tn_init certificate verify file",path,0);
1902             if (ssl_debug_flag)
1903                 printf("  Certificate Verification File: %s\r\n",path);
1904             SSL_CTX_load_verify_locations(ssl_ctx,path,NULL);
1905         }
1906     }
1907 #else /* NT */
1908     {
1909         /* The defaults in the SSL crypto library are not appropriate for OS/2 */
1910         char path[CKMAXPATH];
1911
1912         ckmakmsg(path,CKMAXPATH,exedir,"certs",NULL,NULL);
1913         if (isdir(path) && 
1914             SSL_CTX_load_verify_locations(tls_ctx,NULL,path) == 1)  {
1915             debug(F110,"ssl_tn_init certificate verify dir",path,0);
1916             if (ssl_debug_flag)
1917                 printf("  Certificate Verification Directory: %s\r\n",path);
1918             SSL_CTX_load_verify_locations(ssl_ctx,NULL,path);
1919         }
1920         ckmakmsg(path,CKMAXPATH,exedir,"ca_certs.pem",NULL,NULL);
1921         if (zchki(path) > 0 && 
1922             SSL_CTX_load_verify_locations(tls_ctx,path,NULL) == 1) {
1923             debug(F110,"ssl_tn_init certificate verify file",path,0);
1924             if (ssl_debug_flag)
1925                 printf("  Certificate Verification File: %s\r\n",path);
1926             SSL_CTX_load_verify_locations(ssl_ctx,path,NULL);
1927         }
1928     }
1929 #endif /* NT */
1930 #else /* OS2 */
1931     SSL_CTX_set_default_verify_paths(ssl_ctx);
1932     SSL_CTX_set_default_verify_paths(tls_ctx);
1933 #endif /* OS2 */
1934
1935     if (ssl_verify_file) {
1936         if (zchki(ssl_verify_file) > 0 && 
1937             SSL_CTX_load_verify_locations(tls_ctx,ssl_verify_file,NULL) == 1) {
1938             debug(F110,"ssl_tn_init certificate verify file",ssl_verify_file,0);
1939             if (ssl_debug_flag)
1940                 printf("  Certificate Verification File: %s\r\n",ssl_verify_file);
1941             SSL_CTX_load_verify_locations(ssl_ctx,ssl_verify_file,NULL);
1942         }
1943     }
1944     if (ssl_verify_dir && isdir(ssl_verify_dir)) {
1945         if (SSL_CTX_load_verify_locations(tls_ctx,NULL,ssl_verify_dir) == 1)  {
1946             debug(F110,"ssl_tn_init certificate verify dir",ssl_verify_dir,0);
1947             if (ssl_debug_flag)
1948                 printf("  Certificate Verification Directory: %s\r\n",ssl_verify_dir);
1949             SSL_CTX_load_verify_locations(ssl_ctx,NULL,ssl_verify_dir);
1950         }
1951     }
1952     if (mode == SSL_SERVER) {
1953         SSL_CTX_set_verify(ssl_ctx,
1954                      ssl_verify_flag?ssl_verify_flag|SSL_VERIFY_CLIENT_ONCE:0,
1955                            ssl_server_verify_callback);
1956         SSL_CTX_set_verify(tls_ctx,
1957                      ssl_verify_flag?ssl_verify_flag|SSL_VERIFY_CLIENT_ONCE:0,
1958                            ssl_server_verify_callback);
1959     } else {
1960         SSL_CTX_set_verify(ssl_ctx,ssl_verify_flag,
1961                            ssl_client_verify_callback);
1962         SSL_CTX_set_verify(tls_ctx,ssl_verify_flag,
1963                            ssl_client_verify_callback);
1964     }
1965
1966     /* Free the existing CRL Store */
1967     if (crl_store) {
1968         X509_STORE_free(crl_store);
1969         crl_store = NULL;
1970     }
1971
1972     /* set up the new CRL Store */
1973     crl_store = X509_STORE_new();
1974     if (crl_store) {
1975 #ifdef OS2
1976         char path[CKMAXPATH];
1977
1978         ckmakmsg(path,CKMAXPATH,exedir,"crls",NULL,NULL);
1979         if (isdir(path) &&
1980             X509_STORE_load_locations(crl_store,NULL,path) == 1) {
1981             debug(F110,"ssl_tn_init crl dir",path,0);
1982             if (ssl_debug_flag)
1983                 printf("  CRL Directory: %s\r\n",path);
1984         }
1985 #ifdef NT
1986         ckmakmsg(path,CKMAXPATH,GetAppData(1),"kermit 95/crls",NULL,NULL);
1987         if (isdir(path) && 
1988             X509_STORE_load_locations(crl_store,NULL,path) == 1) {
1989             debug(F110,"ssl_tn_init crl dir",path,0);
1990             if (ssl_debug_flag)
1991                 printf("  CRL Directory: %s\r\n",path);
1992         }
1993         ckmakmsg(path,CKMAXPATH,GetAppData(0),"kermit 95/crls",NULL,NULL);
1994         if (isdir(path) && 
1995             X509_STORE_load_locations(crl_store,NULL,path) == 1) {
1996             debug(F110,"ssl_tn_init crl dir",path,0);
1997             if (ssl_debug_flag)
1998                 printf("  CRL Directory: %s\r\n",path);
1999         }
2000 #endif /* NT */
2001         
2002         ckmakmsg(path,CKMAXPATH,exedir,"ca_crls.pem",NULL,NULL);
2003         if (zchki(path) > 0 && 
2004             X509_STORE_load_locations(crl_store,path,NULL) == 1) {
2005             debug(F110,"ssl_tn_init crl file",path,0);
2006             if (ssl_debug_flag)
2007                 printf("  CRL File: %s\r\n",path);
2008         }
2009 #ifdef NT
2010         ckmakmsg(path,CKMAXPATH,GetAppData(1),"kermit 95/ca_crls.pem",NULL,NULL);
2011         if (zchki(path) > 0 && 
2012             X509_STORE_load_locations(crl_store,path,NULL) == 1) {
2013             debug(F110,"ssl_tn_init crl file",path,0);
2014             if (ssl_debug_flag)
2015                 printf("  CRL File: %s\r\n",path);
2016         }
2017         ckmakmsg(path,CKMAXPATH,GetAppData(0),"kermit 95/ca_crls.pem",NULL,NULL);
2018         if (zchki(path) > 0 && 
2019             X509_STORE_load_locations(crl_store,path,NULL) == 1) {
2020             debug(F110,"ssl_tn_init crl file",path,0);
2021             if (ssl_debug_flag)
2022                 printf("  CRL File: %s\r\n",path);
2023         }
2024 #endif /* NT */
2025 #endif /* OS2 */
2026
2027         if (ssl_crl_file || ssl_crl_dir) {
2028             if (ssl_crl_file && zchki(ssl_crl_file) > 0 && 
2029                 X509_STORE_load_locations(crl_store,ssl_crl_file,NULL) == 1) {
2030                 debug(F110,"ssl_tn_init crl file",ssl_crl_file,0);
2031                 if (ssl_debug_flag)
2032                     printf("  CRL File: %s\r\n",ssl_crl_file);
2033             }
2034             if (ssl_crl_dir && isdir(ssl_crl_dir) &&
2035                 X509_STORE_load_locations(crl_store,NULL,ssl_crl_dir) == 1) {
2036                 debug(F110,"ssl_tn_init crl dir",ssl_crl_dir,0);
2037                 if (ssl_debug_flag)
2038                     printf("  CRL Directory: %s\r\n",ssl_crl_dir);
2039             }
2040         } 
2041 #ifndef OS2
2042         else {
2043             X509_STORE_set_default_paths(crl_store);
2044         }
2045 #endif /* OS2 */
2046     }
2047
2048 #ifndef COMMENT
2049     ssl_conx = ssl_con;
2050     ssl_con=(SSL *)SSL_new(ssl_ctx);
2051     if ( !ssl_con ) {
2052         debug(F110,"ssl_tn_init","SSL_new(ssl_con) failed",0);
2053         last_ssl_mode = -1;
2054         ssl_con = ssl_conx;
2055         return(0);
2056     }
2057     if (ssl_conx) {
2058         if ( mode == SSL_CLIENT ) {
2059             SSL_set_session(ssl_con, SSL_get_session(ssl_conx));
2060         }
2061 #ifdef SSL_KRB5
2062                 if (ssl_conx->kssl_ctx) {
2063                         kssl_ctx_free(ssl_conx->kssl_ctx);
2064                         ssl_conx->kssl_ctx = NULL;
2065                 }
2066 #endif /* SSL_KRB5 */
2067         SSL_free(ssl_conx);
2068         ssl_conx = NULL;
2069     }
2070     tls_conx = tls_con;
2071     tls_con=(SSL *)SSL_new(tls_ctx);
2072     if ( !tls_con ) {
2073         debug(F110,"ssl_tn_init","SSL_new(tls_con) failed",0);
2074         last_ssl_mode = -1;
2075         tls_con = tls_conx;
2076         return(0);
2077     }
2078     if (tls_conx) {
2079         if ( mode == SSL_CLIENT )
2080             SSL_set_session(tls_con, SSL_get_session(tls_conx));
2081 #ifdef SSL_KRB5
2082                 if (tls_conx->kssl_ctx) {
2083                         kssl_ctx_free(tls_conx->kssl_ctx);
2084                         tls_conx->kssl_ctx = NULL;
2085                 }
2086 #endif /* SSL_KRB5 */
2087         SSL_free(tls_conx);
2088         tls_conx = NULL;
2089     }
2090 #else /* COMMENT */
2091     /* I don't know why this does not work to reuse the connection. */
2092     if ( ssl_con ) {
2093         SSL_clear(ssl_con);
2094         SSL_set_session(ssl_con,NULL);
2095         SSL_set_accept_state(ssl_con) ;
2096     } else {
2097         ssl_con=(SSL *)SSL_new(ssl_ctx);
2098         if (!ssl_con) {
2099             debug(F110,"ssl_tn_init","SSL_new(ssl_ctx) failed",0);
2100             last_ssl_mode = -1;
2101             ssl_con = ssl_conx;
2102             return(0);
2103         }
2104     }
2105
2106     if ( tls_con ) {
2107         SSL_clear(tls_con);
2108         SSL_set_session(tls_con,NULL);
2109         SSL_set_accept_state(tls_con) ;
2110     } else {
2111         tls_con=(SSL *)SSL_new(tls_ctx);
2112         if ( !tls_con ) {
2113             debug(F110,"ssl_tn_init","SSL_new(tls_ctx) failed",0);
2114             last_ssl_mode = -1;
2115             tls_con = tls_conx;
2116             return(0);
2117         }
2118     }
2119 #endif /* COMMENT */
2120
2121 #ifdef SSL_KRB5
2122 #ifndef KRB5_SERVICE_NAME
2123 #define KRB5_SERVICE_NAME    "host"
2124 #endif
2125
2126     if (ssl_con->kssl_ctx == NULL)
2127         ssl_con->kssl_ctx = kssl_ctx_new();
2128     if (tls_con->kssl_ctx == NULL)
2129     tls_con->kssl_ctx = kssl_ctx_new();
2130     if (mode == SSL_SERVER) {
2131         if (ssl_con->kssl_ctx != NULL)
2132             kssl_ctx_setstring(ssl_con->kssl_ctx, KSSL_KEYTAB, k5_keytab);
2133         if (tls_con->kssl_ctx != NULL)
2134             kssl_ctx_setstring(tls_con->kssl_ctx, KSSL_KEYTAB, k5_keytab);
2135     } else {
2136         if (ssl_con->kssl_ctx != NULL)
2137             kssl_ctx_setstring(ssl_con->kssl_ctx, KSSL_SERVER, szHostName);
2138         if (tls_con->kssl_ctx != NULL)
2139             kssl_ctx_setstring(tls_con->kssl_ctx, KSSL_SERVER, szHostName);
2140     }
2141     kssl_ctx_setstring(ssl_con->kssl_ctx, KSSL_SERVICE,
2142                         krb5_d_srv ? krb5_d_srv : KRB5_SERVICE_NAME);
2143     kssl_ctx_setstring(tls_con->kssl_ctx, KSSL_SERVICE,
2144                         krb5_d_srv ? krb5_d_srv : KRB5_SERVICE_NAME);
2145 #endif /* SSL_KRB5 */
2146
2147     if (ssl_cipher_list) {
2148         SSL_set_cipher_list(ssl_con,ssl_cipher_list);
2149         SSL_set_cipher_list(tls_con,ssl_cipher_list);
2150     } else {
2151         char * p;
2152         if (p = getenv("SSL_CIPHER")) {
2153             SSL_set_cipher_list(ssl_con,p);
2154             SSL_set_cipher_list(tls_con,p);
2155         } else {
2156             SSL_set_cipher_list(ssl_con,DEFAULT_CIPHER_LIST);
2157             SSL_set_cipher_list(tls_con,DEFAULT_CIPHER_LIST);
2158         }
2159     }
2160
2161     ssl_verify_depth = -1;
2162
2163     if ( ssl_debug_flag )
2164         printf("SSL/TLS init done!\r\n");
2165
2166     ssl_initialized = 1;
2167     last_ssl_mode = mode;
2168     debug(F110,"ssl_tn_init","done",0);
2169     return(1);
2170 }
2171
2172 #ifndef NOHTTP
2173 int
2174 #ifdef CK_ANSIC
2175 ssl_http_init(char * hostname)
2176 #else
2177 ssl_http_init(hostname) char * hostname;
2178 #endif /* CK_ANSIC */
2179 {
2180 #ifdef KRB5
2181     extern char * k5_keytab;
2182     extern char * krb5_d_srv;
2183 #endif /* KRB5 */
2184     SSL * tls_conx=NULL;
2185
2186     ssl_http_initialized = 0;
2187
2188     if ( !ck_ssleay_is_installed() )
2189         return(0);
2190     debug(F110,"ssl_http_init",hostname,0);
2191
2192     if (ssl_debug_flag)
2193         printf("SSL_DEBUG_FLAG on\r\n");
2194
2195     if (!tls_http_ctx ) {
2196         /*
2197           TLS 1.0 is the new default as of 5 Feb 2015.
2198           Previously this was commented out because 
2199           "too many web servers still do not support TLSv1".
2200           Now we try TLS 1.0 first, falling back to SSL 2.3
2201           and SSL 3.0 in that order.  Maybe there should be
2202           an option not to fall back.
2203         */ 
2204         tls_http_ctx=(SSL_CTX *)SSL_CTX_new(TLSv1_client_method());
2205         if ( tls_http_ctx ) {
2206             debug(F110,"ssl_http_init","TLSv1_client_method OK",0);
2207         }
2208     }
2209     SSL_CTX_set_default_passwd_cb(tls_http_ctx,
2210                                   (pem_password_cb *)ssl_passwd_callback);
2211
2212     /* for SSL switch on all the interoperability and bug
2213      * workarounds so that we will communicate with people
2214      * who cannot read poorly written specs :-)
2215      * for TLS be sure to prevent use of SSLv2
2216      */
2217     SSL_CTX_set_options(tls_http_ctx,
2218             SSL_OP_NO_SSLv2|SSL_OP_SINGLE_DH_USE|SSL_OP_EPHEMERAL_RSA);
2219
2220     SSL_CTX_set_info_callback(tls_http_ctx,ssl_client_info_callback);
2221
2222 #ifndef COMMENT
2223     SSL_CTX_set_session_cache_mode(tls_http_ctx,SSL_SESS_CACHE_CLIENT);
2224     SSL_CTX_set_session_id_context(tls_http_ctx,(CHAR *)"3",1);
2225 #else /* COMMENT */
2226     SSL_CTX_set_session_cache_mode(tls_http_ctx,SSL_SESS_CACHE_OFF);
2227 #endif /* COMMENT */
2228
2229     /* make sure we will find certificates in the standard
2230      * location ... otherwise we don't look anywhere for
2231      * these things which is going to make client certificate
2232      * exchange rather useless :-)
2233      */
2234
2235 #ifdef OS2
2236 #ifdef NT
2237     {
2238         /* The defaults in the SSL crypto library are not appropriate for OS/2 */
2239         char path[CKMAXPATH];
2240
2241         ckmakmsg(path,CKMAXPATH,exedir,"certs",NULL,NULL);
2242         if (SSL_CTX_load_verify_locations(tls_http_ctx,NULL,path) == 0)  {
2243             debug(F110,"ssl_http_init unable to load path",path,0);
2244             if (ssl_debug_flag)
2245                 printf("?Unable to load verify-dir: %s\r\n",path);
2246         }
2247
2248         ckmakmsg(path,CKMAXPATH,GetAppData(1),"kermit 95/certs",NULL,NULL);
2249         if (SSL_CTX_load_verify_locations(tls_http_ctx,NULL,path) == 0)  {
2250             debug(F110,"ssl_http_init unable to load path",path,0);
2251             if (ssl_debug_flag)
2252                 printf("?Unable to load verify-dir: %s\r\n",path);
2253         }
2254
2255         ckmakmsg(path,CKMAXPATH,GetAppData(0),"kermit 95/certs",NULL,NULL);
2256         if (SSL_CTX_load_verify_locations(tls_http_ctx,NULL,path) == 0)  {
2257             debug(F110,"ssl_http_init unable to load path",path,0);
2258             if (ssl_debug_flag)
2259                 printf("?Unable to load verify-dir: %s\r\n",path);
2260         }
2261
2262         ckmakmsg(path,CKMAXPATH,exedir,"ca_certs.pem",NULL,NULL);
2263         if (SSL_CTX_load_verify_locations(tls_http_ctx,path,NULL) == 0) {
2264             debug(F110,"ssl_http_init unable to load path",path,0);
2265             if (ssl_debug_flag)
2266                 printf("?Unable to load verify-file: %s\r\n",path);
2267         }
2268
2269         ckmakmsg(path,CKMAXPATH,GetAppData(1),"kermit 95/ca_certs.pem",NULL,NULL);
2270         if (SSL_CTX_load_verify_locations(tls_http_ctx,path,NULL) == 0) {
2271             debug(F110,"ssl_http_init unable to load path",path,0);
2272             if (ssl_debug_flag)
2273                 printf("?Unable to load verify-file: %s\r\n",path);
2274         }
2275
2276         ckmakmsg(path,CKMAXPATH,GetAppData(0),"kermit 95/ca_certs.pem",NULL,NULL);
2277         if (SSL_CTX_load_verify_locations(tls_http_ctx,path,NULL) == 0) {
2278             debug(F110,"ssl_http_init unable to load path",path,0);
2279             if (ssl_debug_flag)
2280                 printf("?Unable to load verify-file: %s\r\n",path);
2281         }
2282     }
2283 #else /* NT */
2284     {
2285         /* The defaults in the SSL crypto library are not appropriate for OS/2 */
2286         char path[CKMAXPATH];
2287
2288         ckmakmsg(path,CKMAXPATH,exedir,"certs",NULL,NULL);
2289         if (SSL_CTX_load_verify_locations(tls_http_ctx,NULL,path) == 0)  {
2290             debug(F110,"ssl_http_init unable to load path",path,0);
2291             if (ssl_debug_flag)
2292                 printf("?Unable to load verify-dir: %s\r\n",path);
2293         }
2294         ckmakmsg(path,CKMAXPATH,exedir,"ca_certs.pem",NULL,NULL);
2295         if (SSL_CTX_load_verify_locations(tls_http_ctx,path,NULL) == 0) {
2296             debug(F110,"ssl_http_init unable to load path",path,0);
2297             if (ssl_debug_flag)
2298                 printf("?Unable to load verify-file: %s\r\n",path);
2299         }
2300     }
2301 #endif /* NT */
2302 #else /* OS2 */
2303     SSL_CTX_set_default_verify_paths(tls_http_ctx);
2304 #endif /* OS2 */
2305
2306     if (ssl_verify_file &&
2307         SSL_CTX_load_verify_locations(tls_http_ctx,ssl_verify_file,NULL) == 0)  {
2308         debug(F110,"ssl_http_init unable to load ssl_verify_file",ssl_verify_file,0);
2309         if (ssl_debug_flag)
2310             printf("?Unable to load verify-file: %s\r\n",ssl_verify_file);
2311     }
2312     if (ssl_verify_dir &&
2313         SSL_CTX_load_verify_locations(tls_http_ctx,NULL,ssl_verify_dir) == 0)  {
2314         debug(F110,"ssl_http_init unable to load ssl_verify_dir",ssl_verify_dir,0);
2315         if (ssl_debug_flag)
2316             printf("?Unable to load verify-dir: %s\r\n",ssl_verify_dir);
2317     }
2318
2319     SSL_CTX_set_verify(tls_http_ctx,ssl_verify_flag,
2320                            ssl_client_verify_callback);
2321
2322     /* Free the existing CRL Store */
2323     if (crl_store) {
2324         X509_STORE_free(crl_store);
2325         crl_store = NULL;
2326     }
2327
2328     /* set up the new CRL Store */
2329     crl_store = X509_STORE_new();
2330     if (crl_store) {
2331 #ifdef OS2
2332         char path[CKMAXPATH];
2333
2334         ckmakmsg(path,CKMAXPATH,exedir,"crls",NULL,NULL);
2335         if (X509_STORE_load_locations(crl_store,NULL,path) == 0) {
2336             debug(F110,"ssl_http_init unable to load dir",path,0);
2337             if (ssl_debug_flag)
2338                 printf("?Unable to load crl-dir: %s\r\n",path);
2339         }
2340 #ifdef NT
2341         ckmakmsg(path,CKMAXPATH,GetAppData(1),"kermit 95/crls",NULL,NULL);
2342         if (X509_STORE_load_locations(crl_store,NULL,path) == 0) {
2343             debug(F110,"ssl_http_init unable to load dir",path,0);
2344             if (ssl_debug_flag)
2345                 printf("?Unable to load crl-dir: %s\r\n",path);
2346         }
2347         ckmakmsg(path,CKMAXPATH,GetAppData(0),"kermit 95/crls",NULL,NULL);
2348         if (X509_STORE_load_locations(crl_store,NULL,path) == 0) {
2349             debug(F110,"ssl_http_init unable to load dir",path,0);
2350             if (ssl_debug_flag)
2351                 printf("?Unable to load crl-dir: %s\r\n",path);
2352         }
2353 #endif /* NT */
2354         
2355         ckmakmsg(path,CKMAXPATH,exedir,"ca_crls.pem",NULL,NULL);
2356         if (X509_STORE_load_locations(crl_store,path,NULL) == 0) {
2357             debug(F110,"ssl_http_init unable to load file",path,0);
2358             if (ssl_debug_flag)
2359                 printf("?Unable to load crl-file: %s\r\n",path);
2360         }
2361 #ifdef NT
2362         ckmakmsg(path,CKMAXPATH,GetAppData(1),"kermit 95/ca_crls.pem",NULL,NULL);
2363         if (X509_STORE_load_locations(crl_store,path,NULL) == 0) {
2364             debug(F110,"ssl_http_init unable to load file",path,0);
2365             if (ssl_debug_flag)
2366                 printf("?Unable to load crl-file: %s\r\n",path);
2367         }
2368         ckmakmsg(path,CKMAXPATH,GetAppData(0),"kermit 95/ca_crls.pem",NULL,NULL);
2369         if (X509_STORE_load_locations(crl_store,path,NULL) == 0) {
2370             debug(F110,"ssl_http_init unable to load file",path,0);
2371             if (ssl_debug_flag)
2372                 printf("?Unable to load crl-file: %s\r\n",path);
2373         }
2374 #endif /* NT */
2375 #endif /* OS2 */
2376
2377         if (ssl_crl_file || ssl_crl_dir) {
2378             if (ssl_crl_file &&
2379                 X509_STORE_load_locations(crl_store,ssl_crl_file,NULL) == 0) {
2380                 debug(F110,"ssl_http_init unable to load ssl_crl_file",ssl_crl_file,0);
2381                 if (ssl_debug_flag)
2382                     printf("?Unable to load crl-file: %s\r\n",ssl_crl_file);
2383             }
2384             if (ssl_crl_dir &&
2385                 X509_STORE_load_locations(crl_store,NULL,ssl_crl_dir) == 0) {
2386                 debug(F110,"ssl_http_init unable to load ssl_crl_dir",ssl_crl_dir,0);
2387                 if (ssl_debug_flag)
2388                     printf("?Unable to load crl-dir: %s\r\n",ssl_crl_dir);
2389             }
2390         } else {
2391             X509_STORE_set_default_paths(crl_store);
2392         }
2393     }
2394
2395 #ifndef COMMENT
2396     tls_conx = tls_http_con;
2397     tls_http_con=(SSL *)SSL_new(tls_http_ctx);
2398     if ( !tls_http_con ) {
2399         debug(F110,"ssl_http_init","SSL_new(tls_http_con) failed",0);
2400         tls_http_con = tls_conx;
2401         return(0);
2402     }
2403     if (tls_conx) {
2404         SSL_set_session(tls_http_con, SSL_get_session(tls_conx));
2405 #ifdef SSL_KRB5
2406                 if (tls_conx->kssl_ctx) {
2407                         kssl_ctx_free(tls_conx->kssl_ctx);
2408                         tls_conx->kssl_ctx = NULL;
2409                 }
2410 #endif /* SSL_KRB5 */
2411         SSL_free(tls_conx);
2412         tls_conx = NULL;
2413     }
2414 #else /* COMMENT */
2415     /* I don't know why this does not work to reuse the connection. */
2416     if ( tls_http_con ) {
2417         SSL_clear(tls_http_con);
2418         SSL_set_session(tls_http_con,NULL);
2419         SSL_set_accept_state(tls_http_con) ;
2420     } else {
2421         tls_http_con=(SSL *)SSL_new(tls_http_ctx);
2422         if ( !tls_http_con ) {
2423             debug(F110,"ssl_http_init","SSL_new(tls_http_ctx) failed",0);
2424             tls_http_con = tls_conx;
2425             return(0);
2426         }
2427     }
2428 #endif /* COMMENT */
2429
2430 #ifdef SSL_KRB5
2431 #ifndef KRB5_SERVICE_NAME
2432 #define KRB5_SERVICE_NAME    "host"
2433 #endif
2434
2435     if (tls_http_con->kssl_ctx == NULL)
2436     tls_http_con->kssl_ctx = kssl_ctx_new();
2437     if (tls_http_con->kssl_ctx != NULL)
2438         kssl_ctx_setstring(tls_http_con->kssl_ctx, KSSL_SERVER, hostname);
2439
2440     kssl_ctx_setstring(tls_http_con->kssl_ctx, KSSL_SERVICE,
2441                         krb5_d_srv ? krb5_d_srv : KRB5_SERVICE_NAME);
2442 #endif /* SSL_KRB5 */
2443
2444     if (ssl_cipher_list)
2445         SSL_set_cipher_list(tls_http_con,ssl_cipher_list);
2446     else {
2447         char * p;
2448         if (p = getenv("SSL_CIPHER")) {
2449             SSL_set_cipher_list(tls_http_con,p);
2450         } else {
2451             SSL_set_cipher_list(tls_http_con,DEFAULT_CIPHER_LIST);
2452         }
2453     }
2454
2455     ssl_verify_depth = -1;
2456
2457     if ( ssl_debug_flag )
2458         printf("SSL/TLS init done!\r\n");
2459
2460     ssl_http_initialized = 1;
2461     return(1);
2462 }
2463 #endif /* NOHTTP */
2464
2465 char *
2466 ssl_get_dNSName(ssl) SSL * ssl;
2467 {
2468     static char *dns = NULL;
2469     X509 *server_cert = NULL;
2470     int i;
2471     X509_EXTENSION *ext = NULL;
2472     STACK_OF(GENERAL_NAME) *ialt = NULL;
2473     GENERAL_NAME *gen = NULL;
2474
2475     if ( dns ) {
2476         free(dns);
2477         dns = NULL;
2478     }
2479
2480     if (server_cert = SSL_get_peer_certificate(ssl)) {
2481         if ((i = X509_get_ext_by_NID(server_cert, NID_subject_alt_name, -1))<0)
2482             return NULL;
2483         if (!(ext = X509_get_ext(server_cert, i)))
2484             return NULL;
2485         X509V3_add_standard_extensions();
2486         if (!(ialt = X509V3_EXT_d2i(ext)))
2487             return NULL;
2488         for (i = 0; i < sk_GENERAL_NAME_num(ialt); i++) {
2489             gen = sk_GENERAL_NAME_value(ialt, i);
2490             if (gen->type == GEN_DNS) {
2491                 if (!gen->d.ia5 || !gen->d.ia5->length)
2492                   break;
2493                 if (strlen((char *)gen->d.ia5->data) != gen->d.ia5->length) {
2494                     /* Ignoring IA5String containing null character */
2495                     continue;
2496                 }
2497                 dns = malloc(gen->d.ia5->length + 1);
2498                 if (dns) {
2499                     memcpy(dns, gen->d.ia5->data, gen->d.ia5->length);
2500                     dns[gen->d.ia5->length] = 0;
2501                 }
2502                 break;
2503             }
2504         }
2505         X509V3_EXT_cleanup();
2506     }
2507 cleanup:
2508     if (ialt)           sk_GENERAL_NAME_free(ialt);
2509     if (server_cert)    X509_free(server_cert);
2510     return dns;
2511 }
2512
2513 char *
2514 ssl_get_commonName(ssl) SSL * ssl; {
2515     static char name[256];
2516     int name_text_len;
2517     int err;
2518     X509 *server_cert;
2519
2520     name_text_len = 0;
2521     if (server_cert = SSL_get_peer_certificate(ssl)) {
2522         name_text_len =
2523             X509_NAME_get_text_by_NID(X509_get_subject_name(server_cert),
2524                                       NID_commonName, name, sizeof(name));
2525         X509_free(server_cert);
2526     }
2527     if (name_text_len <= 0) {
2528         /* Common Name was empty or not retrieved */
2529         err = 0;
2530     } else if (strlen(name) != name_text_len) {
2531         /* Ignoring Common Name containing null character */
2532         err = 0;
2533     } else {
2534         err = 1;
2535     }
2536     if (err > 0)
2537       return name;
2538     else
2539       return NULL;
2540 }
2541
2542 char *
2543 ssl_get_issuer_name(ssl) SSL * ssl;
2544 {
2545     static char name[256];
2546     X509 *server_cert;
2547
2548     name[0] = '\0';
2549     if (server_cert = SSL_get_peer_certificate(ssl)) {
2550         X509_NAME_oneline(X509_get_issuer_name(server_cert),name,sizeof(name));
2551         X509_free(server_cert);
2552         return name;
2553     }
2554     else {
2555 #ifdef COMMENT
2556       fprintf(stderr, "Warning: No certificate from server!\r\n");
2557 #endif /* COMMENT */
2558         return NULL;
2559     }
2560 }
2561
2562 char *
2563 ssl_get_subject_name(ssl) SSL * ssl;
2564 {
2565     static char name[256];
2566     X509 *server_cert;
2567
2568     name[0] = '\0';
2569     if (server_cert = SSL_get_peer_certificate(ssl)) {
2570        X509_NAME_oneline(X509_get_subject_name(server_cert),name,sizeof(name));
2571        X509_free(server_cert);
2572        return name;
2573     }
2574     else
2575         return NULL;
2576 }
2577
2578 #ifdef COMMENT
2579 #ifdef CK_SSL
2580             && !(ck_ssleay_is_installed() &&
2581                (tls_active_flag || ssl_active_flag) &&
2582                ssl_anonymous_cipher(tls_active_flag?tls_con:ssl_con))
2583 #endif /* CK_SSL */
2584
2585 int
2586 ssl_anonymous_cipher(ssl) SSL * ssl;
2587 {
2588     X509 * cert;
2589
2590     if (sstelnet)
2591         cert = SSL_get_certificate(ssl);
2592     else
2593         cert = SSL_get_peer_certificate(ssl);
2594
2595     if ( cert ) {
2596         X509_free(cert);
2597         return 0;
2598     }
2599     return 1;
2600 }
2601 #endif /* COMMENT */
2602
2603 /*
2604   This one is (very much!) based on work by
2605   Ralf S. Engelschall <rse@engelschall.com>.
2606   Comments by Ralf.
2607 */
2608 int
2609 ssl_verify_crl(int ok, X509_STORE_CTX *ctx)
2610 {
2611     X509_OBJECT obj;
2612     X509_NAME *subject = NULL;
2613     X509_NAME *issuer = NULL;
2614     X509 *xs = NULL;
2615     X509_CRL *crl = NULL;
2616     X509_REVOKED *revoked = NULL;
2617     X509_STORE_CTX * store_ctx = NULL;
2618     long serial;
2619     BIO *bio = NULL;
2620     int i, n, rc;
2621     char *cp;
2622     char *cp2;
2623
2624     /*
2625      * Unless a revocation store for CRLs was created we
2626      * cannot do any CRL-based verification, of course.
2627      */
2628     if (!crl_store)
2629         return ok;
2630
2631     store_ctx = X509_STORE_CTX_new();
2632     if ( !store_ctx )
2633         return(ok);
2634
2635     /*
2636      * Determine certificate ingredients in advance
2637      */
2638     xs      = X509_STORE_CTX_get_current_cert(ctx);
2639     subject = X509_get_subject_name(xs);
2640     issuer  = X509_get_issuer_name(xs);
2641
2642     /*
2643      * OpenSSL provides the general mechanism to deal with CRLs but does not
2644      * use them automatically when verifying certificates, so we do it
2645      * explicitly here. We will check the CRL for the currently checked
2646      * certificate, if there is such a CRL in the store.
2647      *
2648      * We come through this procedure for each certificate in the certificate
2649      * chain, starting with the root-CA's certificate. At each step we've to
2650      * both verify the signature on the CRL (to make sure it's a valid CRL)
2651      * and it's revocation list (to make sure the current certificate isn't
2652      * revoked).  But because to check the signature on the CRL we need the
2653      * public key of the issuing CA certificate (which was already processed
2654      * one round before), we've a little problem. But we can both solve it and
2655      * at the same time optimize the processing by using the following
2656      * verification scheme (idea and code snippets borrowed from the GLOBUS
2657      * project):
2658      *
2659      * 1. We'll check the signature of a CRL in each step when we find a CRL
2660      *    through the _subject_ name of the current certificate. This CRL
2661      *    itself will be needed the first time in the next round, of course.
2662      *    But we do the signature processing one round before this where the
2663      *    public key of the CA is available.
2664      *
2665      * 2. We'll check the revocation list of a CRL in each step when
2666      *    we find a CRL through the _issuer_ name of the current certificate.
2667      *    This CRLs signature was then already verified one round before.
2668      *
2669      * This verification scheme allows a CA to revoke its own certificate as
2670      * well, of course.
2671      */
2672
2673     /*
2674      * Try to retrieve a CRL corresponding to the _subject_ of
2675      * the current certificate in order to verify it's integrity.
2676      */
2677     memset((char *)&obj, 0, sizeof(obj));
2678     X509_STORE_CTX_init(store_ctx, crl_store, NULL, NULL);
2679     rc = X509_STORE_get_by_subject(store_ctx, X509_LU_CRL, subject, &obj);
2680     X509_STORE_CTX_cleanup(store_ctx);
2681     crl = obj.data.crl;
2682     if (rc > 0 && crl != NULL) {
2683         /*
2684          * Verify the signature on this CRL
2685          */
2686         if (X509_CRL_verify(crl, X509_get_pubkey(xs)) <= 0) {
2687             fprintf(stderr, "Invalid signature on CRL!\n");
2688             X509_STORE_CTX_set_error(ctx, X509_V_ERR_CRL_SIGNATURE_FAILURE);
2689             X509_OBJECT_free_contents(&obj);
2690             X509_STORE_CTX_free(store_ctx);
2691             return 0;
2692         }
2693
2694         /*
2695          * Check date of CRL to make sure it's not expired
2696          */
2697         i = X509_cmp_current_time(X509_CRL_get_nextUpdate(crl));
2698         if (i == 0) {
2699             fprintf(stderr, "Found CRL has invalid nextUpdate field.\n");
2700             X509_STORE_CTX_set_error(ctx,
2701                                     X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD);
2702             X509_OBJECT_free_contents(&obj);
2703             X509_STORE_CTX_free(store_ctx);
2704             return 0;
2705         }
2706         if (i < 0) {
2707             fprintf(stderr,
2708 "Found CRL is expired - revoking all certificates until you get updated CRL.\n"
2709                     );
2710             X509_STORE_CTX_set_error(ctx, X509_V_ERR_CRL_HAS_EXPIRED);
2711             X509_OBJECT_free_contents(&obj);
2712             X509_STORE_CTX_free(store_ctx);
2713             return 0;
2714         }
2715         X509_OBJECT_free_contents(&obj);
2716     }
2717
2718     /*
2719      * Try to retrieve a CRL corresponding to the _issuer_ of
2720      * the current certificate in order to check for revocation.
2721      */
2722     memset((char *)&obj, 0, sizeof(obj));
2723     X509_STORE_CTX_init(store_ctx, crl_store, NULL, NULL);
2724     rc = X509_STORE_get_by_subject(store_ctx, X509_LU_CRL, issuer, &obj);
2725     X509_STORE_CTX_free(store_ctx);             /* calls X509_STORE_CTX_cleanup() */
2726     crl = obj.data.crl;
2727     if (rc > 0 && crl != NULL) {
2728         /*
2729          * Check if the current certificate is revoked by this CRL
2730          */
2731         n = sk_X509_REVOKED_num(X509_CRL_get_REVOKED(crl));
2732         for (i = 0; i < n; i++) {
2733             revoked = sk_X509_REVOKED_value(X509_CRL_get_REVOKED(crl), i);
2734             if (ASN1_INTEGER_cmp(revoked->serialNumber,
2735                                  X509_get_serialNumber(xs)) == 0) {
2736
2737                 serial = ASN1_INTEGER_get(revoked->serialNumber);
2738                 cp = X509_NAME_oneline(issuer, NULL, 0);
2739                 free(cp);
2740
2741                 X509_STORE_CTX_set_error(ctx, X509_V_ERR_CERT_REVOKED);
2742                 X509_OBJECT_free_contents(&obj);
2743                 return 0;
2744             }
2745         }
2746         X509_OBJECT_free_contents(&obj);
2747     }
2748     return ok;
2749 }
2750
2751 char *
2752 tls_userid_from_client_cert(ssl) SSL * ssl;
2753 {
2754     static char cn[256];
2755     static char *r = cn;
2756     int err;
2757     X509 *client_cert;
2758
2759     if (client_cert = SSL_get_peer_certificate(ssl)) {
2760         /* call the custom function */
2761         err = X509_to_user(client_cert, cn, sizeof(cn));
2762         X509_free(client_cert);
2763         if (err)
2764             return r = NULL;
2765         else
2766             return r;
2767     }
2768     else
2769         return r = NULL;
2770 }
2771
2772 unsigned char **
2773 tls_get_SAN_objs(SSL * ssl, int type)
2774 /* returns NULL or an array of malloc'ed objects of type `type' from the server's
2775  * subjectAltName, remember to free() them all!
2776  */
2777 {
2778 #define NUM_SAN_OBJS 64
2779     static unsigned char *objs[NUM_SAN_OBJS];
2780     unsigned char **rv = NULL;
2781     X509 *server_cert = NULL;
2782     int i, j;
2783     X509_EXTENSION *ext = NULL;
2784     STACK_OF(GENERAL_NAME) *ialt = NULL;
2785     GENERAL_NAME *gen = NULL;
2786
2787     memset(objs, 0, sizeof(objs));
2788     if (server_cert = SSL_get_peer_certificate(ssl)) {
2789         if ((i = X509_get_ext_by_NID(server_cert, NID_subject_alt_name, -1)) < 0)
2790             goto eject;
2791         if (!(ext = X509_get_ext(server_cert, i)))
2792             goto eject;
2793         X509V3_add_standard_extensions();
2794         if (!(ialt = X509V3_EXT_d2i(ext)))
2795             goto eject;
2796         rv = objs;
2797         for (i = 0, j = 0; i < sk_GENERAL_NAME_num(ialt) && j < NUM_SAN_OBJS - 2; i++) {
2798             gen = sk_GENERAL_NAME_value(ialt, i);
2799             /* The use of V_ASN1_CONTEXT_SPECIFIC is because OpenSSL 0.9.6 defined its
2800              * types | V_ASN1_CONTEXT_SPECIFIC.  0.9.7 does not.  In case, we are built
2801              * with one and linked to the other we use this hack.
2802              */
2803             if ((gen->type | V_ASN1_CONTEXT_SPECIFIC) == (type | V_ASN1_CONTEXT_SPECIFIC)) {
2804                 if (!gen->d.ia5 || !gen->d.ia5->length)
2805                   break;
2806                 if (strlen((char *)gen->d.ia5->data) != gen->d.ia5->length) {
2807                     /* Ignoring IA5String containing null character */
2808                     continue;
2809                 }
2810                 objs[j] = malloc(gen->d.ia5->length + 1);
2811                 if (objs[j]) {
2812                     memcpy(objs[j], gen->d.ia5->data, gen->d.ia5->length);
2813                     objs[j][gen->d.ia5->length] = 0;
2814                     j++;
2815                 }
2816             }
2817         }
2818         X509V3_EXT_cleanup();
2819     }
2820 eject:
2821     if (ialt)           sk_GENERAL_NAME_free(ialt);
2822     if (server_cert)    X509_free(server_cert);
2823     return rv;
2824 }
2825
2826
2827 static int
2828 dNSName_cmp(const char *host, const char *dNSName)
2829 {
2830     int c1 = 1, c2 = 1, num_comp, rv = -1;
2831     char *p, *p1, *p2, *host_copy=NULL, *dNSName_copy=NULL;
2832
2833     /* first we count the number of domain name components in both parameters.
2834      * they should be equal many, or it's not a match
2835      */
2836     p = (char *) host;
2837     while (p = strstr(p, ".")) {
2838         c1++;
2839         p++;
2840     }
2841     p = (char *) dNSName;
2842     while (p = strstr(p, ".")) {
2843         c2++;
2844         p++;
2845     }
2846     if (c1 != c2)
2847         return -1;
2848     num_comp = c1;
2849
2850     makestr(&host_copy,host);
2851     makestr(&dNSName_copy,dNSName);
2852     if (host_copy == NULL || dNSName_copy == NULL)
2853         goto eject;
2854     /* make substrings by replacing '.' with '\0' */
2855     p = dNSName_copy;
2856     while (p = strstr(p, ".")) {
2857         *p = '\0';
2858         p++;
2859     }
2860     p = host_copy;
2861     while (p = strstr(p, ".")) {
2862         *p = '\0';
2863         p++;
2864     }
2865
2866     /* compare each component */
2867     p1 = host_copy;
2868     p2 = dNSName_copy;
2869     for (; num_comp; num_comp--) {
2870         if (!ckmatch(p2, p1,0,1))
2871             /* failed match */
2872             goto eject;
2873         p1 += strlen(p1) + 1;
2874         p2 += strlen(p2) + 1;
2875     }
2876     /* match ok */
2877     rv = 0;
2878
2879   eject:
2880     if (dNSName_copy)   free(dNSName_copy);
2881     if (host_copy)      free(host_copy);
2882     return rv;
2883 }
2884
2885
2886
2887 static int
2888 show_hostname_warning(char *s1, char *s2)
2889 {
2890     char prefix[1024];
2891     int ok = 1;
2892     setverbosity();
2893     ckmakxmsg(prefix,1024,
2894               "Warning: Hostname (\"", s1, 
2895               "\") does not match server's certificate (\"", s2, "\")",
2896               NULL,NULL,NULL,NULL,NULL,NULL,NULL);
2897     if (ssl_verify_flag)
2898         ok = uq_ok(prefix,
2899                     "Continue? (Y/N) ",
2900                     3, NULL, 0);
2901     else if (verbosity)
2902         printf(prefix);
2903     return(ok);
2904 }
2905
2906 #ifndef OSF50
2907 #ifndef HPUX10
2908 #ifndef HPUX1100
2909 #ifndef SCO_OSR505
2910 #ifndef OpenBSD
2911 #ifndef FREEBSD4
2912 #ifndef NETBSD15
2913 #ifndef LINUX
2914 #ifndef AIX41
2915 #ifndef UW7
2916 #ifndef IRIX65
2917 #ifndef SOLARIS9
2918 #ifndef SOLARIS8
2919 #ifndef SOLARIS7
2920 #ifndef MACOSX
2921 #ifdef DEC_TCPIP
2922 #define inet_aton INET_ATON
2923 #endif /* DEC_TCPIP */
2924
2925 #ifndef NO_DCL_INET_ATON
2926 static int
2927 inet_aton(char * ipaddress, struct in_addr * ia) {
2928     struct stringarray * q;
2929     union {
2930         unsigned long l;
2931         unsigned char b[4];
2932     } dummy;
2933
2934     q = cksplit(1,0,ipaddress,".","0123456789abcdefACDEF",8,0,0);
2935     if (q->a_size == 4) {
2936         dummy.b[0] = atoi(q->a_head[1]);
2937         dummy.b[1] = atoi(q->a_head[2]);
2938         dummy.b[2] = atoi(q->a_head[3]);
2939         dummy.b[3] = atoi(q->a_head[4]);
2940         ia->s_addr = dummy.l;
2941         return(ia->s_addr != 0);
2942     }
2943     return(0);
2944 }
2945 #endif  /* NO_DCL_INET_ATON */
2946
2947 #endif /* MACOSX */
2948 #endif /* SOLARIS7 */
2949 #endif /* SOLARIS8 */
2950 #endif /* SOLARIS9 */
2951 #endif /* IRIX65 */
2952 #endif /* UW7 */
2953 #endif /* AIX41 */
2954 #endif /* LINUX */
2955 #endif /* NETBSD15 */
2956 #endif /* FREEBSD4 */
2957 #endif /* OpenBSD */
2958 #endif /* SCO_OSR505 */
2959 #endif /* HPUX1100 */
2960 #endif /* HPUX10 */
2961 #endif /* OSF50 */
2962
2963 int
2964 ssl_check_server_name(SSL * ssl, char * hostname)
2965 /* returns 0 if hostname and server's cert matches, else -1 */
2966 {
2967     char * commonName;
2968     unsigned char ** dNSName;
2969     unsigned char ** ipAddress;
2970     struct in_addr ia;
2971     int rv;
2972
2973     setverbosity();
2974     if (verbosity && !inserver) {
2975         if (dNSName = tls_get_SAN_objs(ssl,GEN_DNS)) {
2976             int i = 0;
2977             for (i = 0; dNSName[i]; i++) {
2978                 printf("Certificate[0] altSubjectName DNS=%s\r\n",dNSName[i]);
2979                 free(dNSName[i]);
2980             }
2981         }
2982         if (ipAddress = tls_get_SAN_objs(ssl,GEN_IPADD)) {
2983             int i = 0;
2984             char *server_ip;
2985             struct in_addr ia;
2986
2987             for (i = 0; ipAddress[i]; i++) {
2988                 if (ipAddress[i]) {
2989                     ia.s_addr = *(unsigned long *)ipAddress[i];
2990                     server_ip = inet_ntoa(ia);
2991                     printf("Certificate[0] altSubjectName IPAddr=%s\r\n",server_ip);
2992                 }
2993                 free(ipAddress[i]);
2994             }
2995             /* ipAddress points to a static - don't free */
2996         }
2997         if (dNSName = tls_get_SAN_objs(ssl,GEN_EMAIL)) {
2998             int i = 0;
2999             for (i = 0; dNSName[i]; i++) {
3000                 printf("Certificate[0] altSubjectName Email=%s\r\n",dNSName[i]);
3001                 free(dNSName[i]);
3002             }
3003         }
3004         if (dNSName = tls_get_SAN_objs(ssl,GEN_URI)) {
3005             int i = 0;
3006             for (i = 0; dNSName[i]; i++) {
3007                 printf("Certificate[0] altSubjectName URI=%s\r\n",dNSName[i]);
3008                 free(dNSName[i]);
3009             }
3010         }
3011         if (dNSName = tls_get_SAN_objs(ssl,GEN_OTHERNAME)) {
3012             int i = 0;
3013             for (i = 0; dNSName[i]; i++) {
3014                 printf("Certificate[0] altSubjectName Other=%s\r\n",dNSName[i]);
3015                 free(dNSName[i]);
3016             }
3017         }
3018     }
3019
3020     /* first we check if `hostname' is in fact an ip address */
3021     if (inet_aton(hostname, &ia)) {
3022         ipAddress = tls_get_SAN_objs(ssl,GEN_IPADD);
3023         if (ipAddress) {
3024             int i = 0;
3025             char *server_ip = "UNKNOWN";
3026
3027             for (i = 0; ipAddress[i]; i++)
3028                 if (*(unsigned long *)ipAddress[i] == ia.s_addr)
3029                     return 0;
3030
3031             if (ipAddress[i - 1]) {
3032                 ia.s_addr = *(unsigned long *)ipAddress[i - 1];
3033                 server_ip = inet_ntoa(ia);
3034             }
3035             rv = show_hostname_warning(hostname, server_ip) ? 0 : -1;
3036             for (i = 0; ipAddress[i]; i++)
3037                 free(ipAddress[i]);
3038         } else {
3039             rv = show_hostname_warning(hostname, "NO IP IN CERT") ? 0 : -1;
3040         }
3041         return(rv);
3042     }
3043
3044     /* look for dNSName(s) in subjectAltName in the server's certificate */
3045     dNSName = tls_get_SAN_objs(ssl,GEN_DNS);
3046     if (dNSName) {
3047         int i = 0;
3048         for (i = 0; dNSName[i]; i++) {
3049             if (!dNSName_cmp(hostname,(char *)dNSName[i]))
3050                 return 0;
3051         }
3052         rv = show_hostname_warning(hostname,
3053                                    (char *)((dNSName[i - 1] == NULL) ? 
3054                                    (char *)"UNKNOWN" : (char *)dNSName[i - 1]))
3055              ? 0 : -1;
3056         for (i = 0; dNSName[i]; i++)
3057             free(dNSName[i]);
3058         return rv;
3059     } else if ((commonName = ssl_get_commonName(ssl))) {
3060        /* so the server didn't have any dNSName's, check the commonName */
3061        if (!dNSName_cmp(hostname, commonName))
3062            return 0;
3063        else
3064            return (show_hostname_warning(hostname, commonName) ? 0 : -1);
3065     }
3066     return -1;
3067 }
3068
3069 /* Is 'user' authorized to access the system without a login */
3070 int
3071 tls_is_user_valid(SSL * ssl, const char *user)
3072 {
3073     X509 *client_cert;
3074     int r = 0;
3075
3076     if ( !ssl || !user || !user[0] )
3077         return(0);
3078
3079     if (!(client_cert = SSL_get_peer_certificate(ssl)))
3080         return 0;
3081
3082     /* Use user supplied function */
3083     r = X509_userok(client_cert,user);
3084
3085     X509_free(client_cert);
3086     return r;
3087 }
3088
3089 int
3090 tls_is_anon(int x)
3091 {
3092     char buf[128];
3093     SSL_CIPHER * cipher;
3094     SSL * ssl = NULL;
3095
3096     switch ( x ) {
3097 #ifndef NOFTP
3098 #ifndef SYSFTP
3099     case 1:     /* ftp command */
3100         if ( ssl_ftp_active_flag )
3101             ssl = ssl_ftp_con;
3102         else
3103             return(0);
3104         break;
3105     case 2:     /* ftp data */
3106         if ( ssl_ftp_data_active_flag )
3107             ssl = ssl_ftp_data_con;
3108         else
3109             return(0);
3110         break;
3111 #endif /* SYSFTP */
3112 #endif /* NOFTP */
3113     default:
3114         if (tls_active_flag)
3115             ssl = tls_con;
3116         else if (ssl_active_flag)
3117             ssl = ssl_con;
3118         else
3119             return(0);
3120     }
3121
3122     cipher = SSL_get_current_cipher(ssl);
3123     if (SSL_CIPHER_description(cipher,buf,sizeof(buf))) {
3124         if (ckindex("Au=None",buf,0,0,0) != 0)
3125             return(1);                  /* anonymous */
3126         return(0);                  /* known */
3127     } else {
3128         /* could not get cipher description.  Assume anonymous */
3129         return(1);
3130     }
3131 }
3132
3133 int
3134 tls_is_krb5(int x)
3135 {
3136     char buf[128];
3137     SSL_CIPHER * cipher;
3138     SSL * ssl = NULL;
3139
3140     switch ( x ) {
3141 #ifndef NOFTP
3142 #ifndef SYSFTP
3143     case 1:     /* ftp command */
3144         if ( ssl_ftp_active_flag )
3145             ssl = ssl_ftp_con;
3146         else
3147             return(0);
3148         break;
3149     case 2:     /* ftp data */
3150         if ( ssl_ftp_data_active_flag )
3151             ssl = ssl_ftp_data_con;
3152         else
3153             return(0);
3154         break;
3155 #endif /* SYSFTP */
3156 #endif /* NOFTP */
3157 #ifndef NOHTTP
3158     case 3:
3159         if ( tls_http_active_flag )
3160             ssl = tls_http_con;
3161         break;
3162 #endif /* NOHTTP */
3163     default:
3164         if (tls_active_flag)
3165             ssl = tls_con;
3166         else if (ssl_active_flag)
3167             ssl = ssl_con;
3168         else
3169             return(0);
3170     }
3171
3172     cipher = SSL_get_current_cipher(ssl);
3173     if (cipher && SSL_CIPHER_description(cipher,buf,sizeof(buf))) {
3174         if (ckindex("Au=KRB5",buf,0,0,0) != 0)
3175             return(1);                  /* krb5 */
3176     }
3177     return(0);                          /* not */
3178 }
3179
3180 int
3181 ssl_get_client_finished(char *buf, int count)
3182 {
3183 #ifdef NO_GET_FINISHED
3184     return(0);
3185 #else
3186     if (sstelnet || tcp_incoming) {
3187         return(SSL_get_peer_finished(ssl_active_flag?ssl_con:tls_con,
3188                                       buf,count));
3189     } else {
3190         return(SSL_get_finished(ssl_active_flag?ssl_con:tls_con,
3191                                       buf,count));
3192     }
3193 #endif /* NO_GET_FINISHED */
3194 }
3195
3196 int
3197 ssl_get_server_finished(char *buf, int count)
3198 {
3199 #ifdef NO_GET_FINISHED
3200     return(0);
3201 #else
3202     if (sstelnet || tcp_incoming) {
3203         return(SSL_get_finished(ssl_active_flag?ssl_con:tls_con,
3204                                       buf,count));
3205     } else {
3206         return(SSL_get_peer_finished(ssl_active_flag?ssl_con:tls_con,
3207                                       buf,count));
3208     }
3209 #endif /* NO_GET_FINISHED */
3210 }
3211
3212
3213 #ifdef CK_AUTHENTICATION
3214 int
3215 #ifdef CK_ANSIC
3216 ssl_reply(int how, unsigned char *data, int cnt)
3217 #else
3218 ssl_reply(how,data,cnt) int how; unsigned char *data; int cnt;
3219 #endif
3220 {
3221     char * str=NULL;
3222
3223     setverbosity();
3224     data += 4;                          /* Point to status byte */
3225     cnt  -= 4;
3226
3227     if(cnt-- < 1) {
3228         auth_finished(AUTH_REJECT);
3229         return AUTH_FAILURE;
3230     }
3231
3232     switch(*data++) {
3233     case SSL_ACCEPT:
3234         if (tn_deb || debses)
3235             tn_debug("[SSL - handshake starting]");
3236         else if ( verbosity )
3237             printf("[SSL - handshake starting]\r\n");
3238         debug(F110,"ssl_reply","[SSL - handshake starting]",0);
3239
3240         /* right ... now we drop into the SSL library */
3241         if (!ssl_only_flag) {
3242             if (ssl_dummy_flag) {
3243                 if (tn_deb || debses)
3244                     tn_debug("[SSL - Dummy Connected]");
3245                 else if ( verbosity ) {
3246                     printf("[SSL - Dummy Connected]\r\n");
3247                 }
3248                 debug(F110,"ssl_reply","[SSL - Dummy Connected]",0);
3249                 auth_finished(AUTH_UNKNOWN);
3250                 accept_complete = 1;
3251                 return AUTH_SUCCESS;
3252             }
3253
3254             if (SSL_connect(ssl_con) <= 0) {
3255                 int len;
3256                 if (tn_deb || debses) {
3257                     tn_debug("[SSL - FAILED]");
3258                     ERR_print_errors(bio_err);
3259                     len = BIO_read(bio_err,ssl_err,SSL_ERR_BFSZ);
3260                     ssl_err[len < SSL_ERR_BFSZ ? len : SSL_ERR_BFSZ] = '\0';
3261                     printf(ssl_err);
3262                 } else if ( verbosity ) {
3263                     printf("[SSL - FAILED]\r\n");
3264                     ERR_print_errors(bio_err);
3265                     len = BIO_read(bio_err,ssl_err,SSL_ERR_BFSZ);
3266                     ssl_err[len < SSL_ERR_BFSZ ? len : SSL_ERR_BFSZ] = '\0';
3267                     printf(ssl_err);
3268                 }
3269                 debug(F110,"ssl_reply","[SSL - FAILED]",0);
3270                 auth_finished(AUTH_REJECT);
3271                 ttclos(0);
3272                 return AUTH_FAILURE;
3273             } else {
3274                 if (tn_deb || debses)
3275                     tn_debug("[SSL - OK]");
3276                 else if ( verbosity ) {
3277                     printf("[SSL - OK]\r\n");
3278                 }
3279                 debug(F110,"ssl_reply","[SSL - OK]",0);
3280
3281                 ssl_active_flag = 1;
3282                 ssl_display_connect_details(ssl_con,0,verbosity);
3283             }
3284         }
3285         auth_finished(AUTH_UNKNOWN);
3286         accept_complete = 1;
3287         break;
3288
3289     case SSL_REJECT:
3290         if (tn_deb || debses) {
3291             tn_debug(
3292                  "[SSL - failed to switch on SSL - trying plaintext login]");
3293         } else if ( verbosity ) {
3294             printf("[SSL - failed to switch on SSL]\r\n");
3295             printf("Trying plaintext login:\r\n");
3296         }
3297         debug(F110,"ssl_reply","[SSL - failed to switch on SSL]",0);
3298         auth_finished(AUTH_REJECT);
3299         return AUTH_FAILURE;
3300
3301     default:
3302         return AUTH_FAILURE;
3303     }
3304     return AUTH_SUCCESS;
3305 }
3306
3307 int
3308 #ifdef CK_ANSIC
3309 ssl_is(unsigned char *data, int cnt)
3310 #else
3311 ssl_is(data,cnt) unsigned char *data; int cnt;
3312 #endif
3313 {
3314     if ((cnt -= 4) < 1)
3315         return AUTH_FAILURE;
3316
3317     setverbosity();
3318     data += 4;
3319     switch(*data++) {
3320     case SSL_START:
3321         /* server starts the SSL stuff now ... */
3322         if (!ssl_only_flag) {
3323             if ( !tls_load_certs(ssl_ctx,ssl_con,1) ) {
3324                 auth_finished(AUTH_REJECT);
3325                 return AUTH_FAILURE;
3326             }
3327
3328             if (tn_deb || debses)
3329                 tn_debug("[SSL - handshake starting]");
3330             else if ( verbosity )
3331                 printf("[SSL - handshake starting]\r\n");
3332             debug(F110,"ssl_is","[SSL - handshake starting]",0);
3333
3334             SendSSLAuthSB(SSL_ACCEPT, (void *)0, 0);
3335
3336             auth_ssl_valid = 1;
3337
3338             if (ssl_dummy_flag) {
3339                 if (tn_deb || debses)
3340                     tn_debug("[SSL - Dummy Connected]");
3341                 else if ( verbosity ) {
3342                     printf("[SSL - Dummy Connected]\r\n");
3343                 }
3344                 debug(F110,"ssl_is","[SSL - Dummy Connected]",0);
3345                 accept_complete = 1;
3346                 auth_finished(AUTH_UNKNOWN);
3347                 return AUTH_SUCCESS;
3348             }
3349
3350             if (SSL_accept(ssl_con) <= 0) {
3351                 char errbuf[1024];
3352
3353                 sprintf(errbuf,"[SSL - SSL_accept error: %s",
3354                          ERR_error_string(ERR_get_error(),NULL));
3355
3356                 if (tn_deb || debses)
3357                     tn_debug(errbuf);
3358                 else if ( ssl_debug_flag )
3359                     printf("%s\r\n",errbuf);
3360                 else if ( verbosity )
3361                     printf("[SSL - SSL_accept error]\r\n");
3362
3363                 debug(F110,"ssl_is",errbuf,0);
3364
3365                 auth_finished(AUTH_REJECT);
3366                 ttclos(0);
3367                 return AUTH_FAILURE;
3368             }
3369
3370             if (tn_deb || debses)
3371                 tn_debug("[SSL - OK]");
3372             else if ( verbosity ) {
3373                 printf("[SSL - OK]\r\n");
3374             }
3375             debug(F110,"ssl_is","[SSL - OK]",0);
3376             ssl_active_flag = 1;
3377             ssl_display_connect_details(ssl_con,1,verbosity);
3378
3379             /* now check to see that we got exactly what we
3380             * wanted from the caller ... if a certificate is
3381             * required then we make 100% sure that we were
3382             * given one during the handshake (as it is an optional
3383             * part of SSL)
3384             */
3385
3386 #ifdef SSL_KRB5
3387             if ( tls_is_krb5(0) ) {
3388                 if (ssl_con->kssl_ctx->client_princ)
3389                     debug(F110,"ssl_is KRB5",ssl_con->kssl_ctx->client_princ,0);
3390             } else
3391 #endif /* SSL_KRB5 */
3392             if (ssl_verify_flag & SSL_VERIFY_FAIL_IF_NO_PEER_CERT) {
3393                 X509 * peer = SSL_get_peer_certificate(ssl_con);
3394                 if (peer == NULL) {
3395                     if (tn_deb || debses)
3396                         tn_debug("[SSL - peer check failed]");
3397                     else if (ssl_debug_flag)
3398                         printf("[SSL - peer check failed]\r\n");
3399                     debug(F110,"ssl_is","[SSL - peer check failed]",0);
3400
3401                     /* LOGGING REQUIRED HERE! */
3402                     auth_finished(AUTH_REJECT);
3403                     return AUTH_FAILURE;
3404                 }
3405             }
3406             auth_finished(AUTH_UNKNOWN);
3407             accept_complete = 1;
3408         }
3409         break;
3410
3411     default:
3412         SendSSLAuthSB(SSL_REJECT, (void *) "Unknown option received", -1);
3413         if (tn_deb || debses)
3414             tn_debug("[SSL - Unknown option received]");
3415         else
3416             printf("Unknown SSL option %d\r\n", data[-1]);
3417         debug(F111,"ssl_is","[SSL - Unknown option received]",data[-1]);
3418         auth_ssl_valid = 0;
3419         auth_finished(AUTH_REJECT);
3420         return(AUTH_FAILURE);
3421     }
3422     return AUTH_SUCCESS;
3423 }
3424
3425 #endif /* CK_AUTHENTICATION */
3426
3427 int
3428 ck_tn_tls_negotiate(VOID)
3429 {
3430     X509 * peer = NULL;
3431     char str[256], *uid=NULL;
3432     extern int sstelnet;
3433
3434     if ( !ck_ssleay_is_installed() )
3435         return(-1);
3436
3437     setverbosity();
3438     if (sstelnet) {
3439         /* server starts the TLS stuff now ... */
3440         if (!tls_only_flag) {
3441             if ( !tls_load_certs(tls_ctx,tls_con,1) ) {
3442                 auth_finished(AUTH_REJECT);
3443                 return -1;
3444             }
3445
3446             if (tn_deb || debses)
3447                 tn_debug("[TLS - handshake starting]");
3448             else if ( verbosity )
3449                 printf("[TLS - handshake starting]\r\n");
3450             debug(F110,"ck_tn_tls_negotiate","[TLS - handshake starting]",0);
3451
3452             if (ssl_dummy_flag) {
3453                 if (tn_deb || debses)
3454                     tn_debug("[TLS - Dummy Connected]");
3455                 else if ( verbosity ) {
3456                     printf("[TLS - Dummy Connected]\r\n");
3457                 }
3458                 debug(F110,"ck_tn_tls_negotiate","[TLS - Dummy Connected]",0);
3459                 accept_complete = 1;
3460                 auth_finished(AUTH_REJECT);
3461                 return 0;
3462             }
3463
3464             if (SSL_accept(tls_con) <= 0) {
3465                 char errbuf[1024];
3466
3467                 sprintf(errbuf,"[TLS - SSL_accept error: %s",
3468                          ERR_error_string(ERR_get_error(),NULL));
3469
3470                 if (tn_deb || debses)
3471                     tn_debug(errbuf);
3472                 else if ( ssl_debug_flag )
3473                     printf("%s\r\n",errbuf);
3474                 else if ( verbosity )
3475                     printf("[TLS - SSL_accept error]\r\n");
3476
3477                 debug(F110,"ck_tn_tls_negotiate",errbuf,0);
3478                 auth_finished(AUTH_REJECT);
3479                 return -1;
3480             }
3481
3482             if (tn_deb || debses)
3483                 tn_debug("[TLS - OK]");
3484             else if ( verbosity ) {
3485                 printf("[TLS - OK]\r\n");
3486             }
3487
3488             debug(F110,"ck_tn_tls_negotiate","[TLS - OK]",0);
3489             tls_active_flag = 1;
3490             ssl_display_connect_details(tls_con,1,verbosity);
3491
3492
3493 #ifdef SSL_KRB5
3494             if ( tls_is_krb5(0) ) {
3495                 if (tls_con->kssl_ctx->client_princ) {
3496                     char *p;
3497                     ckstrncpy(szUserNameAuthenticated,
3498                                tls_con->kssl_ctx->client_princ,
3499                                UIDBUFLEN);
3500                     ckstrncpy(szUserNameRequested,
3501                                tls_con->kssl_ctx->client_princ,
3502                                UIDBUFLEN);
3503                     for ( p = szUserNameRequested; *p ; p++ ) {
3504                         if ( *p == '@' || *p == '/' ) {
3505                             *p = '\0';
3506                             break;
3507                         }
3508                     }
3509                 } else {
3510                     szUserNameRequested[0] = '\0';
3511                     szUserNameAuthenticated[0] = '\0';
3512                 }
3513 #ifdef CK_LOGIN
3514                 if (zvuser(szUserNameRequested))
3515                     auth_finished(AUTH_VALID);
3516                 else
3517 #endif /* CK_LOGIN */
3518                     auth_finished(AUTH_USER);
3519             } else
3520 #endif /* SSL_KRB5 */
3521             {
3522             /* now check to see that we got exactly what we
3523             * wanted from the caller ... if a certificate is
3524             * required then we make 100% sure that we were
3525             * given one during the handshake (as it is an optional
3526             * part of TLS)
3527             */
3528             peer=SSL_get_peer_certificate(tls_con);
3529             if (peer == NULL) {
3530                 debug(F100,"SSL_get_peer_certificate() == NULL","",0);
3531                 auth_finished(AUTH_REJECT);
3532                 if (ssl_verify_flag & SSL_VERIFY_FAIL_IF_NO_PEER_CERT) {
3533                     if (tn_deb || debses)
3534                         tn_debug("[TLS - peer check failed]");
3535                     else if (ssl_debug_flag) {
3536                         printf("[TLS - peer check failed]\r\n");
3537                     }
3538                     debug(F110,
3539                            "ck_tn_tls_negotiate",
3540                            "[TLS - peer check failed]",
3541                            0
3542                            );
3543                     /* LOGGING REQUIRED HERE! */
3544                     return -1;
3545                 }
3546             } else {
3547                 debug(F100,"SSL_get_peer_certificate() != NULL","",0);
3548                 X509_NAME_get_text_by_NID(X509_get_subject_name(peer),
3549                                            NID_commonName,str,
3550                                            256
3551                                            );
3552                 if ( verbosity )
3553                     printf("[TLS - commonName=%s]\r\n",str);
3554
3555                 X509_NAME_get_text_by_NID(X509_get_subject_name(peer),
3556 #ifndef NID_x500UniqueIdentifier
3557                                            NID_uniqueIdentifier,
3558 #else
3559                                            NID_x500UniqueIdentifier,
3560 #endif
3561                                            str,
3562                                            256
3563                                            );
3564                 if ( verbosity )
3565                     printf("[TLS - uniqueIdentifier=%s]\r\n",str);
3566
3567                 /* Try to determine user name */
3568                 uid = tls_userid_from_client_cert(tls_con);
3569                 if ( uid ) {
3570                     /* This code is very questionable.
3571                      * How should it behave?
3572                      * The client has presented a certificate that
3573                      * contains a username.  We have validated the
3574                      * certificate but we do not automatically
3575                      * log the user in unless there is a .tlslogin
3576                      * file.
3577                      */
3578
3579                     ckstrncpy(szUserNameRequested,uid,UIDBUFLEN);
3580 #ifdef CK_LOGIN
3581                     if (zvuser(uid))
3582                         auth_finished(AUTH_VALID);
3583                     else
3584 #endif /* CK_LOGIN */
3585                         auth_finished(AUTH_USER);
3586                 }
3587                 else {
3588                     szUserNameRequested[0] = '\0';
3589                     auth_finished(AUTH_REJECT);
3590                 }
3591             }
3592             }
3593         }
3594     } else {
3595         char * str=NULL;
3596
3597         if (tn_deb || debses)
3598             tn_debug("[TLS - handshake starting]");
3599         else if ( verbosity )
3600             printf("[TLS - handshake starting]\r\n");
3601         debug(F110,"ck_tn_tls_negotiate","[TLS - handshake starting]",0);
3602
3603         /* right ... now we drop into the SSL library */
3604         if (!tls_only_flag) {
3605             char *subject=NULL, *issuer=NULL, *commonName=NULL, *dNSName=NULL;
3606
3607             if (ssl_dummy_flag) {
3608                 if (tn_deb || debses)
3609                     tn_debug("[TLS - Dummy Connected]");
3610                 else if ( verbosity ) {
3611                     printf("[TLS - Dummy Connected]\r\n");
3612                 }
3613                 debug(F110,"ck_tn_tls_negotiate","[TLS - Dummy Connected]",0);
3614                 auth_finished(AUTH_REJECT);
3615                 accept_complete = 1;
3616                 return 0;
3617             }
3618
3619 #ifndef USE_CERT_CB
3620             if (!tls_load_certs(tls_ctx,tls_con,0))
3621                 return(-1);
3622 #endif /* USE_CERT_CB */
3623             if (SSL_connect(tls_con) <= 0) {
3624                 int len;
3625                 if (tn_deb || debses) {
3626                     tn_debug("[TLS - FAILED]");
3627                     ERR_print_errors(bio_err);
3628                     len = BIO_read(bio_err,ssl_err,SSL_ERR_BFSZ);
3629                     ssl_err[len < SSL_ERR_BFSZ ? len : SSL_ERR_BFSZ] = '\0';
3630                     printf(ssl_err);
3631                 } else if ( verbosity ) {
3632                     printf("[TLS - FAILED]\r\n");
3633                     ERR_print_errors(bio_err);
3634                     len = BIO_read(bio_err,ssl_err,SSL_ERR_BFSZ);
3635                     ssl_err[len < SSL_ERR_BFSZ ? len : SSL_ERR_BFSZ] = '\0';
3636                     printf(ssl_err);
3637                 }
3638                 debug(F110,"ck_tn_tls_negotiate","[TLS - FAILED]",0);
3639                 auth_finished(AUTH_REJECT);
3640                 return -1;
3641             }
3642
3643             tls_active_flag = 1;
3644             if ( !ssl_certsok_flag && (ssl_verify_flag & SSL_VERIFY_PEER)
3645                  && !tls_is_krb5(0)) {
3646                 char prmpt[1024];
3647                 subject = ssl_get_subject_name(tls_con);
3648
3649                 if (!subject) {
3650                     if (ssl_verify_flag & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)
3651                     {
3652                         if (tn_deb || debses)
3653                             tn_debug("[TLS - FAILED]");
3654                         else if ( verbosity )
3655                             printf("[TLS - FAILED]\r\n");
3656                         debug(F110,"ck_tn_tls_negotiate","[TLS - FAILED]",0);
3657                         auth_finished(AUTH_REJECT);
3658                         return -1;
3659                     } else {
3660                         int ok;
3661                         ok = uq_ok("Warning: Server didn't provide a certificate",
3662                                    "Continue? (Y/N)", 3, NULL, 0);
3663                         if (!ok) {
3664                             if (tn_deb || debses)
3665                                 tn_debug("[TLS - FAILED]");
3666                             else if ( verbosity )
3667                                 printf("[TLS - FAILED]\r\n");
3668                             debug(F110,
3669                                    "ck_tn_tls_negotiate","[TLS - FAILED]",0);
3670                             auth_finished(AUTH_REJECT);
3671                             return -1;
3672                         }
3673                     }
3674                 } else if (ssl_check_server_name(tls_con, szHostName)) {
3675                     if (tn_deb || debses)
3676                         tn_debug("[TLS - FAILED]");
3677                     else if ( verbosity )
3678                         printf("[TLS - FAILED]\r\n");
3679                     debug(F110,
3680                            "ck_tn_tls_negotiate","[TLS - FAILED]",0);
3681                     auth_finished(AUTH_REJECT);
3682                     return -1;
3683                 }
3684             }
3685
3686             if ( ssl_debug_flag && ssl_finished_messages) {
3687                 char msg[32];
3688                 int i, len=32;
3689                 extern char tn_msg[], hexbuf[];
3690
3691                 tn_msg[0] = '\0';
3692                 len = ssl_get_client_finished(msg,len);
3693                 if ( len > 0 ) {
3694                     for ( i=0;i<len;i++ ) {
3695                         sprintf(hexbuf,"%02X ",msg[i]);
3696                         ckstrncat(tn_msg,hexbuf,TN_MSG_LEN);
3697                     }
3698                     printf("TLS client finished: %s\r\n",tn_msg);
3699                 }
3700                 tn_msg[0] = '\0';
3701                 len = ssl_get_server_finished(msg,len);
3702                 if ( len > 0 ) {
3703                     for ( i=0;i<len;i++ ) {
3704                         sprintf(hexbuf,"%02X ",msg[i]);
3705                         ckstrncat(tn_msg,hexbuf,TN_MSG_LEN);
3706                     }
3707                     printf("TLS server finished: %s\r\n",tn_msg);
3708                 }
3709             }
3710
3711             if (tn_deb || debses)
3712                 tn_debug("[TLS - OK]");
3713             else if ( verbosity )
3714                 printf("[TLS - OK]\r\n");
3715             debug(F110,"ck_tn_tls_negotiate","[TLS - OK]",0);
3716
3717             ssl_display_connect_details(tls_con,0,verbosity);
3718         }
3719         auth_finished(AUTH_REJECT);
3720     }
3721     accept_complete = 1;
3722     auth_ssl_valid = 1;
3723     return(0);
3724 }
3725
3726 int
3727 ck_ssl_incoming(fd) int fd;
3728 {
3729     /* if we are not running in debug then any error
3730     * stuff from SSL debug *must* not go down
3731     * the socket (which 0,1,2 are all pointing to by
3732     * default)
3733     */
3734
3735     int timo = 2000;
3736
3737     setverbosity();
3738     if ( !ck_ssleay_is_installed() )
3739         return(-1);
3740
3741     /* do the SSL stuff now ... before we play with pty's */
3742     SSL_set_fd(ssl_con,fd);
3743     SSL_set_fd(tls_con,fd);
3744
3745     if (tls_only_flag) {
3746         if (tn_deb || debses)
3747             tn_debug("[TLS - handshake starting]");
3748         else if ( verbosity )
3749             printf("[TLS - handshake starting]\r\n");
3750         debug(F110,"ck_ssl_incoming","[TLS - handshake starting]",0);
3751
3752         /* hmm ... only when running talking to things like
3753         * https servers should we hit this code and then
3754         * we really don't care *who* we talk to :-)
3755         */
3756         if (SSL_accept(tls_con) <= 0) {
3757             char errbuf[1024];
3758
3759             sprintf(errbuf,"[TLS - SSL_accept error: %s",
3760                      ERR_error_string(ERR_get_error(),NULL));
3761
3762             if (tn_deb || debses)
3763                 tn_debug(errbuf);
3764             else if ( ssl_debug_flag )
3765                 printf("%s\r\n",errbuf);
3766             else if ( verbosity )
3767                 printf("[TLS - SSL_accept error]\r\n");
3768
3769             debug(F110,"ck_ssl_incoming",errbuf,0);
3770             return(-1);
3771         } else {
3772             if (tn_deb || debses)
3773                 tn_debug("[TLS - OK]");
3774             else if ( verbosity )
3775                 printf("[TLS - OK]\r\n");
3776             debug(F110,"ck_ssl_incoming","[TLS - OK]",0);
3777             tls_active_flag = 1;
3778         }
3779     } else if (ssl_only_flag) {
3780         if (tn_deb || debses)
3781             tn_debug("[SSL - handshake starting]");
3782         else if ( verbosity )
3783             printf("[SSL - handshake starting]\r\n");
3784         debug(F110,"ck_ssl_incoming","[SSL - handshake starting]",0);
3785
3786         /* hmm ... only when running talking to things like
3787          * https servers should we hit this code and then
3788          * we really don't care *who* we talk to :-)
3789          */
3790         if (SSL_accept(ssl_con) <= 0) {
3791             char errbuf[1024];
3792
3793             sprintf(errbuf,"[SSL - SSL_accept error: %s",
3794                      ERR_error_string(ERR_get_error(),NULL));
3795
3796             if (tn_deb || debses)
3797                 tn_debug(errbuf);
3798             else if ( ssl_debug_flag )
3799                 printf("%s\r\n",errbuf);
3800             else if ( verbosity )
3801                 printf("[SSL - SSL_accept error]\r\n");
3802
3803             debug(F110,"ck_ssl_incoming",errbuf,0);
3804             return(-1);
3805         } else {
3806             if (tn_deb || debses)
3807                 tn_debug("[SSL - OK]");
3808             else if ( verbosity )
3809             printf("[SSL - OK]\r\n");
3810             debug(F110,"ssl_is","[SSL - OK]",0);
3811             ssl_active_flag = 1;
3812         }
3813     }
3814     if (ssl_active_flag || tls_active_flag) {
3815         X509 *peer;
3816         char str[256], *uid=NULL;
3817
3818         /* now check to see that we got exactly what we
3819          * wanted from the caller ... if a certificate is
3820          * required then we make 100% sure that we were
3821          * given on during the handshake (as it is an optional
3822          * part of SSL and TLS)
3823          */
3824
3825         if ( tls_active_flag ) {
3826             peer=SSL_get_peer_certificate(tls_con);
3827         } else if ( ssl_active_flag ) {
3828             peer=SSL_get_peer_certificate(ssl_con);
3829         }
3830
3831         if (peer == NULL) {
3832             debug(F100,"SSL_get_peer_certificate() == NULL","",0);
3833             auth_finished(AUTH_REJECT);
3834
3835             if (ssl_verify_flag & SSL_VERIFY_FAIL_IF_NO_PEER_CERT) {
3836                 if (tn_deb || debses)
3837                     tn_debug("[SSL/TLS - peer check failed]");
3838                 else if (ssl_debug_flag) {
3839                     printf("[SSL/TLS - peer check failed]\r\n");
3840                 }
3841                 debug(F110,
3842                        "ck_tn_tls_negotiate",
3843                        "[SSL/TLS - peer check failed]",
3844                        0
3845                        );
3846                 /* LOGGING REQUIRED HERE! */
3847                 return -1;
3848             }
3849
3850         } else {
3851             debug(F100,"SSL_get_peer_certificate() != NULL","",0);
3852             X509_NAME_get_text_by_NID(X509_get_subject_name(peer),
3853                                        NID_commonName,str,
3854                                        256
3855                                        );
3856             printf("[TLS - commonName=%s]\r\n",str);
3857
3858             X509_NAME_get_text_by_NID(X509_get_subject_name(peer),
3859 #ifndef NID_x500UniqueIdentifier
3860                                        NID_uniqueIdentifier,
3861 #else   
3862                                        NID_x500UniqueIdentifier,
3863 #endif
3864                                        str,256
3865                                        );
3866             printf("[TLS - uniqueIdentifier=%s]\r\n",str);
3867
3868             /* Try to determine user name */
3869             uid = tls_userid_from_client_cert(tls_con);
3870             if ( uid ) {
3871                 /* This code is very questionable.
3872                 * How should it behave?
3873                 * The client has presented a certificate that
3874                 * contains a username.  We have validated the
3875                 * certificate but we do not automatically
3876                 * log the user in unless there is a .tlslogin
3877                 * file.
3878                 */
3879
3880                 ckstrncpy(szUserNameRequested,uid,UIDBUFLEN);
3881 #ifdef CK_LOGIN
3882                 if (zvuser(uid))
3883                     auth_finished(AUTH_VALID);
3884                 else
3885 #endif /* CK_LOGIN */
3886                     auth_finished(AUTH_USER);
3887             }
3888             else {
3889                 szUserNameRequested[0] = '\0';
3890                 auth_finished(AUTH_REJECT);
3891             }
3892         }
3893     }
3894     return(0);  /* success */
3895 }
3896
3897 int
3898 ck_ssl_outgoing(fd) int fd;
3899 {
3900     int timo = 2000;
3901
3902     setverbosity();
3903     if ( !ck_ssleay_is_installed() )
3904         return(-1);
3905
3906     /* bind in the network descriptor */
3907     SSL_set_fd(ssl_con,fd);
3908     SSL_set_fd(tls_con,fd);
3909
3910     /* If we are doing raw TLS then start it now ... */
3911     if (tls_only_flag) {
3912 #ifndef USE_CERT_CB
3913         if (!tls_load_certs(tls_ctx,tls_con,0)) {
3914             debug(F110,"ck_ssl_outgoing","tls_load_certs() failed",0);
3915             return(-1);
3916         }
3917 #endif /* USE_CERT_CB */
3918         if (tn_deb || debses)
3919             tn_debug("[TLS - handshake starting]");
3920         else if (verbosity)
3921             printf("[TLS - handshake starting]\r\n");
3922         debug(F110,"ck_ssl_outgoing","[TLS - handshake starting]",0);
3923         if (SSL_connect(tls_con) <= 0) {
3924             char errbuf[1024];
3925
3926             sprintf(errbuf,"[TLS - SSL_connect error: %s",
3927                      ERR_error_string(ERR_get_error(),NULL));
3928
3929             if (tn_deb || debses)
3930                 tn_debug(errbuf);
3931             else if ( ssl_debug_flag )
3932                 printf("%s\r\n",errbuf);
3933
3934             if (tn_deb || debses)
3935                 tn_debug("[TLS - FAILED]");
3936             else if ( verbosity )
3937                 printf("[TLS - FAILED]\r\n");
3938             debug(F110,"ck_ssl_outgoing","[TLS - FAILED]",0);
3939             netclos();
3940             return(-1);
3941         } else {
3942             tls_active_flag = 1;
3943             if ( !ssl_certsok_flag && (ssl_verify_flag & SSL_VERIFY_PEER) && 
3944                  !tls_is_krb5(0) ) {
3945                 char *subject = ssl_get_subject_name(tls_con);
3946
3947                 if (!subject) {
3948                     if (ssl_verify_flag & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)
3949                     {
3950                         if (tn_deb || debses)
3951                             tn_debug("[TLS - FAILED]");
3952                         else if ( verbosity )
3953                             printf("[TLS - FAILED]\r\n");
3954                         debug(F110,"ck_tn_tls_negotiate","[TLS - FAILED]",0);
3955
3956                         auth_finished(AUTH_REJECT);
3957                         return -1;
3958                     } else {
3959                         char prmpt[1024];
3960                         int ok;
3961                         ok = uq_ok("Warning: Server didn't provide a certificate",
3962                                    "Continue? (Y/N)", 3, NULL, 0);
3963                         if (!ok) {
3964                             if (tn_deb || debses)
3965                                 tn_debug("[TLS - FAILED]");
3966                             else if ( verbosity )
3967                                 printf("[TLS - FAILED]\r\n");
3968                             debug(F110,
3969                                    "ck_tn_tls_negotiate","[TLS - FAILED]",0);
3970                             auth_finished(AUTH_REJECT);
3971                             return -1;
3972                         }
3973                     }
3974                 } else if (ssl_check_server_name(tls_con, szHostName)) {
3975                     if (tn_deb || debses)
3976                         tn_debug("[TLS - FAILED]");
3977                     else if ( verbosity )
3978                         printf("[TLS - FAILED]\r\n");
3979                     debug(F110,
3980                            "ck_tn_tls_negotiate","[TLS - FAILED]",0);
3981                     auth_finished(AUTH_REJECT);
3982                     return -1;
3983                 }
3984             }
3985             if (tn_deb || debses)
3986                 tn_debug("[TLS - OK]");
3987             else if (!quiet)
3988                 printf("[TLS - OK]\r\n");
3989             debug(F110,"ck_ssl_outgoing","[TLS - OK]",0);
3990             ssl_display_connect_details(tls_con,0,verbosity);
3991         }
3992     }
3993     /* if we are doing raw SSL then start it now ... */
3994     else if (ssl_only_flag) {
3995 #ifndef USE_CERT_CB
3996         if (!tls_load_certs(ssl_ctx,ssl_con,0))
3997             return(-1);
3998 #endif /* USE_CERT_CB */
3999         if (tn_deb || debses)
4000             tn_debug("[SSL - handshake starting]");
4001         else if ( verbosity )
4002             printf("[SSL - handshake starting]\r\n");
4003         debug(F110,"ck_ssl_outgoing","[SSL - handshake starting]",0);
4004         if (SSL_connect(ssl_con) <= 0) {
4005             if ( ssl_debug_flag ) {
4006                 char errbuf[1024];
4007
4008                 sprintf(errbuf,"[SSL - SSL_connect error: %s",
4009                          ERR_error_string(ERR_get_error(),NULL));
4010                 printf("%s\r\n",errbuf);
4011             }
4012             if (tn_deb || debses)
4013                 tn_debug("[SSL - FAILED]");
4014             else if ( verbosity )
4015                 printf("[SSL - FAILED]\r\n");
4016             debug(F110,"ck_ssl_outgoing","[SSL - FAILED]",0);
4017             return(-1);
4018         } else {
4019             ssl_active_flag = 1;
4020
4021             if ( !ssl_certsok_flag && (ssl_verify_flag & SSL_VERIFY_PEER) &&
4022                  !tls_is_krb5(0)) {
4023                 char *subject = ssl_get_subject_name(ssl_con);
4024
4025                 if (!subject) {
4026                     if (ssl_verify_flag & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)
4027                     {
4028                         if (tn_deb || debses)
4029                             tn_debug("[SSL - FAILED]");
4030                         else if ( verbosity )
4031                             printf("[SSL - FAILED]\r\n");
4032                         debug(F110,"ck_tn_tls_negotiate","[SSL - FAILED]",0);
4033
4034                         auth_finished(AUTH_REJECT);
4035                         return -1;
4036                     } else {
4037                         char prmpt[1024];
4038                         int ok;
4039                         ok = uq_ok("Warning: Server didn't provide a certificate",
4040                                    "Continue? (Y/N)", 3, NULL, 0);
4041                         if (!ok) {
4042                             if (tn_deb || debses)
4043                                 tn_debug("[SSL - FAILED]");
4044                             else if ( verbosity )
4045                                 printf("[SSL - FAILED]\r\n");
4046                             debug(F110,
4047                                    "ck_tn_tls_negotiate","[SSL - FAILED]",0);
4048                             auth_finished(AUTH_REJECT);
4049                             return -1;
4050                         }
4051                     }
4052                 } else if (ssl_check_server_name(ssl_con, szHostName)) {
4053                     if (tn_deb || debses)
4054                         tn_debug("[SSL - FAILED]");
4055                     else if ( verbosity )
4056                         printf("[SSL - FAILED]\r\n");
4057                     debug(F110, "ck_tn_tls_negotiate","[SSL - FAILED]",0);
4058                     auth_finished(AUTH_REJECT);
4059                     return -1;
4060                 }
4061             }
4062             if (tn_deb || debses)
4063                 tn_debug("[SSL - OK]");
4064             else if (!quiet)
4065                 printf("[SSL - OK]\r\n");
4066             debug(F110,"ck_ssl_outgoing","[SSL - OK]",0);
4067             ssl_display_connect_details(ssl_con,0,verbosity);
4068         }
4069     }
4070     return(0);  /* success */
4071 }
4072
4073 #ifndef NOHTTP
4074 int
4075 ck_ssl_http_client(fd, hostname) int fd; char * hostname;
4076 {
4077     int timo = 2000;
4078
4079     if ( !ck_ssleay_is_installed() )
4080         return(-1);
4081
4082     setverbosity();
4083
4084     /* bind in the network descriptor */
4085     SSL_set_fd(tls_http_con,fd);
4086
4087     /* If we are doing raw TLS then start it now ... */
4088     if (1) {
4089 #ifndef USE_CERT_CB
4090         if (!tls_load_certs(tls_http_ctx,tls_http_con,0)) {
4091             debug(F110,"ck_ssl_http_client","tls_load_certs() failed",0);
4092             return(-1);
4093         }
4094 #endif /* USE_CERT_CB */
4095         if (tn_deb || debses)
4096             tn_debug("[TLS - handshake starting]");
4097         else if (verbosity)
4098             printf("[TLS - handshake starting]\r\n");
4099         debug(F110,"ck_ssl_outgoing","[TLS - handshake starting]",0);
4100         if (SSL_connect(tls_http_con) <= 0) {
4101             char errbuf[1024];
4102
4103             sprintf(errbuf,"[TLS - SSL_connect error: %s",
4104                      ERR_error_string(ERR_get_error(),NULL));
4105
4106             if (tn_deb || debses)
4107                 tn_debug(errbuf);
4108             else if ( ssl_debug_flag )
4109                 printf("%s\r\n",errbuf);
4110
4111             if (tn_deb || debses)
4112                 tn_debug("[TLS - FAILED]");
4113             else if ( verbosity )
4114                 printf("[TLS - FAILED]\r\n");
4115             debug(F110,"ck_ssl_http_client","[TLS - FAILED]",0);
4116             http_close();
4117             return(-1);
4118         } else {
4119             tls_http_active_flag = 1;
4120             if ( !ssl_certsok_flag && (ssl_verify_flag & SSL_VERIFY_PEER) &&
4121                  !tls_is_krb5(3) ) {
4122                 char *subject = ssl_get_subject_name(tls_http_con);
4123
4124                 if (!subject) {
4125                     if (ssl_verify_flag & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)
4126                     {
4127                         if (tn_deb || debses)
4128                             tn_debug("[TLS - FAILED]");
4129                         else if ( verbosity )
4130                             printf("[TLS - FAILED]\r\n");
4131                         debug(F110,"ck_tn_tls_negotiate","[TLS - FAILED]",0);
4132                         return -1;
4133                     } else {
4134                         char prmpt[1024];
4135                         int ok;
4136                         ok = uq_ok("Warning: Server didn't provide a certificate",
4137                                    "Continue? (Y/N)", 3, NULL, 0);
4138                         if (!ok) {
4139                             if (tn_deb || debses)
4140                                 tn_debug("[TLS - FAILED]");
4141                             else if ( verbosity )
4142                                 printf("[TLS - FAILED]\r\n");
4143                             debug(F110,
4144                                    "ck_tn_tls_negotiate","[TLS - FAILED]",0);
4145                             return -1;
4146                         }
4147                     }
4148                 } else if (ssl_check_server_name(tls_http_con, hostname)) {
4149                     if (tn_deb || debses)
4150                         tn_debug("[TLS - FAILED]");
4151                     else if ( verbosity )
4152                         printf("[TLS - FAILED]\r\n");
4153                     debug(F110,
4154                            "ck_tn_tls_negotiate","[TLS - FAILED]",0);
4155                     return -1;
4156                 }
4157             }
4158
4159             printf("[TLS - OK]\r\n");
4160             if (tn_deb || debses)
4161                 tn_debug("[TLS - OK]");
4162             debug(F110,"ck_ssl_outgoing","[TLS - OK]",0);
4163             ssl_display_connect_details(tls_http_con,0,verbosity);
4164         }
4165     }
4166     return(0);  /* success */
4167 }
4168 #endif /* NOHTTP */
4169 int
4170 ck_ssl_renegotiate_ciphers()
4171 {
4172
4173     if ( !ck_ssleay_is_installed() )
4174         return(0);
4175
4176     if ( !sstelnet )
4177         return(0);
4178
4179     if ( ssl_active_flag )
4180         return SSL_renegotiate(ssl_con);
4181     else if ( tls_active_flag )
4182         return SSL_renegotiate(tls_con);
4183     return(0);
4184 }
4185
4186 #ifdef NT
4187 int 
4188 ck_X509_save_cert_to_user_store(X509 *cert)
4189 {
4190 #ifdef X509V3_EXT_DUMP_UNKNOWN
4191     char path[CKMAXPATH];
4192     char hash[16];
4193     char * GetAppData(int);
4194     BIO * out=NULL;
4195
4196     if ( cert == NULL )
4197         return(0);
4198
4199     sprintf(hash,"%08lx",X509_subject_name_hash(cert));
4200     ckmakmsg(path,CKMAXPATH,GetAppData(0),"kermit 95/certs/",
4201              hash,".0");
4202
4203     
4204     out=BIO_new(BIO_s_file());
4205     if (out == NULL)
4206     {
4207         ERR_print_errors(bio_err);
4208         return(0);
4209     }
4210     if (BIO_write_filename(out,path) <= 0) {
4211         perror(path);
4212         return(0);
4213     }
4214
4215     X509_print_ex(out, cert, XN_FLAG_SEP_MULTILINE, X509V3_EXT_DUMP_UNKNOWN);
4216     if (!PEM_write_bio_X509(out,cert)) {
4217         BIO_printf(bio_err,"unable to write certificate\n");
4218         ERR_print_errors(bio_err);
4219         BIO_free_all(out);
4220         return(0);
4221     }
4222     BIO_free_all(out);
4223     return(1);
4224 #else /* X509V3_EXT_DUMP_UNKNOWN */
4225     return(0);
4226 #endif /* X509V3_EXT_DUMP_UNKNOWN */
4227 }
4228 #endif /* NT */
4229
4230 #ifndef OS2
4231 /* The following function should be replaced by institution specific */
4232 /* code that will convert an X509 cert structure to a userid for the */
4233 /* purposes of client to host login.  The example code included      */
4234 /* simply returns the UID field of the Subject if it exists.         */
4235
4236 /* X509_to_user() returns 0 if valid userid in 'userid', else -1 */
4237 int
4238 X509_to_user(X509 *peer_cert, char *userid, int len)
4239 {
4240 #ifdef X509_UID_TO_USER
4241     /* BEGIN EXAMPLE */
4242     int err;
4243
4244     if (!(peer_cert && userid) || len <= 0)
4245         return -1;
4246
4247     userid[0] = '\0';
4248     debug(F110,"X509_to_user() subject",
4249            X509_NAME_oneline(X509_get_subject_name(peer_cert),NULL,0),0);
4250
4251     /* userid is in cert subject /UID */
4252     err = X509_NAME_get_text_by_NID(X509_get_subject_name(peer_cert),
4253 #ifndef NID_x500UniqueIdentifier
4254                                      NID_uniqueIdentifier,
4255 #else
4256                                      NID_x500UniqueIdentifier,
4257 #endif
4258                                      userid, len);
4259
4260     debug(F111,"X509_to_user() userid",userid,err);
4261     if (err > 0)
4262         return 0;
4263
4264     /* END EXAMPLE */
4265 #else /* X509_UID_TO_USER */
4266 #ifdef X509_SUBJECT_ALT_NAME_TO_USER
4267     /* BEGIN EXAMPLE */
4268     int i;
4269     X509_EXTENSION *ext = NULL;
4270     STACK_OF(GENERAL_NAME) *ialt = NULL;
4271     GENERAL_NAME *gen = NULL;
4272     char email[256];
4273
4274     if (!(peer_cert && userid) || len <= 0)
4275         return -1;
4276
4277     userid[0] = '\0';
4278     email[0] = '\0';
4279     debug(F110,"X509_to_user() subject",
4280            X509_NAME_oneline(X509_get_subject_name(peer_cert),NULL,0),0);
4281
4282     if ((i = X509_get_ext_by_NID(peer_cert, NID_subject_alt_name, -1))<0)
4283         return -1;
4284     if (!(ext = X509_get_ext(peer_cert, i)))
4285         return -1;
4286     X509V3_add_standard_extensions();
4287     if (!(ialt = X509V3_EXT_d2i(ext)))
4288         return -1;
4289     for (i = 0; i < sk_GENERAL_NAME_num(ialt); i++) {
4290         gen = sk_GENERAL_NAME_value(ialt, i);
4291         if (gen->type == GEN_DNS) {
4292             if (!gen->d.ia5 || !gen->d.ia5->length)
4293               break;
4294             if (strlen(gen->d.ia5->data) != gen->d.ia5->length) {
4295                 /* Ignoring IA5String containing null character */
4296                 continue;
4297             }
4298             if ( gen->d.ia5->length + 1 > sizeof(email) ) {
4299                 goto cleanup;
4300             }
4301             memcpy(email, gen->d.ia5->data, gen->d.ia5->length);
4302             email[gen->d.ia5->length] = 0;
4303             break;
4304         }
4305     }
4306   cleanup:
4307     X509V3_EXT_cleanup();
4308     if (ialt)
4309         sk_GENERAL_NAME_free(ialt);
4310
4311     debug(F110,"X509_to_user() email",email,0);
4312
4313     if ( email[0] ) {
4314         char * domain = NULL;
4315
4316         /* Find domain */
4317         for ( i=0 ; email[i] ; i++ ) {
4318             if ( email[i] == '@' ) {
4319                 email[i] = '\0';
4320                 domain = &email[i+1];
4321                 break;
4322             }
4323         }
4324
4325         if ( domain ) {
4326             /* XXX - Put code to Verify domain here */
4327
4328             if ( /* domain is okay */ 1 )
4329                 ckstrncpy(userid,email,len);
4330         }
4331     }
4332
4333     return(userid[0] ? 0 : -1);
4334     /* END EXAMPLE */
4335 #endif /* X509_SUBJECT_ALT_NAME_TO_USER */
4336 #endif /* X509_UID_TO_USER */
4337     return -1;
4338 }
4339
4340 /* The following function should be replaced by institution specific */
4341 /* code that will determine whether or not the combination of the    */
4342 /* provided X509 certificate and username is valid for automatic     */
4343 /* login.   Whereas X509_to_user() is used to provide authentication */
4344 /* of the user, the X509_userok() function is used to provide        */
4345 /* authorization.  The certificate passed into X509_userok() does    */
4346 /* need to map to a userid; nor would the userid it would map to     */
4347 /* need to match the userid provided to the function.  There are     */
4348 /* numerous circumstances in which it is beneficial to have the ability */
4349 /* for multiple users to gain access to a common account such as     */
4350 /* 'root' on Unix; or a class account on a web server.  In Unix we   */
4351 /* implement this capability with the ~userid/.tlslogin file which   */
4352 /* a list of X509 certificates which may be used to access the       */
4353 /* account 'userid'.                                                 */
4354
4355 /* X509_to_user() returns 0 if access is denied; 1 is access is permitted */
4356 int
4357 X509_userok(X509 * peer_cert, const char * userid)
4358 {
4359 #ifndef VMS
4360     /* check if clients cert is in "user"'s ~/.tlslogin file */
4361     char buf[512];
4362     int r = 0;
4363     FILE *fp;
4364     struct passwd *pwd;
4365     X509 *file_cert;
4366
4367     if ( peer_cert == NULL )
4368         return(0);
4369
4370     if (!(pwd = getpwnam(userid)))
4371        return 0;
4372     if (strlen(pwd->pw_dir) > 500)
4373        return(0);
4374     sprintf(buf, "%s/.tlslogin", pwd->pw_dir);
4375
4376     if (!(fp = fopen(buf, "r")))
4377         return 0;
4378     while (!r && (file_cert = PEM_read_X509(fp, NULL, NULL, NULL))) {
4379         if (!ASN1_STRING_cmp(peer_cert->signature, file_cert->signature))
4380             r = 1;
4381         X509_free(file_cert);
4382     }
4383     fclose(fp);
4384     return(r);
4385 #else /* VMS */
4386     /* Need to implement an appropriate function for VMS */
4387     return(0);
4388 #endif /* VMS */
4389 }
4390 #endif /* OS2 */
4391 #endif /* CK_SSL */