ssl.cpp 36.8 KB
Newer Older
1
/*
2
   Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; version 2 of the License.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; see the file COPYING. If not, write to the
   Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
   MA  02110-1301  USA.
*/

/*  SSL source implements all openssl compatibility API functions
 *
 *  TODO: notes are mostly api additions to allow compilation with mysql
 *  they don't affect normal modes but should be provided for completeness

 *  stunnel functions at end of file
 */



/*  see man pages for function descriptions */

#include "runtime.hpp"
#include "openssl/ssl.h"
#include "handshake.hpp"
#include "yassl_int.hpp"
#include "md5.hpp"              // for TaoCrypt MD5 size assert
#include "md4.hpp"              // for TaoCrypt MD4 size assert
#include "file.hpp"             // for TaoCrypt Source
#include "coding.hpp"           // HexDecoder
#include "helpers.hpp"          // for placement new hack
40
41
#include "rsa.hpp"              // for TaoCrypt RSA key decode
#include "dsa.hpp"              // for TaoCrypt DSA key decode
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include <stdio.h>

#ifdef _WIN32
    #include <windows.h>    // FindFirstFile etc..
#else
    #include <sys/types.h>  // file helper
    #include <sys/stat.h>   // stat
    #include <dirent.h>     // opendir
#endif


namespace yaSSL {



int read_file(SSL_CTX* ctx, const char* file, int format, CertType type)
{
59
60
    int ret = SSL_SUCCESS;

61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
    if (format != SSL_FILETYPE_ASN1 && format != SSL_FILETYPE_PEM)
        return SSL_BAD_FILETYPE;

    if (file == NULL || !file[0])
      return SSL_BAD_FILE;

    FILE* input = fopen(file, "rb");
    if (!input)
        return SSL_BAD_FILE;

    if (type == CA) {
        // may have a bunch of CAs
        x509* ptr;
        while ( (ptr = PemToDer(input, Cert)) )
            ctx->AddCA(ptr);

        if (!feof(input)) {
            fclose(input);
            return SSL_BAD_FILE;
        }
    }
    else {
        x509*& x = (type == Cert) ? ctx->certificate_ : ctx->privateKey_;

        if (format == SSL_FILETYPE_ASN1) {
            fseek(input, 0, SEEK_END);
            long sz = ftell(input);
            rewind(input);
            x = NEW_YS x509(sz); // takes ownership
            size_t bytes = fread(x->use_buffer(), sz, 1, input);
            if (bytes != 1) {
                fclose(input);
                return SSL_BAD_FILE;
            }
        }
        else {
            EncryptedInfo info;
            x = PemToDer(input, type, &info);
            if (!x) {
                fclose(input);
                return SSL_BAD_FILE;
            }
            if (info.set) {
                // decrypt
                char password[80];
                pem_password_cb cb = ctx->GetPasswordCb();
                if (!cb) {
                    fclose(input);
                    return SSL_BAD_FILE;
                }
                int passwordSz = cb(password, sizeof(password), 0,
                                    ctx->GetUserData());
                byte key[AES_256_KEY_SZ];  // max sizes
                byte iv[AES_IV_SZ];
                
                // use file's salt for key derivation, but not real iv
                TaoCrypt::Source source(info.iv, info.ivSz);
                TaoCrypt::HexDecoder dec(source);
                memcpy(info.iv, source.get_buffer(), min((uint)sizeof(info.iv),
                                                         source.size()));
                EVP_BytesToKey(info.name, "MD5", info.iv, (byte*)password,
                               passwordSz, 1, key, iv);

                mySTL::auto_ptr<BulkCipher> cipher;
                if (strncmp(info.name, "DES-CBC", 7) == 0)
                    cipher.reset(NEW_YS DES);
                else if (strncmp(info.name, "DES-EDE3-CBC", 13) == 0)
                    cipher.reset(NEW_YS DES_EDE);
                else if (strncmp(info.name, "AES-128-CBC", 13) == 0)
                    cipher.reset(NEW_YS AES(AES_128_KEY_SZ));
                else if (strncmp(info.name, "AES-192-CBC", 13) == 0)
                    cipher.reset(NEW_YS AES(AES_192_KEY_SZ));
                else if (strncmp(info.name, "AES-256-CBC", 13) == 0)
                    cipher.reset(NEW_YS AES(AES_256_KEY_SZ));
                else {
                    fclose(input);
                    return SSL_BAD_FILE;
                }
                cipher->set_decryptKey(key, info.iv);
                mySTL::auto_ptr<x509> newx(NEW_YS x509(x->get_length()));   
                cipher->decrypt(newx->use_buffer(), x->get_buffer(),
                                x->get_length());
                ysDelete(x);
                x = newx.release();
            }
        }
    }
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163

    if (type == PrivateKey && ctx->privateKey_) {
        // see if key is valid early
        TaoCrypt::Source rsaSource(ctx->privateKey_->get_buffer(),
                                   ctx->privateKey_->get_length());
        TaoCrypt::RSA_PrivateKey rsaKey;
        rsaKey.Initialize(rsaSource);

        if (rsaSource.GetError().What()) {
            // rsa failed see if DSA works

            TaoCrypt::Source dsaSource(ctx->privateKey_->get_buffer(),
                                       ctx->privateKey_->get_length());
            TaoCrypt::DSA_PrivateKey dsaKey;
            dsaKey.Initialize(dsaSource);

164
            if (dsaSource.GetError().What()) {
165
166
167
168
169
170
                // neither worked
                ret = SSL_FAILURE;
            }
        }
    }

171
    fclose(input);
172
    return ret;
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
}


extern "C" {


SSL_METHOD* SSLv3_method()
{
    return SSLv3_client_method();
}


SSL_METHOD* SSLv3_server_method()
{
    return NEW_YS SSL_METHOD(server_end, ProtocolVersion(3,0));
}


SSL_METHOD* SSLv3_client_method()
{
    return NEW_YS SSL_METHOD(client_end, ProtocolVersion(3,0));
}


SSL_METHOD* TLSv1_server_method()
{
    return NEW_YS SSL_METHOD(server_end, ProtocolVersion(3,1));
}


SSL_METHOD* TLSv1_client_method()
{
    return NEW_YS SSL_METHOD(client_end, ProtocolVersion(3,1));
}


SSL_METHOD* TLSv1_1_server_method()
{
    return NEW_YS SSL_METHOD(server_end, ProtocolVersion(3,2));
}


SSL_METHOD* TLSv1_1_client_method()
{
    return NEW_YS SSL_METHOD(client_end, ProtocolVersion(3,2));
}


SSL_METHOD* SSLv23_server_method()
{
    // compatibility only, no version 2 support, but does SSL 3 and TLS 1
    return NEW_YS SSL_METHOD(server_end, ProtocolVersion(3,2), true);
}


SSL_METHOD* SSLv23_client_method()
{
    // compatibility only, no version 2 support, but does SSL 3 and TLS 1
    // though it sends TLS1 hello not SSLv2 so SSLv3 only servers will decline
    // TODO: maybe add support to send SSLv2 hello ???
    return NEW_YS SSL_METHOD(client_end, ProtocolVersion(3,2), true);
}


SSL_CTX* SSL_CTX_new(SSL_METHOD* method)
{
    return NEW_YS SSL_CTX(method);
}


void SSL_CTX_free(SSL_CTX* ctx)
{
    ysDelete(ctx);
}


SSL* SSL_new(SSL_CTX* ctx)
{
    return NEW_YS SSL(ctx);
}


void SSL_free(SSL* ssl)
{
    ysDelete(ssl);
}


int SSL_set_fd(SSL* ssl, YASSL_SOCKET_T fd)
{
    ssl->useSocket().set_fd(fd);
    return SSL_SUCCESS;
}


YASSL_SOCKET_T SSL_get_fd(const SSL* ssl)
{
    return ssl->getSocket().get_fd();
}


// if you get an error from connect see note at top of README
int SSL_connect(SSL* ssl)
{
    if (ssl->GetError() == YasslError(SSL_ERROR_WANT_READ))
        ssl->SetError(no_error);

    if (ssl->GetError() == YasslError(SSL_ERROR_WANT_WRITE)) {
    
        ssl->SetError(no_error);
        ssl->SendWriteBuffered();
        if (!ssl->GetError())
            ssl->useStates().UseConnect() =
                             ConnectState(ssl->getStates().GetConnect() + 1);
    }

    ClientState neededState;

    switch (ssl->getStates().GetConnect()) {

    case CONNECT_BEGIN :
        sendClientHello(*ssl);
        if (!ssl->GetError())
            ssl->useStates().UseConnect() = CLIENT_HELLO_SENT;

    case CLIENT_HELLO_SENT :
        neededState = ssl->getSecurity().get_resuming() ?
                      serverFinishedComplete : serverHelloDoneComplete;
        while (ssl->getStates().getClient() < neededState) {
            if (ssl->GetError()) break;
            processReply(*ssl);
            // if resumption failed, reset needed state 
            if (neededState == serverFinishedComplete)
                if (!ssl->getSecurity().get_resuming())
                    neededState = serverHelloDoneComplete;
        }
        if (!ssl->GetError())
            ssl->useStates().UseConnect() = FIRST_REPLY_DONE;

    case FIRST_REPLY_DONE :
        if(ssl->getCrypto().get_certManager().sendVerify())
            sendCertificate(*ssl);

        if (!ssl->getSecurity().get_resuming())
            sendClientKeyExchange(*ssl);

        if(ssl->getCrypto().get_certManager().sendVerify())
            sendCertificateVerify(*ssl);

        sendChangeCipher(*ssl);
        sendFinished(*ssl, client_end);
        ssl->flushBuffer();

        if (!ssl->GetError())
            ssl->useStates().UseConnect() = FINISHED_DONE;

    case FINISHED_DONE :
        if (!ssl->getSecurity().get_resuming())
            while (ssl->getStates().getClient() < serverFinishedComplete) {
                if (ssl->GetError()) break;
                processReply(*ssl);
            }
        if (!ssl->GetError())
            ssl->useStates().UseConnect() = SECOND_REPLY_DONE;

    case SECOND_REPLY_DONE :
        ssl->verifyState(serverFinishedComplete);
        ssl->useLog().ShowTCP(ssl->getSocket().get_fd());

        if (ssl->GetError()) {
            GetErrors().Add(ssl->GetError());
            return SSL_FATAL_ERROR;
        }   
        return SSL_SUCCESS;

    default :
        return SSL_FATAL_ERROR; // unkown state
    }
}


int SSL_write(SSL* ssl, const void* buffer, int sz)
{
    return sendData(*ssl, buffer, sz);
}


int SSL_read(SSL* ssl, void* buffer, int sz)
{
    Data data(min(sz, MAX_RECORD_SIZE), static_cast<opaque*>(buffer));
    return receiveData(*ssl, data);
}


int SSL_accept(SSL* ssl)
{
    if (ssl->GetError() == YasslError(SSL_ERROR_WANT_READ))
        ssl->SetError(no_error);

    if (ssl->GetError() == YasslError(SSL_ERROR_WANT_WRITE)) {
    
        ssl->SetError(no_error);
        ssl->SendWriteBuffered();
        if (!ssl->GetError())
            ssl->useStates().UseAccept() =
                             AcceptState(ssl->getStates().GetAccept() + 1);
    }

    switch (ssl->getStates().GetAccept()) {

    case ACCEPT_BEGIN :
        processReply(*ssl);
        if (!ssl->GetError())
            ssl->useStates().UseAccept() = ACCEPT_FIRST_REPLY_DONE;

    case ACCEPT_FIRST_REPLY_DONE :
        sendServerHello(*ssl);

        if (!ssl->getSecurity().get_resuming()) {
            sendCertificate(*ssl);

            if (ssl->getSecurity().get_connection().send_server_key_)
                sendServerKeyExchange(*ssl);

            if(ssl->getCrypto().get_certManager().verifyPeer())
                sendCertificateRequest(*ssl);

            sendServerHelloDone(*ssl);
            ssl->flushBuffer();
        }
      
        if (!ssl->GetError())
            ssl->useStates().UseAccept() = SERVER_HELLO_DONE;

    case SERVER_HELLO_DONE :
        if (!ssl->getSecurity().get_resuming()) {
            while (ssl->getStates().getServer() < clientFinishedComplete) {
                if (ssl->GetError()) break;
                processReply(*ssl);
            }
        }
        if (!ssl->GetError())
            ssl->useStates().UseAccept() = ACCEPT_SECOND_REPLY_DONE;

    case ACCEPT_SECOND_REPLY_DONE :
        sendChangeCipher(*ssl);
        sendFinished(*ssl, server_end);
        ssl->flushBuffer();

        if (!ssl->GetError())
            ssl->useStates().UseAccept() = ACCEPT_FINISHED_DONE;

    case ACCEPT_FINISHED_DONE :
        if (ssl->getSecurity().get_resuming()) {
            while (ssl->getStates().getServer() < clientFinishedComplete) {
                if (ssl->GetError()) break;
                processReply(*ssl);
            }
        }
        if (!ssl->GetError())
            ssl->useStates().UseAccept() = ACCEPT_THIRD_REPLY_DONE;

    case ACCEPT_THIRD_REPLY_DONE :
        ssl->useLog().ShowTCP(ssl->getSocket().get_fd());

        if (ssl->GetError()) {
            GetErrors().Add(ssl->GetError());
            return SSL_FATAL_ERROR;
        }
        return SSL_SUCCESS;

    default:
        return SSL_FATAL_ERROR; // unknown state
    }
}


int SSL_do_handshake(SSL* ssl)
{
    if (ssl->getSecurity().get_parms().entity_ == client_end)
        return SSL_connect(ssl);
    else
        return SSL_accept(ssl);
}


int SSL_clear(SSL* ssl)
{
    GetErrors().Remove();

    return SSL_SUCCESS;
}


int SSL_shutdown(SSL* ssl)
{
    if (!ssl->GetQuietShutdown()) {
      Alert alert(warning, close_notify);
      sendAlert(*ssl, alert);
    }
    ssl->useLog().ShowTCP(ssl->getSocket().get_fd(), true);

    GetErrors().Remove();

    return SSL_SUCCESS;
}


void SSL_set_quiet_shutdown(SSL *ssl,int mode)
{
    ssl->SetQuietShutdown(mode != 0);
}


int SSL_get_quiet_shutdown(SSL *ssl)
{
    return ssl->GetQuietShutdown();
}


/* on by default but allow user to turn off */
long SSL_CTX_set_session_cache_mode(SSL_CTX* ctx, long mode)
{
    if (mode == SSL_SESS_CACHE_OFF)
        ctx->SetSessionCacheOff();

    if (mode == SSL_SESS_CACHE_NO_AUTO_CLEAR)
        ctx->SetSessionCacheFlushOff();

    return SSL_SUCCESS;
}


SSL_SESSION* SSL_get_session(SSL* ssl)
{
    if (ssl->getSecurity().GetContext()->GetSessionCacheOff())
        return 0;

    return GetSessions().lookup(
        ssl->getSecurity().get_connection().sessionID_);
}


int SSL_set_session(SSL* ssl, SSL_SESSION* session)
{
    if (ssl->getSecurity().GetContext()->GetSessionCacheOff())
        return SSL_FAILURE;

    ssl->set_session(session);
    return SSL_SUCCESS;
}


int SSL_session_reused(SSL* ssl)
{
    return ssl->getSecurity().get_resuming();
}


long SSL_SESSION_set_timeout(SSL_SESSION* sess, long t)
{
    if (!sess)
        return SSL_ERROR_NONE;

    sess->SetTimeOut(t);
    return SSL_SUCCESS;
}


long SSL_get_default_timeout(SSL* /*ssl*/)
{
    return DEFAULT_TIMEOUT;
}


void SSL_flush_sessions(SSL_CTX *ctx, long /* tm */)
{
    if (ctx->GetSessionCacheOff())
        return;

    GetSessions().Flush();
}


const char* SSL_get_cipher_name(SSL* ssl)
{ 
    return SSL_get_cipher(ssl); 
}


const char* SSL_get_cipher(SSL* ssl)
{
    return ssl->getSecurity().get_parms().cipher_name_;
}


// SSLv2 only, not implemented
char* SSL_get_shared_ciphers(SSL* /*ssl*/, char* buf, int len)
{
    return strncpy(buf, "Not Implemented, SSLv2 only", len);
}


const char* SSL_get_cipher_list(SSL* ssl, int priority)
{
    if (priority < 0 || priority >= MAX_CIPHERS)
        return 0;

    if (ssl->getSecurity().get_parms().cipher_list_[priority][0])
        return ssl->getSecurity().get_parms().cipher_list_[priority];

    return 0;
}


int SSL_CTX_set_cipher_list(SSL_CTX* ctx, const char* list)
{
    if (ctx->SetCipherList(list))
        return SSL_SUCCESS;
    else
        return SSL_FAILURE;
}


const char* SSL_get_version(SSL* ssl)
{
    static const char* version3 =  "SSLv3";
    static const char* version31 = "TLSv1";

    return ssl->isTLS() ? version31 : version3;
}

const char* SSLeay_version(int)
{
    static const char* version = "SSLeay yaSSL compatibility";
    return version;
}


int SSL_get_error(SSL* ssl, int /*previous*/)
{
    return ssl->getStates().What();
}



/* turn on yaSSL zlib compression
   returns 0 for success, else error (not built in)
   only need to turn on for client, becuase server on by default if built in
   but calling for server will tell you whether it's available or not
*/
int SSL_set_compression(SSL* ssl)   /* Chad didn't rename to ya~ because it is prob. bug. */
{
    return ssl->SetCompression();
}



X509* SSL_get_peer_certificate(SSL* ssl)
{
    return ssl->getCrypto().get_certManager().get_peerX509();
}


void X509_free(X509* /*x*/)
{
    // peer cert set for deletion during destruction
    // no need to delete now
}


X509* X509_STORE_CTX_get_current_cert(X509_STORE_CTX* ctx)
{
    return ctx->current_cert;
}


int X509_STORE_CTX_get_error(X509_STORE_CTX* ctx)
{
    return ctx->error;
}


int X509_STORE_CTX_get_error_depth(X509_STORE_CTX* ctx)
{
    return ctx->error_depth;
}


// copy name into buffer, at most sz bytes, if buffer is null
// will malloc buffer, caller responsible for freeing
char* X509_NAME_oneline(X509_NAME* name, char* buffer, int sz)
{
    if (!name->GetName()) return buffer;

    int len    = (int)strlen(name->GetName()) + 1;
    int copySz = min(len, sz);

    if (!buffer) {
        buffer = (char*)malloc(len);
        if (!buffer) return buffer;
        copySz = len;
    }

    if (copySz == 0)
        return buffer;

    memcpy(buffer, name->GetName(), copySz - 1);
    buffer[copySz - 1] = 0;

    return buffer;
}


X509_NAME* X509_get_issuer_name(X509* x)
{
    return  x->GetIssuer();
}


X509_NAME* X509_get_subject_name(X509* x)
{
    return x->GetSubject();
}


void SSL_load_error_strings()   // compatibility only 
{}


void SSL_set_connect_state(SSL*)
{
    // already a client by default
}


void SSL_set_accept_state(SSL* ssl)
{
    ssl->useSecurity().use_parms().entity_ = server_end;
}


long SSL_get_verify_result(SSL*)
{
    // won't get here if not OK
    return X509_V_OK;
}


long SSL_CTX_sess_set_cache_size(SSL_CTX* /*ctx*/, long /*sz*/)
{
    // unlimited size, can't set for now
    return 0;
}


long SSL_CTX_get_session_cache_mode(SSL_CTX*)
{
    // always 0, unlimited size for now
    return 0;
}


long SSL_CTX_set_tmp_dh(SSL_CTX* ctx, DH* dh)
{
    if (ctx->SetDH(*dh))
        return SSL_SUCCESS;
    else
        return SSL_FAILURE;
}


int SSL_CTX_use_certificate_file(SSL_CTX* ctx, const char* file, int format)
{
    return read_file(ctx, file, format, Cert);
}


int SSL_CTX_use_PrivateKey_file(SSL_CTX* ctx, const char* file, int format)
{
    return read_file(ctx, file, format, PrivateKey);
}


void SSL_CTX_set_verify(SSL_CTX* ctx, int mode, VerifyCallback vc)
{
    if (mode & SSL_VERIFY_PEER)
        ctx->setVerifyPeer();

    if (mode == SSL_VERIFY_NONE)
        ctx->setVerifyNone();

    if (mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)
        ctx->setFailNoCert();

    ctx->setVerifyCallback(vc);
}


int SSL_CTX_load_verify_locations(SSL_CTX* ctx, const char* file,
                                  const char* path)
{
    int       ret = SSL_FAILURE;
    const int HALF_PATH = 128;

    if (file) ret = read_file(ctx, file, SSL_FILETYPE_PEM, CA);

    if (ret == SSL_SUCCESS && path) {
        // call read_file for each reqular file in path
#ifdef _WIN32

        WIN32_FIND_DATA FindFileData;
        HANDLE hFind;

787
788
789
790
791
792
793
794
        const int DELIMITER_SZ      = 2;
        const int DELIMITER_STAR_SZ = 3;
        int pathSz = (int)strlen(path);
        int nameSz = pathSz + DELIMITER_STAR_SZ + 1; // plus 1 for terminator
        char* name = NEW_YS char[nameSz];  // directory specification
        memset(name, 0, nameSz);
        strncpy(name, path, nameSz - DELIMITER_STAR_SZ - 1);
        strncat(name, "\\*", DELIMITER_STAR_SZ);
795
796

        hFind = FindFirstFile(name, &FindFileData);
797
798
799
800
        if (hFind == INVALID_HANDLE_VALUE) {
            ysArrayDelete(name);
            return SSL_BAD_PATH;
        }
801
802

        do {
803
804
805
806
807
808
809
810
811
812
813
814
815
            if (!(FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
                int curSz = (int)strlen(FindFileData.cFileName);
                if (pathSz + curSz + DELIMITER_SZ + 1 > nameSz) {
                    ysArrayDelete(name);
                    // plus 1 for terminator
                    nameSz = pathSz + curSz + DELIMITER_SZ + 1;
                    name = NEW_YS char[nameSz];
                }
                memset(name, 0, nameSz);
                strncpy(name, path, nameSz - curSz - DELIMITER_SZ - 1);
                strncat(name, "\\", DELIMITER_SZ);
                strncat(name, FindFileData.cFileName,
                                            nameSz - pathSz - DELIMITER_SZ - 1);
816
817
818
819
                ret = read_file(ctx, name, SSL_FILETYPE_PEM, CA);
            }
        } while (ret == SSL_SUCCESS && FindNextFile(hFind, &FindFileData));

820
        ysArrayDelete(name);
821
822
823
824
825
826
827
828
        FindClose(hFind);

#else   // _WIN32
        DIR* dir = opendir(path);
        if (!dir) return SSL_BAD_PATH;

        struct dirent* entry;
        struct stat    buf;
829
830
831
832
        const int DELIMITER_SZ = 1;
        int pathSz = (int)strlen(path);
        int nameSz = pathSz + DELIMITER_SZ + 1; //plus 1 for null terminator
        char* name = NEW_YS char[nameSz];  // directory specification
833
834

        while (ret == SSL_SUCCESS && (entry = readdir(dir))) {
835
836
837
838
839
840
841
842
843
844
845
            int curSz = (int)strlen(entry->d_name);
            if (pathSz + curSz + DELIMITER_SZ + 1 > nameSz) {
                ysArrayDelete(name);
                nameSz = pathSz + DELIMITER_SZ + curSz + 1;
                name = NEW_YS char[nameSz];
            }
            memset(name, 0, nameSz);
            strncpy(name, path, nameSz - curSz - 1);
            strncat(name, "/",  DELIMITER_SZ);
            strncat(name, entry->d_name, nameSz - pathSz - DELIMITER_SZ - 1);

846
            if (stat(name, &buf) < 0) {
847
                ysArrayDelete(name);
848
849
850
                closedir(dir);
                return SSL_BAD_STAT;
            }
851
852
853
854
855
     
            if (S_ISREG(buf.st_mode))
                ret = read_file(ctx, name, SSL_FILETYPE_PEM, CA);
        }

856
        ysArrayDelete(name);
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
        closedir(dir);

#endif
    }

    return ret;
}


int SSL_CTX_set_default_verify_paths(SSL_CTX* /*ctx*/)
{
    // TODO: figure out way to set/store default path, then call load_verify
    return SSL_NOT_IMPLEMENTED;
}


int SSL_CTX_set_session_id_context(SSL_CTX*, const unsigned char*,
                                    unsigned int)
{
    // No application specific context needed for yaSSL
    return SSL_SUCCESS;
}


int SSL_CTX_check_private_key(SSL_CTX* /*ctx*/)
{
    // TODO: check private against public for RSA match
    return SSL_NOT_IMPLEMENTED;
}


// TODO: all session stats
long SSL_CTX_sess_accept(SSL_CTX* ctx)
{
    return ctx->GetStats().accept_;
}


long SSL_CTX_sess_connect(SSL_CTX* ctx)
{
    return ctx->GetStats().connect_;
}


long SSL_CTX_sess_accept_good(SSL_CTX* ctx)
{
    return ctx->GetStats().acceptGood_;
}


long SSL_CTX_sess_connect_good(SSL_CTX* ctx)
{
    return ctx->GetStats().connectGood_;
}


long SSL_CTX_sess_accept_renegotiate(SSL_CTX* ctx)
{
    return ctx->GetStats().acceptRenegotiate_;
}


long SSL_CTX_sess_connect_renegotiate(SSL_CTX* ctx)
{
    return ctx->GetStats().connectRenegotiate_;
}


long SSL_CTX_sess_hits(SSL_CTX* ctx)
{
    return ctx->GetStats().hits_;
}


long SSL_CTX_sess_cb_hits(SSL_CTX* ctx)
{
    return ctx->GetStats().cbHits_;
}


long SSL_CTX_sess_cache_full(SSL_CTX* ctx)
{
    return ctx->GetStats().cacheFull_;
}


long SSL_CTX_sess_misses(SSL_CTX* ctx)
{
    return ctx->GetStats().misses_;
}


long SSL_CTX_sess_timeouts(SSL_CTX* ctx)
{
    return ctx->GetStats().timeouts_;
}


long SSL_CTX_sess_number(SSL_CTX* ctx)
{
    return ctx->GetStats().number_;
}


long SSL_CTX_sess_get_cache_size(SSL_CTX* ctx)
{
    return ctx->GetStats().getCacheSize_;
}
// end session stats TODO:


int SSL_CTX_get_verify_mode(SSL_CTX* ctx)
{
    return ctx->GetStats().verifyMode_;
}


int SSL_get_verify_mode(SSL* ssl)
{
    return ssl->getSecurity().GetContext()->GetStats().verifyMode_;
}


int SSL_CTX_get_verify_depth(SSL_CTX* ctx)
{
    return ctx->GetStats().verifyDepth_;
}


int SSL_get_verify_depth(SSL* ssl)
{
    return ssl->getSecurity().GetContext()->GetStats().verifyDepth_;
}


long SSL_CTX_set_options(SSL_CTX*, long)
{
    // TDOD:
    return SSL_SUCCESS;
}


void SSL_CTX_set_info_callback(SSL_CTX*, void (*)())
{