summaryrefslogtreecommitdiffstats
path: root/extra/wolfssl/wolfssl/src/crl.c
blob: 559e459c1deec0293ee42a4a07a8bed46e8f02e0 (plain)
1
2
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
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
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
/* crl.c
 *
 * Copyright (C) 2006-2023 wolfSSL Inc.
 *
 * This file is part of wolfSSL.
 *
 * wolfSSL 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; either version 2 of the License, or
 * (at your option) any later version.
 *
 * wolfSSL 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; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA
 */


/*
CRL Options:
 * CRL_STATIC_REVOKED_LIST:                                        default: off
 *                         Enables fixed static list of RevokedCerts to allow
 *                         for a binary search.
 * CRL_MAX_REVOKED_CERTS:                                          default: 4
 *                         Specifies the number of buffers to hold RevokedCerts.
 *                         The default value is set to 4.
*/
#ifdef HAVE_CONFIG_H
    #include <config.h>
#endif

#include <wolfssl/wolfcrypt/settings.h>

#ifndef WOLFCRYPT_ONLY
#ifdef HAVE_CRL

#include <wolfssl/internal.h>
#include <wolfssl/error-ssl.h>

#ifndef WOLFSSL_LINUXKM
    #include <string.h>
#endif

#ifdef HAVE_CRL_MONITOR
    #if (defined(__MACH__) || defined(__FreeBSD__) || defined(__linux__))
        static int StopMonitor(int mfd);
    #else
        #error "CRL monitor only currently supported on linux or mach"
    #endif
#endif /* HAVE_CRL_MONITOR */


/* Initialize CRL members */
int InitCRL(WOLFSSL_CRL* crl, WOLFSSL_CERT_MANAGER* cm)
{
    WOLFSSL_ENTER("InitCRL");
    if(cm != NULL)
        crl->heap = cm->heap;
    else
        crl->heap = NULL;
    crl->cm = cm;
    crl->crlList  = NULL;
    crl->currentEntry = NULL;
    crl->monitors[0].path = NULL;
    crl->monitors[1].path = NULL;
#ifdef HAVE_CRL_MONITOR
    crl->tid   =  0;
    crl->mfd   = -1;    /* mfd for bsd is kqueue fd, eventfd for linux */
    crl->setup = 0;     /* thread setup done predicate */
    if (pthread_cond_init(&crl->cond, 0) != 0) {
        WOLFSSL_MSG("Pthread condition init failed");
        return BAD_COND_E;
    }
#endif
#ifdef HAVE_CRL_IO
    crl->crlIOCb = NULL;
#endif
    if (wc_InitMutex(&crl->crlLock) != 0) {
        WOLFSSL_MSG("Init Mutex failed");
        return BAD_MUTEX_E;
    }

    return 0;
}


/* Initialize CRL Entry */
static int InitCRL_Entry(CRL_Entry* crle, DecodedCRL* dcrl, const byte* buff,
                         int verified, void* heap)
{
    WOLFSSL_ENTER("InitCRL_Entry");

    XMEMCPY(crle->issuerHash, dcrl->issuerHash, CRL_DIGEST_SIZE);
    /* XMEMCPY(crle->crlHash, dcrl->crlHash, CRL_DIGEST_SIZE);
     * copy the hash here if needed for optimized comparisons */
    XMEMCPY(crle->lastDate, dcrl->lastDate, MAX_DATE_SIZE);
    XMEMCPY(crle->nextDate, dcrl->nextDate, MAX_DATE_SIZE);
    crle->lastDateFormat = dcrl->lastDateFormat;
    crle->nextDateFormat = dcrl->nextDateFormat;
    crle->version = dcrl->version;

#if defined(OPENSSL_EXTRA)
    crle->lastDateAsn1.length = MAX_DATE_SIZE;
    XMEMCPY (crle->lastDateAsn1.data, crle->lastDate,
             crle->lastDateAsn1.length);
    crle->lastDateAsn1.type = crle->lastDateFormat;
    crle->nextDateAsn1.length = MAX_DATE_SIZE;
    XMEMCPY (crle->nextDateAsn1.data, crle->nextDate,
             crle->nextDateAsn1.length);
    crle->nextDateAsn1.type = crle->nextDateFormat;

    crle->issuer = NULL;
    wolfSSL_d2i_X509_NAME(&crle->issuer, (unsigned char**)&dcrl->issuer,
                          dcrl->issuerSz);
    if (crle->issuer == NULL) {
        return WOLFSSL_FAILURE;
    }
#endif
#ifdef CRL_STATIC_REVOKED_LIST
    /* ParseCRL_CertList() has already cached the Revoked certs into
       the crle->certs array */
#else
    crle->certs = dcrl->certs;   /* take ownership */
#endif
    dcrl->certs = NULL;
    crle->totalCerts = dcrl->totalCerts;
    crle->crlNumber = dcrl->crlNumber;
    crle->verified = verified;
    if (!verified) {
        crle->tbsSz = dcrl->sigIndex - dcrl->certBegin;
        crle->signatureSz = dcrl->sigLength;
        crle->signatureOID = dcrl->signatureOID;
        crle->toBeSigned = (byte*)XMALLOC(crle->tbsSz, heap,
                                          DYNAMIC_TYPE_CRL_ENTRY);
        if (crle->toBeSigned == NULL)
            return -1;
        crle->signature = (byte*)XMALLOC(crle->signatureSz, heap,
                                         DYNAMIC_TYPE_CRL_ENTRY);
        if (crle->signature == NULL) {
            XFREE(crle->toBeSigned, heap, DYNAMIC_TYPE_CRL_ENTRY);
            crle->toBeSigned = NULL;
            return -1;
        }
        XMEMCPY(crle->toBeSigned, buff + dcrl->certBegin, crle->tbsSz);
        XMEMCPY(crle->signature, dcrl->signature, crle->signatureSz);
    #ifndef NO_SKID
        crle->extAuthKeyIdSet = dcrl->extAuthKeyIdSet;
        if (crle->extAuthKeyIdSet)
            XMEMCPY(crle->extAuthKeyId, dcrl->extAuthKeyId, KEYID_SIZE);
    #endif
    }
    else {
        crle->toBeSigned = NULL;
        crle->signature = NULL;
    }

    (void)verified;
    (void)heap;

    return 0;
}


