summaryrefslogtreecommitdiffstats
path: root/src/VBox/Runtime/common/crypto/store-cert-add-basic.cpp
blob: db776ec7d29aa3489b6c3c32f89ba9c0177f3d97 (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
/* $Id: store-cert-add-basic.cpp $ */
/** @file
 * IPRT - Cryptographic (Certificate) Store, RTCrStoreCertAddFromDir.
 */

/*
 * Copyright (C) 2006-2019 Oracle Corporation
 *
 * This file is part of VirtualBox Open Source Edition (OSE), as
 * available from http://www.virtualbox.org. This file is free software;
 * you can redistribute it and/or modify it under the terms of the GNU
 * General Public License (GPL) as published by the Free Software
 * Foundation, in version 2 as it comes in the "COPYING" file of the
 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
 *
 * The contents of this file may alternatively be used under the terms
 * of the Common Development and Distribution License Version 1.0
 * (CDDL) only, as it comes in the "COPYING.CDDL" file of the
 * VirtualBox OSE distribution, in which case the provisions of the
 * CDDL are applicable instead of those of the GPL.
 *
 * You may elect to license modified versions of this file under the
 * terms and conditions of either the GPL or the CDDL or both.
 */


/*********************************************************************************************************************************
*   Header Files                                                                                                                 *
*********************************************************************************************************************************/
#include "internal/iprt.h"
#include <iprt/crypto/store.h>

#include <iprt/assert.h>
#include <iprt/crypto/pem.h>
#include <iprt/dir.h>
#include <iprt/err.h>
#include <iprt/file.h>
#include <iprt/mem.h>
#include <iprt/path.h>
#include <iprt/sha.h>
#include <iprt/string.h>

#include "x509-internal.h"


/*********************************************************************************************************************************
*   Global Variables                                                                                                             *
*********************************************************************************************************************************/
/** BEGIN CERTIFICATE / END CERTIFICATE. */
static RTCRPEMMARKERWORD const g_aWords_Certificate[] =
{
    { RT_STR_TUPLE("CERTIFICATE") }
};

/** BEGIN TRUSTED CERTIFICATE / END TRUSTED CERTIFICATE. */
static RTCRPEMMARKERWORD const g_aWords_TrustedCertificate[] =
{
    { RT_STR_TUPLE("TRUSTED") },
    { RT_STR_TUPLE("CERTIFICATE") }
};

/** BEGIN X509 CERTIFICATE / END X509 CERTIFICATE. (old) */
static RTCRPEMMARKERWORD const g_aWords_X509Certificate[] =
{
    { RT_STR_TUPLE("X509") },
    { RT_STR_TUPLE("CERTIFICATE") }
};

/**
 * X509 Certificate markers.
 *
 * @remark See crypto/pem/pem.h in OpenSSL for a matching list.
 */
static RTCRPEMMARKER const g_aX509CertificateMarkers[3] =
{
    { g_aWords_Certificate,         RT_ELEMENTS(g_aWords_Certificate) },
    { g_aWords_TrustedCertificate,  RT_ELEMENTS(g_aWords_TrustedCertificate) },
    { g_aWords_X509Certificate,     RT_ELEMENTS(g_aWords_X509Certificate) }
};



#ifdef RT_STRICT
/**
 * Checks if we've found all the certificates already.
 *
 * @returns true if all found, false if not.
 * @param   afFound             Indicator array.
 * @param   cWanted             Number of wanted certificates.
 */
DECLINLINE(bool) rtCrStoreAllDone(bool const *afFound, size_t cWanted)
{
    while (cWanted-- > 0)
        if (!afFound[cWanted])
            return false;
    return true;
}
#endif /* RT_STRICT */


/**
 * Checks if the given certificate specs matches the given wanted poster.
 *
 * @returns true if match, false if not.
 * @param   pWanted     The certificate wanted poster.
 * @param   cbEncoded   The candidate certificate encoded size.
 * @param   paSha1      The candidate certificate SHA-1 fingerprint.
 * @param   paSha512    The candidate certificate SHA-512 fingerprint.
 * @param   pCert       The decoded candidate certificate, optional.  If not
 *                      given the result will be uncertain.
 */
DECLINLINE(bool) rtCrStoreIsCertEqualToWanted(PCRTCRCERTWANTED pWanted,
                                              size_t cbEncoded,
                                              uint8_t const pabSha1[RTSHA1_HASH_SIZE],
                                              uint8_t const pabSha512[RTSHA512_HASH_SIZE],
                                              PCRTCRX509CERTIFICATE pCert)
{
    if (   pWanted->cbEncoded != cbEncoded
        && pWanted->cbEncoded != 0)
        return false;

    if (   pWanted->fSha1Fingerprint
        && memcmp(pWanted->abSha1, pabSha1, RTSHA1_HASH_SIZE) != 0)
        return false;

    if (   pWanted->fSha512Fingerprint
        && memcmp(pWanted->abSha512, pabSha512, RTSHA512_HASH_SIZE) != 0)
        return false;

    if (   pWanted->pszSubject
        && pCert
        && !RTCrX509Name_MatchWithString(&pCert->TbsCertificate.Subject, pWanted->pszSubject))
        return false;

    return true;
}


/**
 * Checks if a certificate is wanted.
 *
 * @returns true if match, false if not.
 * @param   paWanted    The certificate wanted posters.
 * @param   cWanted     The number of wanted posters.
 * @param   apfFound    Found initicators running paralell to @a paWanted.
 * @param   cbEncoded   The candidate certificate encoded size.
 * @param   paSha1      The candidate certificate SHA-1 fingerprint.
 * @param   paSha512    The candidate certificate SHA-512 fingerprint.
 * @param   pCert       The decoded candidate certificate, optional.  If not
 *                      given the result will be uncertain.
 */
DECLINLINE(bool) rtCrStoreIsCertWanted(PCRTCRCERTWANTED paWanted, size_t cWanted, bool const *pafFound, size_t cbEncoded,
                                       uint8_t const pabSha1[RTSHA1_HASH_SIZE], uint8_t const pabSha512[RTSHA512_HASH_SIZE],
                                       PCRTCRX509CERTIFICATE pCert)
{
    for (size_t iCert = 0; iCert < cWanted; iCert++)
        if (!pafFound[iCert])
            if (rtCrStoreIsCertEqualToWanted(&paWanted[iCert], cbEncoded, pabSha1, pabSha512, pCert))
                return true;
    return false;
}


/**
 * Marks a certificate as found after it has been added to the store.
 *
 * May actually mark several certificates as found if there are duplicates or
 * ambiguities in the wanted list.
 *
 * @returns true if all have been found, false if more to search for.
 *
 * @param   apfFound    Found initicators running paralell to @a paWanted.
 *                      This is what this function updates.
 * @param   paWanted    The certificate wanted posters.
 * @param   cWanted     The number of wanted posters.
 * @param   cbEncoded   The candidate certificate encoded size.
 * @param   paSha1      The candidate certificate SHA-1 fingerprint.
 * @param   paSha512    The candidate certificate SHA-512 fingerprint.
 * @param   pCert       The decoded candidate certificate, optional.  If not
 *                      given the result will be uncertain.
 */
static bool rtCrStoreMarkCertFound(bool *pafFound, PCRTCRCERTWANTED paWanted, size_t cWanted, size_t cbEncoded,
                                   uint8_t const pabSha1[RTSHA1_HASH_SIZE], uint8_t const pabSha512[RTSHA512_HASH_SIZE],
                                   PCRTCRX509CERTIFICATE pCert)
{
    size_t cFound = 0;
    for (size_t iCert = 0; iCert < cWanted; iCert++)
        if (pafFound[iCert])
            cFound++;
        else if (rtCrStoreIsCertEqualToWanted(&paWanted[iCert], cbEncoded, pabSha1, pabSha512, pCert))
        {
            pafFound[iCert] = true;
            cFound++;
        }
    return cFound == cWanted;
}


RTDECL(int) RTCrStoreCertAddFromStore(RTCRSTORE hStore, uint32_t fFlags, RTCRSTORE hStoreSrc)
{
    /*
     * Validate input.
     */
    AssertReturn(!(fFlags & ~(RTCRCERTCTX_F_ADD_IF_NOT_FOUND | RTCRCERTCTX_F_ADD_CONTINUE_ON_ERROR)), VERR_INVALID_FLAGS);

    /*
     * Enumerate all the certificates in the source store, adding them to the destination.
     */
    RTCRSTORECERTSEARCH Search;
    int rc = RTCrStoreCertFindAll(hStoreSrc, &Search);
    if (RT_SUCCESS(rc))
    {
        PCRTCRCERTCTX pCertCtx;
        while ((pCertCtx = RTCrStoreCertSearchNext(hStoreSrc, &Search)) != NULL)
        {
            int rc2 = RTCrStoreCertAddEncoded(hStore, pCertCtx->fFlags | (fFlags & RTCRCERTCTX_F_ADD_IF_NOT_FOUND),
                                              pCertCtx->pabEncoded, pCertCtx->cbEncoded, NULL);
            if (RT_FAILURE(rc2))
            {
                rc = rc2;
                if (!(fFlags & RTCRCERTCTX_F_ADD_CONTINUE_ON_ERROR))
                    break;
            }
            RTCrCertCtxRelease(pCertCtx);
        }

        int rc2 = RTCrStoreCertSearchDestroy(hStoreSrc, &Search); AssertRC(rc2);
    }
    return rc;
}
RT_EXPORT_SYMBOL(RTCrStoreCertAddFromStore);


RTDECL(int) RTCrStoreCertAddWantedFromStore(RTCRSTORE hStore, uint32_t fFlags, RTCRSTORE hSrcStore,
                                            PCRTCRCERTWANTED paWanted, size_t cWanted, bool *pafFound)
{
    /*
     * Validate input a little.
     */
    AssertReturn(!(fFlags & ~(RTCRCERTCTX_F_ADD_IF_NOT_FOUND | RTCRCERTCTX_F_ADD_CONTINUE_ON_ERROR)), VERR_INVALID_FLAGS);
    fFlags |= RTCRCERTCTX_F_ADD_IF_NOT_FOUND; /* forced */

    AssertReturn(cWanted, VERR_NOT_FOUND);
    for (uint32_t i = 0; i < cWanted; i++)
    {
        AssertReturn(!paWanted[i].pszSubject || *paWanted[i].pszSubject, VERR_INVALID_PARAMETER);
        AssertReturn(   paWanted[i].pszSubject
                     || paWanted[i].fSha1Fingerprint
                     || paWanted[i].fSha512Fingerprint,
                     VERR_INVALID_PARAMETER);
    }

    /*
     * Make sure we've got a result array.
     */
    bool *pafFoundFree = NULL;
    if (!pafFound)
    {
        pafFound = pafFoundFree = (bool *)RTMemTmpAllocZ(sizeof(bool) * cWanted);
        AssertReturn(pafFound, VERR_NO_TMP_MEMORY);
    }

    /*
     * Enumerate the store entries.
     */
    RTCRSTORECERTSEARCH Search;
    int rc = RTCrStoreCertFindAll(hSrcStore, &Search);
    if (RT_SUCCESS(rc))
    {
        rc = VWRN_NOT_FOUND;
        PCRTCRCERTCTX pCertCtx;
        while ((pCertCtx = RTCrStoreCertSearchNext(hSrcStore, &Search)) != NULL)
        {
            if (   (pCertCtx->fFlags & RTCRCERTCTX_F_ENC_MASK) == RTCRCERTCTX_F_ENC_X509_DER
                && pCertCtx->cbEncoded > 0
                && pCertCtx->pCert)
            {
                /*
                 * If the certificate is wanted, try add it to the store.
                 */
                uint8_t abSha1[RTSHA1_HASH_SIZE];
                RTSha1(pCertCtx->pabEncoded, pCertCtx->cbEncoded, abSha1);
                uint8_t abSha512[RTSHA512_HASH_SIZE];
                RTSha512(pCertCtx->pabEncoded, pCertCtx->cbEncoded, abSha512);
                if (rtCrStoreIsCertWanted(paWanted, cWanted, pafFound, pCertCtx->cbEncoded, abSha1, abSha512, pCertCtx->pCert))
                {
                    int rc2 = RTCrStoreCertAddEncoded(hStore,
                                                      RTCRCERTCTX_F_ENC_X509_DER | (fFlags & RTCRCERTCTX_F_ADD_IF_NOT_FOUND),
                                                      pCertCtx->pabEncoded, pCertCtx->cbEncoded, NULL /*pErrInfo*/);
                    if (RT_SUCCESS(rc2))
                    {
                        /*
                         * Mark it as found, stop if we've found all.
                         */
                        if (rtCrStoreMarkCertFound(pafFound, paWanted, cWanted,
                                                   pCertCtx->cbEncoded, abSha1, abSha512, pCertCtx->pCert))
                        {
                            if (RT_SUCCESS(rc))
                                rc = VINF_SUCCESS;
                            RTCrCertCtxRelease(pCertCtx);
                            break;
                        }
                    }
                    else
                    {
                        /*
                         * Some error adding the certificate.  Since it cannot be anything with
                         * the encoding, it must be something with the store or resources, so
                         * always return the error status.
                         */
                        rc = rc2;
                        if (!(fFlags & RTCRCERTCTX_F_ADD_CONTINUE_ON_ERROR))
                        {
                            RTCrCertCtxRelease(pCertCtx);
                            break;
                        }
                    }
                }
            }
            RTCrCertCtxRelease(pCertCtx);
        }
        int rc2 = RTCrStoreCertSearchDestroy(hSrcStore, &Search);
        AssertRC(rc2);
    }

    if (pafFoundFree)
        RTMemTmpFree(pafFoundFree);
    return rc;
}
RT_EXPORT_SYMBOL(RTCrStoreCertAddWantedFromStore);


RTDECL(int) RTCrStoreCertCheckWanted(RTCRSTORE hStore, PCRTCRCERTWANTED paWanted, size_t cWanted, bool *pafFound)
{
    /*
     * Validate input a little.
     */
    AssertReturn(cWanted, VERR_NOT_FOUND);
    for (uint32_t i = 0; i < cWanted; i++)
    {
        AssertReturn(!paWanted[i].pszSubject || *paWanted[i].pszSubject, VERR_INVALID_PARAMETER);
        AssertReturn(   paWanted[i].pszSubject
                     || paWanted[i].fSha1Fingerprint
                     || paWanted[i].fSha512Fingerprint,
                     VERR_INVALID_PARAMETER);
    }
    AssertPtrReturn(pafFound, VERR_INVALID_POINTER);

    /*
     * Clear the found array.
     */
    for (uint32_t iCert = 0; iCert < cWanted; iCert++)
        pafFound[iCert] = false;

    /*
     * Enumerate the store entries.
     */
    RTCRSTORECERTSEARCH Search;
    int rc = RTCrStoreCertFindAll(hStore, &Search);
    if (RT_SUCCESS(rc))
    {
        rc = VWRN_NOT_FOUND;
        PCRTCRCERTCTX pCertCtx;
        while ((pCertCtx = RTCrStoreCertSearchNext(hStore, &Search)) != NULL)
        {
            if (   (pCertCtx->fFlags & RTCRCERTCTX_F_ENC_MASK) == RTCRCERTCTX_F_ENC_X509_DER
                && pCertCtx->cbEncoded > 0
                && pCertCtx->pCert)
            {
                /*
                 * Hash it and check if it's wanted.  Stop when we've found all.
                 */
                uint8_t abSha1[RTSHA1_HASH_SIZE];
                RTSha1(pCertCtx->pabEncoded, pCertCtx->cbEncoded, abSha1);
                uint8_t abSha512[RTSHA512_HASH_SIZE];
                RTSha512(pCertCtx->pabEncoded, pCertCtx->cbEncoded, abSha512);
                if (rtCrStoreMarkCertFound(pafFound, paWanted, cWanted, pCertCtx->cbEncoded, abSha1, abSha512, pCertCtx->pCert))
                {
                    rc = VINF_SUCCESS;
                    RTCrCertCtxRelease(pCertCtx);
                    break;
                }
            }
            RTCrCertCtxRelease(pCertCtx);
        }
        int rc2 = RTCrStoreCertSearchDestroy(hStore, &Search);
        AssertRC(rc2);
    }

    return rc;
}
RT_EXPORT_SYMBOL(RTCrStoreCertAddWantedFromStore);


RTDECL(int) RTCrStoreCertAddFromFile(RTCRSTORE hStore, uint32_t fFlags, const char *pszFilename, PRTERRINFO pErrInfo)
{
    AssertReturn(!(fFlags & ~(RTCRCERTCTX_F_ADD_IF_NOT_FOUND | RTCRCERTCTX_F_ADD_CONTINUE_ON_ERROR)), VERR_INVALID_FLAGS);

    size_t      cbContent;
    void        *pvContent;
    int rc = RTFileReadAllEx(pszFilename, 0, 64U*_1M, RTFILE_RDALL_O_DENY_WRITE, &pvContent, &cbContent);
    if (RT_SUCCESS(rc))
    {
        /*
         * Is it a java key store file?
         */
        if (   cbContent > 32
            && ((uint32_t const *)pvContent)[0] == RT_H2BE_U32_C(UINT32_C(0xfeedfeed)) /* magic */
            && ((uint32_t const *)pvContent)[1] == RT_H2BE_U32_C(UINT32_C(0x00000002)) /* version */ )
            rc = RTCrStoreCertAddFromJavaKeyStoreInMem(hStore, fFlags, pvContent, cbContent, pszFilename, pErrInfo);
        /*
         * No assume PEM or DER encoded binary certificate.
         */
        else if (cbContent)
        {
            PCRTCRPEMSECTION pSectionHead;
            rc = RTCrPemParseContent(pvContent, cbContent,
                                     (fFlags & RTCRCERTCTX_F_ADD_CONTINUE_ON_ERROR)
                                     ? RTCRPEMREADFILE_F_CONTINUE_ON_ENCODING_ERROR : 0,
                                     g_aX509CertificateMarkers, RT_ELEMENTS(g_aX509CertificateMarkers),
                                     &pSectionHead, pErrInfo);
            if (RT_SUCCESS(rc))
            {
                PCRTCRPEMSECTION pCurSec = pSectionHead;
                while (pCurSec)
                {
                    int rc2 = RTCrStoreCertAddEncoded(hStore,
                                                      RTCRCERTCTX_F_ENC_X509_DER | (fFlags & RTCRCERTCTX_F_ADD_IF_NOT_FOUND),
                                                      pCurSec->pbData, pCurSec->cbData,
                                                      !RTErrInfoIsSet(pErrInfo) ? pErrInfo : NULL);
                    if (RT_FAILURE(rc2) && RT_SUCCESS(rc))
                    {
                        rc = rc2;
                        if (!(fFlags & RTCRCERTCTX_F_ADD_CONTINUE_ON_ERROR))
                            break;
                    }
                    pCurSec = pCurSec->pNext;
                }

                RTCrPemFreeSections(pSectionHead);
            }
        }
        else /* Will happen if proxy not set / no connection available. */
            rc = RTErrInfoSetF(pErrInfo, VERR_EOF, "Certificate '%s' is empty", pszFilename);
        RTFileReadAllFree(pvContent, cbContent);
    }
    else
        rc = RTErrInfoSetF(pErrInfo, rc, "RTFileReadAllEx failed with %Rrc on '%s'", rc, pszFilename);
    return rc;
}
RT_EXPORT_SYMBOL(RTCrStoreCertAddFromFile);


RTDECL(int) RTCrStoreCertAddWantedFromFile(RTCRSTORE hStore, uint32_t fFlags, const char *pszFilename,
                                           PCRTCRCERTWANTED paWanted, size_t cWanted, bool *pafFound, PRTERRINFO pErrInfo)
{
    /*
     * Validate input a little.
     */
    AssertReturn(!(fFlags & ~(RTCRCERTCTX_F_ADD_IF_NOT_FOUND | RTCRCERTCTX_F_ADD_CONTINUE_ON_ERROR)), VERR_INVALID_FLAGS);
    fFlags |= RTCRCERTCTX_F_ADD_IF_NOT_FOUND; /* forced */

    AssertReturn(cWanted, VERR_NOT_FOUND);
    for (uint32_t i = 0; i < cWanted; i++)
    {
        AssertReturn(!paWanted[i].pszSubject || *paWanted[i].pszSubject, VERR_INVALID_PARAMETER);
        AssertReturn(   paWanted[i].pszSubject
                     || paWanted[i].fSha1Fingerprint
                     || paWanted[i].fSha512Fingerprint,
                     VERR_INVALID_PARAMETER);
    }

    /*
     * Make sure we've got a result array.
     */
    bool *pafFoundFree = NULL;
    if (!pafFound)
    {
        pafFound = pafFoundFree = (bool *)RTMemTmpAllocZ(sizeof(bool) * cWanted);
        AssertReturn(pafFound, VERR_NO_TMP_MEMORY);
    }

    size_t cbContent;
    void  *pvContent;
    int rc = RTFileReadAllEx(pszFilename, 0, 64U*_1M, RTFILE_RDALL_O_DENY_WRITE, &pvContent, &cbContent);
    if (RT_SUCCESS(rc))
    {
        /*
         * Is it a java key store file?   If so, load it into a tmp store
         * which we can search.  Don't want to duplicate the JKS reader code.
         */
        if (   cbContent > 32
            && ((uint32_t const *)pvContent)[0] == RT_H2BE_U32_C(UINT32_C(0xfeedfeed)) /* magic */
            && ((uint32_t const *)pvContent)[1] == RT_H2BE_U32_C(UINT32_C(0x00000002)) /* version */ )
        {
            RTCRSTORE hTmpStore;
            rc = RTCrStoreCreateInMem(&hTmpStore, 64);
            if (RT_SUCCESS(rc))
            {
                rc = RTCrStoreCertAddFromJavaKeyStoreInMem(hStore, fFlags, pvContent, cbContent, pszFilename, pErrInfo);
                if (RT_SUCCESS(rc))
                    rc = RTCrStoreCertAddWantedFromStore(hStore, fFlags, hTmpStore, paWanted, cWanted, pafFound);
                RTCrStoreRelease(hTmpStore);
            }
            else
                rc = RTErrInfoSet(pErrInfo, rc, "Error creating temporary crypto store");
        }
        /*
         * No assume PEM or DER encoded binary certificate.  Inspect them one by one.
         */
        else if (cbContent)
        {
            PCRTCRPEMSECTION pSectionHead;
            rc = RTCrPemParseContent(pvContent, cbContent,
                                     (fFlags & RTCRCERTCTX_F_ADD_CONTINUE_ON_ERROR)
                                     ? RTCRPEMREADFILE_F_CONTINUE_ON_ENCODING_ERROR : 0,
                                     g_aX509CertificateMarkers, RT_ELEMENTS(g_aX509CertificateMarkers),
                                     &pSectionHead, pErrInfo);
            if (RT_SUCCESS(rc))
            {
                rc = VWRN_NOT_FOUND;
                for (PCRTCRPEMSECTION pCurSec = pSectionHead; pCurSec; pCurSec = pCurSec->pNext)
                {
                    if (!pCurSec->cbData)
                        continue;

                    /*
                     * See if this is a binary blob we might be interested in.
                     */
                    uint8_t abSha1[RTSHA1_HASH_SIZE];
                    RTSha1(pCurSec->pbData, pCurSec->cbData, abSha1);
                    uint8_t abSha512[RTSHA512_HASH_SIZE];
                    RTSha512(pCurSec->pbData, pCurSec->cbData, abSha512);
                    if (!rtCrStoreIsCertWanted(paWanted, cWanted, pafFound, pCurSec->cbData, abSha1, abSha512, NULL))
                        continue;

                    /*
                     * Decode the certificate so we can match the subject string.
                     */
                    RTASN1CURSORPRIMARY Cursor;
                    RTAsn1CursorInitPrimary(&Cursor, pCurSec->pbData, (uint32_t)pCurSec->cbData,
                                            !RTErrInfoIsSet(pErrInfo) ? pErrInfo : NULL,
                                            &g_RTAsn1DefaultAllocator, RTASN1CURSOR_FLAGS_DER, "InMem");
                    RTCRX509CERTIFICATE X509Cert;
                    int rc2 = RTCrX509Certificate_DecodeAsn1(&Cursor.Cursor, 0, &X509Cert, "Cert");
                    if (RT_SUCCESS(rc2))
                    {
                        rc2 = RTCrX509Certificate_CheckSanity(&X509Cert, 0, !RTErrInfoIsSet(pErrInfo) ? pErrInfo : NULL, "Cert");
                        if (RT_SUCCESS(rc2))
                        {
                            if (rtCrStoreIsCertWanted(paWanted, cWanted, pafFound, pCurSec->cbData, abSha1, abSha512, &X509Cert))
                            {
                                /*
                                 * The certificate is wanted, now add it to the store.
                                 */
                                rc2 = RTCrStoreCertAddEncoded(hStore,
                                                              RTCRCERTCTX_F_ENC_X509_DER
                                                              | (fFlags & RTCRCERTCTX_F_ADD_IF_NOT_FOUND),
                                                              pCurSec->pbData, pCurSec->cbData,
                                                              !RTErrInfoIsSet(pErrInfo) ? pErrInfo : NULL);
                                if (RT_SUCCESS(rc2))
                                {
                                    /*
                                     * Mark it as found, stop if we've found all.
                                     */
                                    if (rtCrStoreMarkCertFound(pafFound, paWanted, cWanted,
                                                               pCurSec->cbData, abSha1, abSha512, &X509Cert))
                                    {
                                        RTAsn1VtDelete(&X509Cert.SeqCore.Asn1Core);
                                        rc = VINF_SUCCESS;
                                        break;
                                    }
                                }
                            }
                        }
                        else
                            Assert(!pErrInfo || RTErrInfoIsSet(pErrInfo));
                        RTAsn1VtDelete(&X509Cert.SeqCore.Asn1Core);
                    }
                    else if (!RTErrInfoIsSet(pErrInfo))
                        RTErrInfoSetF(pErrInfo, rc2, "RTCrX509Certificate_DecodeAsn1 failed");

                    /*
                     * Stop on error, if requested.  Otherwise, let pErrInfo keep it.
                     */
                    if (RT_FAILURE(rc2) && !(fFlags & RTCRCERTCTX_F_ADD_CONTINUE_ON_ERROR))
                    {
                        rc = rc2;
                        break;
                    }
                } /* For each PEM section. */

                RTCrPemFreeSections(pSectionHead);
            }
        }
        else /* Will happen if proxy not set / no connection available. */
            rc = RTErrInfoSetF(pErrInfo, VERR_EOF, "Certificate '%s' is empty", pszFilename);
        RTFileReadAllFree(pvContent, cbContent);
    }
    else
        rc = RTErrInfoSetF(pErrInfo, rc, "RTFileReadAllEx failed with %Rrc on '%s'", rc, pszFilename);

    if (pafFoundFree)
        RTMemTmpFree(pafFoundFree);
    return rc;
}
RT_EXPORT_SYMBOL(RTCrStoreCertAddWantedFromFile);


/**
 * Checks if the directory entry matches the specified suffixes.
 *
 * @returns true on match, false on mismatch.
 * @param   pDirEntry           The directory to check.
 * @param   paSuffixes          The array of suffixes to match against.
 * @param   cSuffixes           The number of suffixes in the array.
 */
DECLINLINE(bool) rtCrStoreIsSuffixMatch(PCRTDIRENTRY pDirEntry, PCRTSTRTUPLE paSuffixes, size_t cSuffixes)
{
    if (cSuffixes == 0)
        return true;

    size_t const cchName = pDirEntry->cbName;
    size_t i = cSuffixes;
    while (i-- > 0)
        if (   cchName > paSuffixes[i].cch
            && memcmp(&pDirEntry->szName[cchName - paSuffixes[i].cch], paSuffixes[i].psz, paSuffixes[i].cch) == 0)
            return true;

    return false;
}


RTDECL(int) RTCrStoreCertAddFromDir(RTCRSTORE hStore, uint32_t fFlags, const char *pszDir,
                                    PCRTSTRTUPLE paSuffixes, size_t cSuffixes, PRTERRINFO pErrInfo)
{
    /*
     * Validate input.
     */
    AssertReturn(!(fFlags & ~(RTCRCERTCTX_F_ADD_IF_NOT_FOUND | RTCRCERTCTX_F_ADD_CONTINUE_ON_ERROR)), VERR_INVALID_FLAGS);
    size_t i = cSuffixes;
    while (i-- > 0)
    {
        Assert(paSuffixes[i].cch > 0);
        Assert(strlen(paSuffixes[i].psz) == paSuffixes[i].cch);
    }

    /*
     * Prepare for constructing path to the files in the directory, so that we
     * can open them.
     */
    char szPath[RTPATH_MAX];
    int rc = RTStrCopy(szPath, sizeof(szPath), pszDir);
    if (RT_SUCCESS(rc))
    {
        size_t cchPath = RTPathEnsureTrailingSeparator(szPath, sizeof(szPath));
        if (cchPath > 0)
        {
            size_t const cbMaxFilename = sizeof(szPath) - cchPath;

            /*
             * Enumerate the directory.
             */
            RTDIR hDir;
            rc = RTDirOpen(&hDir, pszDir);
            if (RT_SUCCESS(rc))
            {
                for (;;)
                {
                    /* Read the next entry. */
                    union
                    {
                        RTDIRENTRY  DirEntry;
                        uint8_t     abPadding[RTPATH_MAX + sizeof(RTDIRENTRY)];
                    } u;
                    size_t cbBuf = sizeof(u);
                    int rc2 = RTDirRead(hDir, &u.DirEntry, &cbBuf);
                    if (RT_SUCCESS(rc2))
                    {
                        if (   (   u.DirEntry.enmType == RTDIRENTRYTYPE_FILE
                                || u.DirEntry.enmType == RTDIRENTRYTYPE_SYMLINK
                                || (   u.DirEntry.enmType == RTDIRENTRYTYPE_UNKNOWN
                                    && !RTDirEntryIsStdDotLink(&u.DirEntry)) )
                            && rtCrStoreIsSuffixMatch(&u.DirEntry, paSuffixes, cSuffixes) )
                        {
                            if (u.DirEntry.cbName < cbMaxFilename)
                            {
                                memcpy(&szPath[cchPath], u.DirEntry.szName, u.DirEntry.cbName + 1);
                                rc2 = RTDirQueryUnknownType(szPath, true /*fFollowSymlinks*/, &u.DirEntry.enmType);
                                if (   RT_SUCCESS(rc2)
                                    && u.DirEntry.enmType == RTDIRENTRYTYPE_FILE)
                                {
                                    /*
                                     * Add it.
                                     */
                                    rc2 = RTCrStoreCertAddFromFile(hStore, fFlags, szPath, pErrInfo);
                                    if (RT_FAILURE(rc2))
                                    {
                                        rc = rc2;
                                        if (!(fFlags & RTCRCERTCTX_F_ADD_CONTINUE_ON_ERROR))
                                            break;
                                    }
                                }
                            }
                            else
                            {
                                rc = RTErrInfoAddF(pErrInfo, VERR_FILENAME_TOO_LONG,
                                                   "  Too long filename (%u bytes)", u.DirEntry.cbName);
                                if (!(fFlags & RTCRCERTCTX_F_ADD_CONTINUE_ON_ERROR))
                                    break;
                            }
                        }
                    }
                    else
                    {
                        if (rc2 != VERR_NO_MORE_FILES)
                            rc = RTErrInfoAddF(pErrInfo, rc2, "  RTDirRead failed: %Rrc", rc2);
                        break;
                    }
                }

                RTDirClose(hDir);
            }
            else
                rc = RTErrInfoAddF(pErrInfo, rc, "  RTDirOpen('%s'): %Rrc", pszDir, rc);
        }
        else
            rc = VERR_FILENAME_TOO_LONG;
    }
    return rc;
}
RT_EXPORT_SYMBOL(RTCrStoreCertAddFromDir);


RTDECL(int) RTCrStoreCertAddWantedFromDir(RTCRSTORE hStore, uint32_t fFlags,
                                          const char *pszDir, PCRTSTRTUPLE paSuffixes, size_t cSuffixes,
                                          PCRTCRCERTWANTED paWanted, size_t cWanted, bool *pafFound, PRTERRINFO pErrInfo)
{
    /*
     * Validate input a little.
     */
    AssertReturn(*pszDir, VERR_PATH_ZERO_LENGTH);
    AssertReturn(!(fFlags & ~(RTCRCERTCTX_F_ADD_IF_NOT_FOUND | RTCRCERTCTX_F_ADD_CONTINUE_ON_ERROR)), VERR_INVALID_FLAGS);
    fFlags |= RTCRCERTCTX_F_ADD_IF_NOT_FOUND; /* forced */

    AssertReturn(cWanted, VERR_NOT_FOUND);
    for (uint32_t i = 0; i < cWanted; i++)
    {
        AssertReturn(!paWanted[i].pszSubject || *paWanted[i].pszSubject, VERR_INVALID_PARAMETER);
        AssertReturn(   paWanted[i].pszSubject
                     || paWanted[i].fSha1Fingerprint
                     || paWanted[i].fSha512Fingerprint,
                     VERR_INVALID_PARAMETER);
    }

    /*
     * Prepare for constructing path to the files in the directory, so that we
     * can open them.
     */
    char szPath[RTPATH_MAX];
    int rc = RTStrCopy(szPath, sizeof(szPath), pszDir);
    if (RT_SUCCESS(rc))
    {
        size_t cchPath = RTPathEnsureTrailingSeparator(szPath, sizeof(szPath));
        if (cchPath > 0)
        {
            size_t const cbMaxFilename = sizeof(szPath) - cchPath;

            /*
             * Enumerate the directory.
             */
            RTDIR hDir;
            rc = RTDirOpen(&hDir, pszDir);
            if (RT_SUCCESS(rc))
            {
                rc = VWRN_NOT_FOUND;
                for (;;)
                {
                    /* Read the next entry. */
                    union
                    {
                        RTDIRENTRY  DirEntry;
                        uint8_t     abPadding[RTPATH_MAX + sizeof(RTDIRENTRY)];
                    } u;
                    size_t cbEntry = sizeof(u);
                    int rc2 = RTDirRead(hDir, &u.DirEntry, &cbEntry);
                    if (RT_SUCCESS(rc2))
                    {
                        if (   (   u.DirEntry.enmType == RTDIRENTRYTYPE_FILE
                                || u.DirEntry.enmType == RTDIRENTRYTYPE_SYMLINK
                                || (   u.DirEntry.enmType == RTDIRENTRYTYPE_UNKNOWN
                                    && !RTDirEntryIsStdDotLink(&u.DirEntry)) )
                            && rtCrStoreIsSuffixMatch(&u.DirEntry, paSuffixes, cSuffixes) )
                        {
                            if (u.DirEntry.cbName < cbMaxFilename)
                            {
                                memcpy(&szPath[cchPath], u.DirEntry.szName, u.DirEntry.cbName);
                                szPath[cchPath + u.DirEntry.cbName] = '\0';
                                if (u.DirEntry.enmType != RTDIRENTRYTYPE_FILE)
                                    RTDirQueryUnknownType(szPath, true /*fFollowSymlinks*/, &u.DirEntry.enmType);
                                if (u.DirEntry.enmType == RTDIRENTRYTYPE_FILE)
                                {
                                    rc2 = RTCrStoreCertAddWantedFromFile(hStore, fFlags, szPath,
                                                                         paWanted, cWanted, pafFound, pErrInfo);
                                    if (rc2 == VINF_SUCCESS)
                                    {
                                        Assert(rtCrStoreAllDone(pafFound, cWanted));
                                        if (RT_SUCCESS(rc))
                                            rc = VINF_SUCCESS;
                                        break;
                                    }
                                    if (RT_FAILURE(rc2) && !(fFlags & RTCRCERTCTX_F_ADD_CONTINUE_ON_ERROR))
                                    {
                                        rc = rc2;
                                        break;
                                    }
                                }
                            }
                            else
                            {
                                /*
                                 * pErrInfo keeps the status code unless it's fatal.
                                 */
                                RTErrInfoAddF(pErrInfo, VERR_FILENAME_TOO_LONG,
                                              "  Too long filename (%u bytes)", u.DirEntry.cbName);
                                if (!(fFlags & RTCRCERTCTX_F_ADD_CONTINUE_ON_ERROR))
                                {
                                    rc = VERR_FILENAME_TOO_LONG;
                                    break;
                                }
                            }
                        }
                    }
                    else
                    {
                        if (rc2 != VERR_NO_MORE_FILES)
                        {
                            RTErrInfoAddF(pErrInfo, rc2, "RTDirRead failed: %Rrc", rc2);
                            if (!(fFlags & RTCRCERTCTX_F_ADD_CONTINUE_ON_ERROR))
                                rc = rc2;
                        }
                        break;
                    }
                }
                RTDirClose(hDir);
            }
        }
        else
            rc = VERR_FILENAME_TOO_LONG;
    }
    return rc;
}
RT_EXPORT_SYMBOL(RTCrStoreCertAddWantedFromDir);