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