/* Free all CRL Entry resources */
static void FreeCRL_Entry(CRL_Entry* crle, void* heap)
{
#ifdef CRL_STATIC_REVOKED_LIST
    if (crle != NULL) {
        XMEMSET(crle->certs, 0, CRL_MAX_REVOKED_CERTS*sizeof(RevokedCert));
    }
#else
    RevokedCert* tmp = crle->certs;
    RevokedCert* next;

    WOLFSSL_ENTER("FreeCRL_Entry");

    while (tmp) {
        next = tmp->next;
        XFREE(tmp, heap, DYNAMIC_TYPE_REVOKED);
        tmp = next;
    }
#endif
    if (crle->signature != NULL)
        XFREE(crle->signature, heap, DYNAMIC_TYPE_CRL_ENTRY);
    if (crle->toBeSigned != NULL)
        XFREE(crle->toBeSigned, heap, DYNAMIC_TYPE_CRL_ENTRY);
#if defined(OPENSSL_EXTRA)
    if (crle->issuer != NULL) {
        FreeX509Name(crle->issuer);
        XFREE(crle->issuer, heap, DYNAMIC_TYPE_X509);
    }
#endif
    (void)heap;
}



/* Free all CRL resources */
void FreeCRL(WOLFSSL_CRL* crl, int dynamic)
{
    CRL_Entry* tmp = crl->crlList;

    WOLFSSL_ENTER("FreeCRL");
    if (crl->monitors[0].path)
        XFREE(crl->monitors[0].path, crl->heap, DYNAMIC_TYPE_CRL_MONITOR);

    if (crl->monitors[1].path)
        XFREE(crl->monitors[1].path, crl->heap, DYNAMIC_TYPE_CRL_MONITOR);

    XFREE(crl->currentEntry, crl->heap, DYNAMIC_TYPE_CRL_ENTRY);
    crl->currentEntry = NULL;
    while(tmp) {
        CRL_Entry* next = tmp->next;
        FreeCRL_Entry(tmp, crl->heap);
        XFREE(tmp, crl->heap, DYNAMIC_TYPE_CRL_ENTRY);
        tmp = next;
    }

#ifdef HAVE_CRL_MONITOR
    if (crl->tid != 0) {
        WOLFSSL_MSG("stopping monitor thread");
        if (StopMonitor(crl->mfd) == 0) {
            int _pthread_ret = pthread_join(crl->tid, NULL);
            if (_pthread_ret != 0)
                WOLFSSL_MSG("stop monitor failed in pthread_join");
        }
        else {
            WOLFSSL_MSG("stop monitor failed");
        }
    }
    {
        int _pthread_ret = pthread_cond_destroy(&crl->cond);
        if (_pthread_ret != 0)
            WOLFSSL_MSG("pthread_cond_destroy failed in FreeCRL");
    }
#endif
    wc_FreeMutex(&crl->crlLock);
    if (dynamic)   /* free self */
        XFREE(crl, crl->heap, DYNAMIC_TYPE_CRL);
}

static int FindRevokedSerial(DecodedCert* cert, RevokedCert* rc, int totalCerts)
{
    int ret = 0;
#ifdef CRL_STATIC_REVOKED_LIST
    /* do binary search */
    int low, high, mid;

    low = 0;
    high = totalCerts - 1;

    while (low <= high) {
        mid = (low + high) / 2;

        if (XMEMCMP(rc[mid].serialNumber, cert->serial, rc->serialSz) < 0) {
            low = mid + 1;
        }
        else if (XMEMCMP(rc[mid].serialNumber, cert->serial,
                                                        rc->serialSz) > 0) {
            high = mid - 1;
        }
        else {
            WOLFSSL_MSG("Cert revoked");
            ret = CRL_CERT_REVOKED;
            break;
        }
    }
#else
    (void)totalCerts;
    /* search in the linked list*/

    while (rc) {
        if (rc->serialSz == cert->serialSz &&
               XMEMCMP(rc->serialNumber, cert->serial, rc->serialSz) == 0) {
            WOLFSSL_MSG("Cert revoked");
            ret = CRL_CERT_REVOKED;
            break;
        }
        rc = rc->next;
    }
#endif
    return ret;
}
static int CheckCertCRLList(WOLFSSL_CRL* crl, DecodedCert* cert, int *pFoundEntry)
{
    CRL_Entry* crle;
    int        foundEntry = 0;
    int        ret = 0;

    if (wc_LockMutex(&crl->crlLock) != 0) {
        WOLFSSL_MSG("wc_LockMutex failed");
        return BAD_MUTEX_E;
    }

    crle = crl->crlList;

    while (crle) {
        if (XMEMCMP(crle->issuerHash, cert->issuerHash, CRL_DIGEST_SIZE) == 0) {
            WOLFSSL_MSG("Found CRL Entry on list");

            if (crle->verified == 0) {
                Signer* ca = NULL;
            #ifndef NO_SKID
                byte extAuthKeyId[KEYID_SIZE];
            #endif
                byte issuerHash[CRL_DIGEST_SIZE];
                byte* tbs;
                word32 tbsSz = crle->tbsSz;
                byte* sig = NULL;
                word32 sigSz = crle->signatureSz;
                word32 sigOID = crle->signatureOID;
                SignatureCtx sigCtx;

                tbs = (byte*)XMALLOC(tbsSz, crl->heap, DYNAMIC_TYPE_CRL_ENTRY);
                if (tbs == NULL) {
                    wc_UnLockMutex(&crl->crlLock);
                    return MEMORY_E;
                }
                sig = (byte*)XMALLOC(sigSz, crl->heap, DYNAMIC_TYPE_CRL_ENTRY);
                if (sig == NULL) {
                    XFREE(tbs, crl->heap, DYNAMIC_TYPE_CRL_ENTRY);
                    wc_UnLockMutex(&crl->crlLock);
                    return MEMORY_E;
                }

                XMEMCPY(tbs, crle->toBeSigned, tbsSz);
                XMEMCPY(sig, crle->signature, sigSz);
            #ifndef NO_SKID
                XMEMCPY(extAuthKeyId, crle->extAuthKeyId,
                                                          sizeof(extAuthKeyId));
            #endif
                XMEMCPY(issuerHash, crle->issuerHash, sizeof(issuerHash));

                wc_UnLockMutex(&crl->crlLock);

            #ifndef NO_SKID
                if (crle->extAuthKeyIdSet)
                    ca = GetCA(crl->cm, extAuthKeyId);
                if (ca == NULL)
                    ca = GetCAByName(crl->cm, issuerHash);
            #else /* NO_SKID */
                ca = GetCA(crl->cm, issuerHash);
            #endif /* NO_SKID */
                if (ca == NULL) {
                    XFREE(sig, crl->heap, DYNAMIC_TYPE_CRL_ENTRY);
                    XFREE(tbs, crl->heap, DYNAMIC_TYPE_CRL_ENTRY);
                    WOLFSSL_MSG("Did NOT find CRL issuer CA");
                    return ASN_CRL_NO_SIGNER_E;
                }

                ret = VerifyCRL_Signature(&sigCtx, tbs, tbsSz, sig, sigSz,
                                          sigOID, ca, crl->heap);

                XFREE(sig, crl->heap, DYNAMIC_TYPE_CRL_ENTRY);
                XFREE(tbs, crl->heap, DYNAMIC_TYPE_CRL_ENTRY);

                if (wc_LockMutex(&crl->crlLock) != 0) {
                    WOLFSSL_MSG("wc_LockMutex failed");
                    return BAD_MUTEX_E;
                }

                crle = crl->crlList;
                while (crle) {
                    if (XMEMCMP(crle->issuerHash, cert->issuerHash,
                        CRL_DIGEST_SIZE) == 0) {

                        if (ret == 0)
                            crle->verified = 1;
                        else
                            crle->verified = ret;

                        XFREE(crle->toBeSigned, crl->heap,
                                                        DYNAMIC_TYPE_CRL_ENTRY);
                        crle->toBeSigned = NULL;
                        XFREE(crle->signature, crl->heap,
                                                        DYNAMIC_TYPE_CRL_ENTRY);
                        crle->signature = NULL;
                        break;
                    }
                    crle = crle->next;
                }
                if (crle == NULL || crle->verified < 0)
                    break;
            }
            else if (crle->verified < 0) {
                WOLFSSL_MSG("Cannot use CRL as it didn't verify");
                ret = crle->verified;
                break;
            }

            WOLFSSL_MSG("Checking next date validity");

        #ifdef WOLFSSL_NO_CRL_NEXT_DATE
            if (crle->nextDateFormat != ASN_OTHER_TYPE)
        #endif
            {
            #ifndef NO_ASN_TIME
                if (!XVALIDATE_DATE(crle->nextDate,crle->nextDateFormat, AFTER)) {
                    WOLFSSL_MSG("CRL next date is no longer valid");
                    ret = ASN_AFTER_DATE_E;
                }
            #endif
            }
            if (ret == 0) {
                foundEntry = 1;
            }
            break;
        }
        crle = crle->next;
    }

    if (foundEntry) {
        ret = FindRevokedSerial(cert, crle->certs, crle->totalCerts);
    }

    wc_UnLockMutex(&crl->crlLock);

    *pFoundEntry = foundEntry;

    return ret;
}

/* Is the cert ok with CRL, return 0 on success */
int CheckCertCRL(WOLFSSL_CRL* crl, DecodedCert* cert)
{
    int        foundEntry = 0;
    int        ret = 0;

    WOLFSSL_ENTER("CheckCertCRL");

#ifdef WOLFSSL_CRL_ALLOW_MISSING_CDP
    /* Skip CRL verification in case no CDP in peer cert */
    if (!cert->extCrlInfo) {
        return ret;
    }
#endif

    ret = CheckCertCRLList(crl, cert, &foundEntry);

#ifdef HAVE_CRL_IO
    if (foundEntry == 0) {
        /* perform embedded lookup */
        if (crl->crlIOCb) {
            ret = crl->crlIOCb(crl, (const char*)cert->extCrlInfo,
                                                        cert->extCrlInfoSz);
            if (ret == WOLFSSL_CBIO_ERR_WANT_READ) {
                ret = OCSP_WANT_READ;
            }
            else if (ret >= 0) {
                /* try again */
                ret = CheckCertCRLList(crl, cert, &foundEntry);
            }
        }
    }
#endif

#if defined(OPENSSL_ALL) && defined(WOLFSSL_CERT_GEN) && \
    (defined(WOLFSSL_CERT_REQ) || defined(WOLFSSL_CERT_EXT)) && \
    !defined(NO_FILESYSTEM) && !defined(NO_WOLFSSL_DIR)
    /* if not find entry in the CRL list, it looks at the folder that sets  */
    /* by LOOKUP_ctrl because user would want to use hash_dir.              */
    /* Loading <issuer-hash>.rN form CRL file if find at the folder,        */
    /* and try again checking Cert in the CRL list.                         */
    /* When not set the folder or not use hash_dir, do nothing.             */
    if ((foundEntry == 0) && (ret != OCSP_WANT_READ)) {
        if (crl->cm->x509_store_p != NULL) {
            ret = LoadCertByIssuer(crl->cm->x509_store_p,
                          (WOLFSSL_X509_NAME*)cert->issuerName, X509_LU_CRL);
            if (ret == WOLFSSL_SUCCESS) {
                /* try again */
                ret = CheckCertCRLList(crl, cert, &foundEntry);
            }
        }
    }
#endif
    if (foundEntry == 0) {
        WOLFSSL_MSG("Couldn't find CRL for status check");
        if (ret != CRL_CERT_DATE_ERR) {
            ret = CRL_MISSING;
        }

        if (crl->cm->cbMissingCRL) {
            char url[256];

            WOLFSSL_MSG("Issuing missing CRL callback");
            url[0] = '\0';
            if (cert->extCrlInfo) {
                if (cert->extCrlInfoSz < (int)sizeof(url) -1 ) {
                    XMEMCPY(url, cert->extCrlInfo, cert->extCrlInfoSz);
                    url[cert->extCrlInfoSz] = '\0';
                }
                else  {
                    WOLFSSL_MSG("CRL url too long");
                }
            }

            crl->cm->cbMissingCRL(url);
        }
    }

    return ret;
}


/* Add Decoded CRL, 0 on success */
static int AddCRL(WOLFSSL_CRL* crl, DecodedCRL* dcrl, const byte* buff,
                  int verified)
{
    CRL_Entry* crle = NULL;

    WOLFSSL_ENTER("AddCRL");

    if (crl == NULL)
        return -1;

    crle = crl->currentEntry;

    if (crle == NULL) {
        crle = (CRL_Entry*)XMALLOC(sizeof(CRL_Entry), crl->heap,
                                   DYNAMIC_TYPE_CRL_ENTRY);
        if (crle == NULL) {
            WOLFSSL_MSG("alloc CRL Entry failed");
            return MEMORY_E;
        }
    }

    if (InitCRL_Entry(crle, dcrl, buff, verified, crl->heap) < 0) {
        WOLFSSL_MSG("Init CRL Entry failed");
        FreeCRL_Entry(crle, crl->heap);
        if (crle != crl->currentEntry) {
            XFREE(crle, crl->heap, DYNAMIC_TYPE_CRL_ENTRY);
        }
        return -1;
    }

    if (wc_LockMutex(&crl->crlLock) != 0) {
        WOLFSSL_MSG("wc_LockMutex failed");
        FreeCRL_Entry(crle, crl->heap);
        if (crle != crl->currentEntry) {
            XFREE(crle, crl->heap, DYNAMIC_TYPE_CRL_ENTRY);
        }
        return BAD_MUTEX_E;
    }

    crle->next = crl->crlList;
    crl->crlList = crle;
    wc_UnLockMutex(&crl->crlLock);
    /* Avoid heap-use-after-free after crl->crlList is released */
    crl->currentEntry = NULL;

    return 0;
}


/* Load CRL File of type, WOLFSSL_SUCCESS on ok */
int BufferLoadCRL(WOLFSSL_CRL* crl, const byte* buff, long sz, int type,
                  int verify)
{
    int          ret = WOLFSSL_SUCCESS;
    const byte*  myBuffer = buff;    /* if DER ok, otherwise switch */
    DerBuffer*   der = NULL;
#ifdef WOLFSSL_SMALL_STACK
    DecodedCRL*  dcrl;
#else
    DecodedCRL   dcrl[1];
#endif

    WOLFSSL_ENTER("BufferLoadCRL");

    if (crl == NULL || buff == NULL || sz == 0)
        return BAD_FUNC_ARG;

    if (type == WOLFSSL_FILETYPE_PEM) {
    #ifdef WOLFSSL_PEM_TO_DER
        ret = PemToDer(buff, sz, CRL_TYPE, &der, NULL, NULL, NULL);
        if (ret == 0) {
            myBuffer = der->buffer;
            sz = der->length;
        }
        else {
            WOLFSSL_MSG("Pem to Der failed");
            FreeDer(&der);
            return -1;
        }
    #else
        ret = NOT_COMPILED_IN;
    #endif
    }

#ifdef WOLFSSL_SMALL_STACK
    dcrl = (DecodedCRL*)XMALLOC(sizeof(DecodedCRL), NULL, DYNAMIC_TYPE_TMP_BUFFER);
    if (dcrl == NULL) {
        FreeDer(&der);
        return MEMORY_E;
    }
#endif

    crl->currentEntry = (CRL_Entry*)XMALLOC(sizeof(CRL_Entry), crl->heap,
                                        DYNAMIC_TYPE_CRL_ENTRY);
    if (crl->currentEntry == NULL) {
        WOLFSSL_MSG("alloc CRL Entry failed");
    #ifdef WOLFSSL_SMALL_STACK
        XFREE(dcrl, NULL, DYNAMIC_TYPE_TMP_BUFFER);
    #endif
        FreeDer(&der);
        return MEMORY_E;
    }
    XMEMSET(crl->currentEntry, 0, sizeof(CRL_Entry));

    InitDecodedCRL(dcrl, crl->heap);
    ret = ParseCRL(crl->currentEntry->certs, dcrl, myBuffer, (word32)sz,
                   verify, crl->cm);
    if (ret != 0 && !(ret == ASN_CRL_NO_SIGNER_E && verify == NO_VERIFY)) {
        WOLFSSL_MSG("ParseCRL error");
        XFREE(crl->currentEntry, crl->heap, DYNAMIC_TYPE_CRL_ENTRY);
        crl->currentEntry = NULL;
    }
    else {
        ret = AddCRL(crl, dcrl, myBuffer, ret != ASN_CRL_NO_SIGNER_E);
        if (ret != 0) {
            WOLFSSL_MSG("AddCRL error");
        }
    }

    FreeDecodedCRL(dcrl);

#ifdef WOLFSSL_SMALL_STACK
    XFREE(dcrl, NULL, DYNAMIC_TYPE_TMP_BUFFER);
#endif

    FreeDer(&der);

    return ret ? ret : WOLFSSL_SUCCESS; /* convert 0 to WOLFSSL_SUCCESS */
}

#if defined(OPENSSL_EXTRA) && defined(HAVE_CRL)
/* helper function to create a new dynamic WOLFSSL_X509_CRL structure */
static WOLFSSL_X509_CRL* wolfSSL_X509_crl_new(WOLFSSL_CERT_MANAGER* cm)
{
    WOLFSSL_X509_CRL* ret;

    ret = (WOLFSSL_X509_CRL*)XMALLOC(sizeof(WOLFSSL_X509_CRL), cm->heap,
                DYNAMIC_TYPE_CRL);
    if (ret != NULL) {
        if (InitCRL(ret, cm) < 0) {
            WOLFSSL_MSG("Unable to initialize new CRL structure");
            XFREE(ret, cm->heap, DYNAMIC_TYPE_CRL);
            ret = NULL;
        }
    }
    return ret;
}

#ifndef CRL_STATIC_REVOKED_LIST
/* returns head of copied list that was alloc'd */
static RevokedCert *DupRevokedCertList(RevokedCert* in, void* heap)
{
    RevokedCert* head = NULL;
    RevokedCert* current = in;
    RevokedCert* prev = NULL;
    while (current) {
        RevokedCert* tmp = (RevokedCert*)XMALLOC(sizeof(RevokedCert), heap,
                DYNAMIC_TYPE_REVOKED);
        if (tmp != NULL) {
            XMEMCPY(tmp->serialNumber, current->serialNumber,
                    EXTERNAL_SERIAL_SIZE);
            tmp->serialSz = current->serialSz;
            XMEMCPY(tmp->revDate, current->revDate,
                    MAX_DATE_SIZE);
            tmp->revDateFormat = current->revDateFormat;
            tmp->next = NULL;
            if (prev != NULL)
                prev->next = tmp;
            if (head == NULL)
                head = tmp;
            prev = tmp;
        }
        else {
            WOLFSSL_MSG("Failed to allocate new RevokedCert structure");
            /* free up any existing list */
            while (head != NULL) {
                current = head;
                head = head->next;
                XFREE(current, heap, DYNAMIC_TYPE_REVOKED);
            }
            return NULL;
        }
        current = current->next;
    }

    (void)heap;
    return head;
}

#endif /* CRL_STATIC_REVOKED_LIST */
/* returns a deep copy of ent on success and null on fail */
static CRL_Entry* DupCRL_Entry(const CRL_Entry* ent, void* heap)
{
    CRL_Entry *dupl;
#ifdef CRL_STATIC_REVOKED_LIST
    if (ent->totalCerts > CRL_MAX_REVOKED_CERTS) {
        return NULL;
    }
#endif
    dupl = (CRL_Entry*)XMALLOC(sizeof(CRL_Entry), heap, DYNAMIC_TYPE_CRL_ENTRY);
    if (dupl == NULL) {
        WOLFSSL_MSG("alloc CRL Entry failed");
        return NULL;
    }
    XMEMSET(dupl, 0, sizeof(CRL_Entry));

    XMEMCPY(dupl->issuerHash, ent->issuerHash, CRL_DIGEST_SIZE);
    XMEMCPY(dupl->lastDate, ent->lastDate, MAX_DATE_SIZE);
    XMEMCPY(dupl->nextDate, ent->nextDate, MAX_DATE_SIZE);
    dupl->lastDateFormat = ent->lastDateFormat;
    dupl->nextDateFormat = ent->nextDateFormat;

#if defined(OPENSSL_EXTRA)
    dupl->lastDateAsn1.length = MAX_DATE_SIZE;
    XMEMCPY (dupl->lastDateAsn1.data, dupl->lastDate,
             dupl->lastDateAsn1.length);
    dupl->lastDateAsn1.type = dupl->lastDateFormat;
    dupl->nextDateAsn1.length = MAX_DATE_SIZE;
    XMEMCPY (dupl->nextDateAsn1.data, dupl->nextDate,
             dupl->nextDateAsn1.length);
    dupl->nextDateAsn1.type = dupl->nextDateFormat;
#endif

#ifdef CRL_STATIC_REVOKED_LIST
    XMEMCPY(dupl->certs, ent->certs, ent->totalCerts*sizeof(RevokedCert));
#else
    dupl->certs = DupRevokedCertList(ent->certs, heap);
#endif
    dupl->totalCerts = ent->totalCerts;
    dupl->verified = ent->verified;

    if (!ent->verified) {
        dupl->tbsSz = ent->tbsSz;
        dupl->signatureSz = ent->signatureSz;
        dupl->signatureOID = ent->signatureOID;
        dupl->toBeSigned = (byte*)XMALLOC(dupl->tbsSz, heap,
                                          DYNAMIC_TYPE_CRL_ENTRY);
        if (dupl->toBeSigned == NULL) {
            FreeCRL_Entry(dupl, heap);
            XFREE(dupl, heap, DYNAMIC_TYPE_CRL_ENTRY);
            return NULL;
        }

        dupl->signature = (byte*)XMALLOC(dupl->signatureSz, heap,
                                         DYNAMIC_TYPE_CRL_ENTRY);
        if (dupl->signature == NULL) {
            FreeCRL_Entry(dupl, heap);
            XFREE(dupl, heap, DYNAMIC_TYPE_CRL_ENTRY);
            return NULL;
        }
        XMEMCPY(dupl->toBeSigned, ent->toBeSigned, dupl->tbsSz);
        XMEMCPY(dupl->signature, ent->signature, dupl->signatureSz);
    #ifndef NO_SKID
        dupl->extAuthKeyIdSet = ent->extAuthKeyIdSet;
        if (dupl->extAuthKeyIdSet)
            XMEMCPY(dupl->extAuthKeyId, ent->extAuthKeyId, KEYID_SIZE);
    #endif
    }
    else {
        dupl->toBeSigned = NULL;
        dupl->tbsSz = 0;
        dupl->signature = NULL;
        dupl->signatureSz = 0;
    }

    return dupl;
}


/* returns the head of a deep copy of the list on success and null on fail */
static CRL_Entry* DupCRL_list(CRL_Entry* crl, void* heap)
{
    CRL_Entry* current;
    CRL_Entry* head = NULL;
    CRL_Entry* prev = NULL;

    current = crl;
    while (current != NULL) {
        CRL_Entry* tmp = DupCRL_Entry(current, heap);
        if (tmp != NULL) {
            tmp->next = NULL;
            if (head == NULL)
                head = tmp;
            if (prev != NULL)
                prev->next = tmp;
            prev = tmp;
        }
        else {
            WOLFSSL_MSG("Failed to allocate new CRL_Entry structure");
            /* free up any existing list */
            while (head != NULL) {
                current = head;
                head = head->next;
                FreeCRL_Entry(current, heap);
                XFREE(current, heap, DYNAMIC_TYPE_CRL_ENTRY);
            }

            return NULL;
        }
        current = current->next;
    }
    return head;
}


/* Duplicates everything except the parent cm pointed to.
 * Expects that Init has already been done to 'dupl'
 * return 0 on success */
static int DupX509_CRL(WOLFSSL_X509_CRL *dupl, const WOLFSSL_X509_CRL* crl)
{
    if (dupl == NULL || crl == NULL) {
        return BAD_FUNC_ARG;
    }

    if (crl->monitors[0].path) {
        int pathSz = (int)XSTRLEN(crl->monitors[0].path) + 1;
        dupl->monitors[0].path = (char*)XMALLOC(pathSz, dupl->heap,
                DYNAMIC_TYPE_CRL_MONITOR);
        if (dupl->monitors[0].path != NULL) {
            XSTRNCPY(dupl->monitors[0].path, crl->monitors[0].path, pathSz);
        }
        else {
            return MEMORY_E;
        }
    }

    if (crl->monitors[1].path) {
        int pathSz = (int)XSTRLEN(crl->monitors[1].path) + 1;
        dupl->monitors[1].path = (char*)XMALLOC(pathSz, dupl->heap,
                DYNAMIC_TYPE_CRL_MONITOR);
        if (dupl->monitors[1].path != NULL) {
            XSTRNCPY(dupl->monitors[1].path, crl->monitors[1].path, pathSz);
        }
        else {
            if (dupl->monitors[0].path != NULL) {
                XFREE(dupl->monitors[0].path, dupl->heap,
                        DYNAMIC_TYPE_CRL_MONITOR);
            }
            return MEMORY_E;
        }
    }

    dupl->crlList = DupCRL_list(crl->crlList, dupl->heap);
#ifdef HAVE_CRL_IO
    dupl->crlIOCb = crl->crlIOCb;
#endif

    return 0;
}

/* returns WOLFSSL_SUCCESS on success. Does not take ownership of newcrl */
int wolfSSL_X509_STORE_add_crl(WOLFSSL_X509_STORE *store, WOLFSSL_X509_CRL *newcrl)
{
    CRL_Entry   *crle;
    WOLFSSL_X509_CRL *crl;

    WOLFSSL_ENTER("wolfSSL_X509_STORE_add_crl");
    if (store == NULL || newcrl == NULL || store->cm == NULL)
        return BAD_FUNC_ARG;

    if (store->cm->crl == NULL) {
        crl = wolfSSL_X509_crl_new(store->cm);
        if (crl == NULL) {
            return WOLFSSL_FAILURE;
        }
        if (DupX509_CRL(crl, newcrl) != 0) {
            if (crl != NULL)
                FreeCRL(crl, 1);
            return WOLFSSL_FAILURE;
        }
        store->crl = store->cm->crl = crl;
        if (wolfSSL_CertManagerEnableCRL(store->cm, WOLFSSL_CRL_CHECKALL)
                != WOLFSSL_SUCCESS) {
            WOLFSSL_MSG("wolfSSL_CertManagerEnableCRL error");
            return WOLFSSL_FAILURE;
        }
        return WOLFSSL_SUCCESS;
    }

    /* find tail of current list and add new list */
    crl  = store->cm->crl;
    crle = crl->crlList;
    if (newcrl->crlList != NULL) {
        CRL_Entry *tail = crle;
        CRL_Entry *toAdd;

        if (wc_LockMutex(&crl->crlLock) != 0)
        {
            WOLFSSL_MSG("wc_LockMutex failed");
            return BAD_MUTEX_E;
        }

        toAdd = DupCRL_list(newcrl->crlList, crl->heap);
        if (tail == NULL) {
            crl->crlList = toAdd;
        }
        else {
            while (tail->next != NULL) tail = tail->next;
            tail->next = toAdd;
        }
        wc_UnLockMutex(&crl->crlLock);
    }

    if (wolfSSL_CertManagerEnableCRL(store->cm, WOLFSSL_CRL_CHECKALL)
            != WOLFSSL_SUCCESS) {
        WOLFSSL_MSG("wolfSSL_CertManagerEnableCRL error");
        return WOLFSSL_FAILURE;
    }

    WOLFSSL_LEAVE("wolfSSL_X509_STORE_add_crl", WOLFSSL_SUCCESS);

    return WOLFSSL_SUCCESS;
}
#endif

#ifdef HAVE_CRL_MONITOR


/* Signal Monitor thread is setup, save status to setup flag, 0 on success */
static int SignalSetup(WOLFSSL_CRL* crl, int status)
{
    int ret;

    /* signal to calling thread we're setup */
    if (wc_LockMutex(&crl->crlLock) != 0) {
        WOLFSSL_MSG("wc_LockMutex crlLock failed");
        return BAD_MUTEX_E;
    }

        crl->setup = status;
        ret = pthread_cond_signal(&crl->cond);

    wc_UnLockMutex(&crl->crlLock);

    if (ret != 0)
        return BAD_COND_E;

    return 0;
}


/* read in new CRL entries and save new list */
static int SwapLists(WOLFSSL_CRL* crl)
{
    int        ret;
    CRL_Entry* newList;
#ifdef WOLFSSL_SMALL_STACK
    WOLFSSL_CRL* tmp;
#else
    WOLFSSL_CRL tmp[1];
#endif

#ifdef WOLFSSL_SMALL_STACK
    tmp = (WOLFSSL_CRL*)XMALLOC(sizeof(WOLFSSL_CRL), NULL, DYNAMIC_TYPE_TMP_BUFFER);
    if (tmp == NULL)
        return MEMORY_E;
#endif

    if (InitCRL(tmp, crl->cm) < 0) {
        WOLFSSL_MSG("Init tmp CRL failed");
#ifdef WOLFSSL_SMALL_STACK
        XFREE(tmp, NULL, DYNAMIC_TYPE_TMP_BUFFER);
#endif
        return -1;
    }

    if (crl->monitors[0].path) {
        ret = LoadCRL(tmp, crl->monitors[0].path, WOLFSSL_FILETYPE_PEM, 0);
        if (ret != WOLFSSL_SUCCESS) {
            WOLFSSL_MSG("PEM LoadCRL on dir change failed");
            FreeCRL(tmp, 0);
#ifdef WOLFSSL_SMALL_STACK
            XFREE(tmp, NULL, DYNAMIC_TYPE_TMP_BUFFER);
#endif
            return -1;
        }
    }

    if (crl->monitors[1].path) {
        ret = LoadCRL(tmp, crl->monitors[1].path, WOLFSSL_FILETYPE_ASN1, 0);
        if (ret != WOLFSSL_SUCCESS) {
            WOLFSSL_MSG("DER LoadCRL on dir change failed");
            FreeCRL(tmp, 0);
#ifdef WOLFSSL_SMALL_STACK
            XFREE(tmp, NULL, DYNAMIC_TYPE_TMP_BUFFER);
#endif
            return -1;
        }
    }

    if (wc_LockMutex(&crl->crlLock) != 0) {
        WOLFSSL_MSG("wc_LockMutex failed");
        FreeCRL(tmp, 0);
#ifdef WOLFSSL_SMALL_STACK
        XFREE(tmp, NULL, DYNAMIC_TYPE_TMP_BUFFER);
#endif
        return -1;
    }

    newList = tmp->crlList;

    /* swap lists */
    tmp->crlList  = crl->crlList;
    crl->crlList = newList;

    wc_UnLockMutex(&crl->crlLock);

    FreeCRL(tmp, 0);

#ifdef WOLFSSL_SMALL_STACK
    XFREE(tmp, NULL, DYNAMIC_TYPE_TMP_BUFFER);
#endif

    return 0;
}


#if (defined(__MACH__) || defined(__FreeBSD__))

#include <sys/types.h>
#include <sys/event.h>
#include <sys/time.h>
#include <fcntl.h>
#include <unistd.h>

#ifdef __MACH__
    #define XEVENT_MODE O_EVTONLY
#elif defined(__FreeBSD__)
    #define XEVENT_MODE EVFILT_VNODE
#endif


/* we need a unique kqueue user filter fd for crl in case user is doing custom
 * events too */
#ifndef CRL_CUSTOM_FD
    #define CRL_CUSTOM_FD 123456
#endif


/* shutdown monitor thread, 0 on success */
static int StopMonitor(int mfd)
{
    struct kevent change;

    /* trigger custom shutdown */
    EV_SET(&change, CRL_CUSTOM_FD, EVFILT_USER, 0, NOTE_TRIGGER, 0, NULL);
    if (kevent(mfd, &change, 1, NULL, 0, NULL) < 0) {
        WOLFSSL_MSG("kevent trigger customer event failed");
        return -1;
    }

    return 0;
}


/* OS X  monitoring */
static void* DoMonitor(void* arg)
{
    int fPEM, fDER;
    struct kevent change;

    WOLFSSL_CRL* crl = (WOLFSSL_CRL*)arg;

    WOLFSSL_ENTER("DoMonitor");

    crl->mfd = kqueue();
    if (crl->mfd == -1) {
        WOLFSSL_MSG("kqueue failed");
        SignalSetup(crl, MONITOR_SETUP_E);
        return NULL;
    }

    /* listen for custom shutdown event */
    EV_SET(&change, CRL_CUSTOM_FD, EVFILT_USER, EV_ADD, 0, 0, NULL);
    if (kevent(crl->mfd, &change, 1, NULL, 0, NULL) < 0) {
        WOLFSSL_MSG("kevent monitor customer event failed");
        SignalSetup(crl, MONITOR_SETUP_E);
        (void)close(crl->mfd);
        return NULL;
    }

    fPEM = -1;
    fDER = -1;

    if (crl->monitors[0].path) {
        fPEM = open(crl->monitors[0].path, XEVENT_MODE);
        if (fPEM == -1) {
            WOLFSSL_MSG("PEM event dir open failed");
            SignalSetup(crl, MONITOR_SETUP_E);
            (void)close(crl->mfd);
            return NULL;
        }
    }

    if (crl->monitors[1].path) {
        fDER = open(crl->monitors[1].path, XEVENT_MODE);
        if (fDER == -1) {
            WOLFSSL_MSG("DER event dir open failed");
            if (fPEM != -1)
                (void)close(fPEM);
            (void)close(crl->mfd);
            SignalSetup(crl, MONITOR_SETUP_E);
            return NULL;
        }
    }

    if (fPEM != -1)
        EV_SET(&change, fPEM, EVFILT_VNODE, EV_ADD | EV_ENABLE | EV_ONESHOT,
                NOTE_DELETE | NOTE_EXTEND | NOTE_WRITE | NOTE_ATTRIB, 0, 0);

    if (fDER != -1)
        EV_SET(&change, fDER, EVFILT_VNODE, EV_ADD | EV_ENABLE | EV_ONESHOT,
                NOTE_DELETE | NOTE_EXTEND | NOTE_WRITE | NOTE_ATTRIB, 0, 0);

    /* signal to calling thread we're setup */
    if (SignalSetup(crl, 1) != 0) {
        if (fPEM != -1)
            (void)close(fPEM);
        if (fDER != -1)
            (void)close(fDER);
        (void)close(crl->mfd);
        return NULL;
    }

    for (;;) {
        struct kevent event;
        int           numEvents = kevent(crl->mfd, &change, 1, &event, 1, NULL);

        WOLFSSL_MSG("Got kevent");

        if (numEvents == -1) {
            WOLFSSL_MSG("kevent problem, continue");
            continue;
        }

        if (event.filter == EVFILT_USER) {
            WOLFSSL_MSG("Got user shutdown event, breaking out");
            break;
        }

        if (SwapLists(crl) < 0) {
            WOLFSSL_MSG("SwapLists problem, continue");
        }
    }

    if (fPEM != -1)
        (void)close(fPEM);
    if (fDER != -1)
        (void)close(fDER);

    (void)close(crl->mfd);

    return NULL;
}


#elif defined(__linux__)

#include <sys/types.h>
#include <sys/inotify.h>
#include <sys/eventfd.h>
#include <unistd.h>


#ifndef max
    static WC_INLINE int max(int a, int b)
    {
        return a > b ? a : b;
    }
#endif /* max */


/* shutdown monitor thread, 0 on success */
static int StopMonitor(int mfd)
{
    word64 w64 = 1;

    /* write to our custom event */
    if (write(mfd, &w64, sizeof(w64)) < 0) {
        WOLFSSL_MSG("StopMonitor write failed");
        return -1;
    }

    return 0;
}


/* linux monitoring */
static void* DoMonitor(void* arg)
{
    int         notifyFd;
    int         wd  = -1;
    WOLFSSL_CRL* crl = (WOLFSSL_CRL*)arg;
#ifdef WOLFSSL_SMALL_STACK
    char*       buff;
#else
    char        buff[8192];
#endif

    WOLFSSL_ENTER("DoMonitor");

    crl->mfd = eventfd(0, 0);  /* our custom shutdown event */
    if (crl->mfd < 0) {
        WOLFSSL_MSG("eventfd failed");
        SignalSetup(crl, MONITOR_SETUP_E);
        return NULL;
    }

    notifyFd = inotify_init();
    if (notifyFd < 0) {
        WOLFSSL_MSG("inotify failed");
        (void)close(crl->mfd);
        SignalSetup(crl, MONITOR_SETUP_E);
        return NULL;
    }

    if (crl->monitors[0].path) {
        wd = inotify_add_watch(notifyFd, crl->monitors[0].path, IN_CLOSE_WRITE |
                                                                IN_DELETE);
        if (wd < 0) {
            WOLFSSL_MSG("PEM notify add watch failed");
            (void)close(crl->mfd);
            (void)close(notifyFd);
            SignalSetup(crl, MONITOR_SETUP_E);
            return NULL;
        }
    }

    if (crl->monitors[1].path) {
        wd = inotify_add_watch(notifyFd, crl->monitors[1].path, IN_CLOSE_WRITE |
                                                                IN_DELETE);
        if (wd < 0) {
            WOLFSSL_MSG("DER notify add watch failed");
            (void)close(crl->mfd);
            (void)close(notifyFd);
            SignalSetup(crl, MONITOR_SETUP_E);
            return NULL;
        }
    }

#ifdef WOLFSSL_SMALL_STACK
    buff = (char*)XMALLOC(8192, NULL, DYNAMIC_TYPE_TMP_BUFFER);
    if (buff == NULL)
        return NULL;
#endif

    /* signal to calling thread we're setup */
    if (SignalSetup(crl, 1) != 0) {
        #ifdef WOLFSSL_SMALL_STACK
            XFREE(buff, NULL, DYNAMIC_TYPE_TMP_BUFFER);
        #endif

        if (wd > 0) {
            if (inotify_rm_watch(notifyFd, wd) < 0)
                WOLFSSL_MSG("inotify_rm_watch #1 failed in DoMonitor");
        }
        (void)close(crl->mfd);
        (void)close(notifyFd);
        return NULL;
    }

    for (;;) {
        fd_set readfds;
        int    result;
        int    length;

        FD_ZERO(&readfds);
        FD_SET(notifyFd, &readfds);
        FD_SET(crl->mfd, &readfds);

        result = select(max(notifyFd, crl->mfd) + 1, &readfds, NULL, NULL,NULL);

        WOLFSSL_MSG("Got notify event");

        if (result < 0) {
            WOLFSSL_MSG("select problem, continue");
            continue;
        }

        if (FD_ISSET(crl->mfd, &readfds)) {
            word64 r64;
            int    rlen;

            WOLFSSL_MSG("got custom shutdown event, breaking out");

            /* read out the bytes written to the event to clean up */
            rlen = (int) read(crl->mfd, &r64, sizeof(r64));
            if (rlen < 0) {
                WOLFSSL_MSG("read custom event failure");
            }

            break;
        }

        length = (int) read(notifyFd, buff, 8192);
        if (length < 0) {
            WOLFSSL_MSG("notify read problem, continue");
            continue;
        }

        if (SwapLists(crl) < 0) {
            WOLFSSL_MSG("SwapLists problem, continue");
        }
    }

#ifdef WOLFSSL_SMALL_STACK
    XFREE(buff, NULL, DYNAMIC_TYPE_TMP_BUFFER);
#endif

    if (wd > 0) {
        if (inotify_rm_watch(notifyFd, wd) < 0)
            WOLFSSL_MSG("inotify_rm_watch #2 failed in DoMonitor");
    }
    (void)close(crl->mfd);
    (void)close(notifyFd);

    return NULL;
}

#endif /* MACH or linux */


/* Start Monitoring the CRL path(s) in a thread */
static int StartMonitorCRL(WOLFSSL_CRL* crl)
{
    int ret = WOLFSSL_SUCCESS;

    WOLFSSL_ENTER("StartMonitorCRL");

    if (crl == NULL)
        return BAD_FUNC_ARG;

    if (crl->tid != 0) {
        WOLFSSL_MSG("Monitor thread already running");
        return ret;  /* that's ok, someone already started */
    }

    if (pthread_create(&crl->tid, NULL, DoMonitor, crl) != 0) {
        WOLFSSL_MSG("Thread creation error");
        return THREAD_CREATE_E;
    }

    /* wait for setup to complete */
    if (wc_LockMutex(&crl->crlLock) != 0) {
        WOLFSSL_MSG("wc_LockMutex crlLock error");
        return BAD_MUTEX_E;
    }

        while (crl->setup == 0) {
            if (pthread_cond_wait(&crl->cond, &crl->crlLock) != 0) {
                ret = BAD_COND_E;
                break;
            }
        }
        if (crl->setup < 0)
            ret = crl->setup;  /* store setup error */

    wc_UnLockMutex(&crl->crlLock);

    if (ret < 0) {
        WOLFSSL_MSG("DoMonitor setup failure");
        crl->tid = 0;  /* thread already done */
    }

    return ret;
}


#else /* HAVE_CRL_MONITOR */

#if !defined(NO_FILESYSTEM) && !defined(NO_WOLFSSL_DIR)

static int StartMonitorCRL(WOLFSSL_CRL* crl)
{
    (void)crl;

    WOLFSSL_ENTER("StartMonitorCRL");
    WOLFSSL_MSG("Not compiled in");

    return NOT_COMPILED_IN;
}

#endif /* !NO_FILESYSTEM && !NO_WOLFSSL_DIR */

#endif  /* HAVE_CRL_MONITOR */

#if !defined(NO_FILESYSTEM) && !defined(NO_WOLFSSL_DIR)

/* Load CRL path files of type, WOLFSSL_SUCCESS on ok */
int LoadCRL(WOLFSSL_CRL* crl, const char* path, int type, int monitor)
{
    int         ret = WOLFSSL_SUCCESS;
    char*       name = NULL;
#ifdef WOLFSSL_SMALL_STACK
    ReadDirCtx* readCtx = NULL;
#else
    ReadDirCtx  readCtx[1];
#endif

    WOLFSSL_ENTER("LoadCRL");
    if (crl == NULL)
        return BAD_FUNC_ARG;

#ifdef WOLFSSL_SMALL_STACK
    readCtx = (ReadDirCtx*)XMALLOC(sizeof(ReadDirCtx), crl->heap,
                                                       DYNAMIC_TYPE_TMP_BUFFER);
    if (readCtx == NULL)
        return MEMORY_E;
#endif

    /* try to load each regular file in path */
    ret = wc_ReadDirFirst(readCtx, path, &name);
    while (ret == 0 && name) {
        int skip = 0;
        if (type == WOLFSSL_FILETYPE_PEM) {
            if (XSTRSTR(name, ".pem") == NULL) {
                WOLFSSL_MSG("not .pem file, skipping");
                skip = 1;
            }
        }
        else {
            if (XSTRSTR(name, ".der") == NULL &&
                XSTRSTR(name, ".crl") == NULL)
            {
                WOLFSSL_MSG("not .der or .crl file, skipping");
                skip = 1;
            }
        }

        if (!skip && ProcessFile(NULL, name, type, CRL_TYPE, NULL, 0, crl,
                                 VERIFY) != WOLFSSL_SUCCESS) {
            WOLFSSL_MSG("CRL file load failed, continuing");
        }

        ret = wc_ReadDirNext(readCtx, path, &name);
    }
    wc_ReadDirClose(readCtx);
    ret = WOLFSSL_SUCCESS; /* load failures not reported, for backwards compat */

#ifdef WOLFSSL_SMALL_STACK
    XFREE(readCtx, crl->heap, DYNAMIC_TYPE_TMP_BUFFER);
#endif

    if (monitor & WOLFSSL_CRL_MONITOR) {
        word32 pathLen;
        char* pathBuf;

        WOLFSSL_MSG("monitor path requested");

        pathLen = (word32)XSTRLEN(path);
        pathBuf = (char*)XMALLOC(pathLen+1, crl->heap,DYNAMIC_TYPE_CRL_MONITOR);
        if (pathBuf) {
            XMEMCPY(pathBuf, path, pathLen+1);

            if (type == WOLFSSL_FILETYPE_PEM) {
                /* free old path before setting a new one */
                if (crl->monitors[0].path) {
                    XFREE(crl->monitors[0].path, crl->heap,
                            DYNAMIC_TYPE_CRL_MONITOR);
                }
                crl->monitors[0].path = pathBuf;
                crl->monitors[0].type = WOLFSSL_FILETYPE_PEM;
            } else {
                /* free old path before setting a new one */
                if (crl->monitors[1].path) {
                    XFREE(crl->monitors[1].path, crl->heap,
                            DYNAMIC_TYPE_CRL_MONITOR);
                }
                crl->monitors[1].path = pathBuf;
                crl->monitors[1].type = WOLFSSL_FILETYPE_ASN1;
            }

            if (monitor & WOLFSSL_CRL_START_MON) {
                WOLFSSL_MSG("start monitoring requested");

                ret = StartMonitorCRL(crl);
            }
        }
        else {
            ret = MEMORY_E;
        }
    }

    return ret;
}

#else
int LoadCRL(WOLFSSL_CRL* crl, const char* path, int type, int monitor)
{
    (void)crl;
    (void)path;
    (void)type;
    (void)monitor;

    /* stub for scenario where file system is not supported */
    return NOT_COMPILED_IN;
}
#endif /* !NO_FILESYSTEM && !NO_WOLFSSL_DIR */

#endif /* HAVE_CRL */
#endif /* !WOLFCRYPT_ONLY */