Coverage Report

Created: 2026-12-01 07:06

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/xmlsec/src/openssl/x509.c
Line
Count
Source
1
/**
2
 * XML Security Library (http://www.aleksey.com/xmlsec).
3
 *
4
 * This is free software; see the Copyright file in the source distribution for precise wording.
5
 *
6
 * Copyright (C) 2002-2026 Aleksey Sanin <aleksey@aleksey.com>. All Rights Reserved.
7
 */
8
/**
9
 * @addtogroup xmlsec_openssl_x509
10
 * @brief X509 certificates implementation for OpenSSL.
11
 * @details X509 key data implementation.
12
 */
13
#include "globals.h"
14
15
#include <stdlib.h>
16
#include <stdio.h>
17
#include <string.h>
18
#include <time.h>
19
20
#include <xmlsec/xmlsec.h>
21
#include <xmlsec/base64.h>
22
#include <xmlsec/keys.h>
23
#include <xmlsec/keyinfo.h>
24
#include <xmlsec/keysmngr.h>
25
#include <xmlsec/x509.h>
26
#include <xmlsec/errors.h>
27
#include <openssl/pem.h>
28
#include <xmlsec/private.h>
29
#include <xmlsec/xmltree.h>
30
31
#include <xmlsec/openssl/crypto.h>
32
#include <xmlsec/openssl/evp.h>
33
#include <xmlsec/openssl/x509.h>
34
35
/* Windows overwrites X509_NAME and other things that break openssl */
36
#include <openssl/evp.h>
37
#include <openssl/x509.h>
38
#include <openssl/x509v3.h>
39
#include <openssl/asn1.h>
40
41
#if defined(XMLSEC_OPENSSL_IS_BORINGSSL) || defined(XMLSEC_OPENSSL_IS_AWSLC)
42
#include <openssl/mem.h>
43
#endif /* XMLSEC_OPENSSL_IS_BORINGSSL || XMLSEC_OPENSSL_IS_AWSLC */
44
45
#include "../cast_helpers.h"
46
#include "../x509_helpers.h"
47
48
#include "openssl_compat.h"
49
#include "private.h"
50
51
#ifndef XMLSEC_NO_X509
52
53
54
/******************************************************************************
55
 *
56
 * X509 utility functions
57
 *
58
 *****************************************************************************/
59
static int              xmlSecOpenSSLVerifyAndAdoptX509KeyData  (xmlSecKeyPtr key,
60
                                                                 xmlSecKeyDataPtr data,
61
                                                                 xmlSecKeyInfoCtxPtr keyInfoCtx);
62
static X509*            xmlSecOpenSSLX509CertDerRead            (const xmlSecByte* buf,
63
                                                                 xmlSecSize size);
64
static X509_CRL*        xmlSecOpenSSLX509CrlDerRead             (const xmlSecByte* buf,
65
                                                                 xmlSecSize size);
66
static void             xmlSecOpenSSLX509CertDebugDump          (X509* cert,
67
                                                                 FILE* output);
68
static void             xmlSecOpenSSLX509CertDebugXmlDump       (X509* cert,
69
                                                                 FILE* output);
70
71
/******************************************************************************
72
 *
73
 * Internal OpenSSL X509 data CTX
74
 *
75
 *****************************************************************************/
76
typedef struct _xmlSecOpenSSLX509DataCtx                xmlSecOpenSSLX509DataCtx,
77
                                                        *xmlSecOpenSSLX509DataCtxPtr;
78
struct _xmlSecOpenSSLX509DataCtx {
79
    X509*               keyCert;    /* OWNED BY certsList */
80
    STACK_OF(X509)*     certsList;
81
    STACK_OF(X509_CRL)* crlsList;
82
};
83
84
/******************************************************************************
85
 *
86
 * &lt;dsig:X509Data/&gt; processing (http://www.w3.org/TR/xmldsig-core/#sec-X509Data)
87
 *
88
 *****************************************************************************/
89
19.6k
XMLSEC_KEY_DATA_DECLARE(OpenSSLX509Data, xmlSecOpenSSLX509DataCtx)
90
19.6k
#define xmlSecOpenSSLX509DataSize XMLSEC_KEY_DATA_SIZE(OpenSSLX509Data)
91
19.6k
92
19.6k
static int              xmlSecOpenSSLKeyDataX509Initialize      (xmlSecKeyDataPtr data);
93
19.6k
static int              xmlSecOpenSSLKeyDataX509Duplicate       (xmlSecKeyDataPtr dst,
94
19.6k
                                                                 xmlSecKeyDataPtr src);
95
19.6k
static void             xmlSecOpenSSLKeyDataX509Finalize        (xmlSecKeyDataPtr data);
96
19.6k
static int              xmlSecOpenSSLKeyDataX509XmlRead         (xmlSecKeyDataId id,
97
19.6k
                                                                 xmlSecKeyPtr key,
98
19.6k
                                                                 xmlNodePtr node,
99
19.6k
                                                                 xmlSecKeyInfoCtxPtr keyInfoCtx);
100
19.6k
static int              xmlSecOpenSSLKeyDataX509XmlWrite        (xmlSecKeyDataId id,
101
19.6k
                                                                 xmlSecKeyPtr key,
102
19.6k
                                                                 xmlNodePtr node,
103
19.6k
                                                                 xmlSecKeyInfoCtxPtr keyInfoCtx);
104
19.6k
105
19.6k
static void             xmlSecOpenSSLKeyDataX509DebugDump       (xmlSecKeyDataPtr data,
106
19.6k
                                                                 FILE* output);
107
19.6k
static void             xmlSecOpenSSLKeyDataX509DebugXmlDump    (xmlSecKeyDataPtr data,
108
19.6k
                                                                 FILE* output);
109
19.6k
110
19.6k
111
19.6k
typedef struct _xmlSecOpenSSLKeyDataX509Context {
112
19.6k
    xmlSecSize crtPos;
113
19.6k
    xmlSecSize crtSize;
114
19.6k
    xmlSecSize crlPos;
115
19.6k
    xmlSecSize crlSize;
116
19.6k
} xmlSecOpenSSLKeyDataX509Context;
117
19.6k
118
19.6k
static int              xmlSecOpenSSLKeyDataX509Read            (xmlSecKeyDataPtr data,
119
19.6k
                                                                 xmlSecKeyX509DataValuePtr x509Value,
120
19.6k
                                                                 xmlSecKeysMngrPtr keysMngr,
121
19.6k
                                                                 unsigned int flags);
122
19.6k
123
19.6k
static int              xmlSecOpenSSLKeyDataX509Write           (xmlSecKeyDataPtr data,
124
19.6k
                                                                  xmlSecKeyX509DataValuePtr x509Value,
125
19.6k
                                                                  int content,
126
19.6k
                                                                  void* context);
127
19.6k
128
19.6k
static xmlSecKeyDataKlass xmlSecOpenSSLKeyDataX509Klass = {
129
19.6k
    sizeof(xmlSecKeyDataKlass),
130
19.6k
    xmlSecOpenSSLX509DataSize,
131
19.6k
132
19.6k
    /* data */
133
19.6k
    xmlSecNameX509Data,
134
19.6k
    xmlSecKeyDataUsageReadFromFile | xmlSecKeyDataUsageKeyInfoNode | xmlSecKeyDataUsageRetrievalMethodNodeXml,
135
19.6k
                                                /* xmlSecKeyDataUsage usage; */
136
19.6k
    xmlSecHrefX509Data,                         /* const xmlChar* href; */
137
19.6k
    xmlSecNodeX509Data,                         /* const xmlChar* dataNodeName; */
138
19.6k
    xmlSecDSigNs,                               /* const xmlChar* dataNodeNs; */
139
19.6k
140
19.6k
    /* constructors/destructor */
141
19.6k
    xmlSecOpenSSLKeyDataX509Initialize,         /* xmlSecKeyDataInitMethod initialize; */
142
19.6k
    xmlSecOpenSSLKeyDataX509Duplicate,          /* xmlSecKeyDataDuplicateMethod duplicate; */
143
19.6k
    xmlSecOpenSSLKeyDataX509Finalize,           /* xmlSecKeyDataFinalizeMethod finalize; */
144
19.6k
    NULL,                                       /* xmlSecKeyDataGenerateMethod generate; */
145
19.6k
146
19.6k
    /* get info */
147
19.6k
    NULL,                                       /* xmlSecKeyDataGetTypeMethod getType; */
148
19.6k
    NULL,                                       /* xmlSecKeyDataGetSizeMethod getSize; */
149
19.6k
    NULL,                                       /* DEPRECATED xmlSecKeyDataGetIdentifier getIdentifier; */
150
19.6k
151
19.6k
    /* read/write */
152
19.6k
    xmlSecOpenSSLKeyDataX509XmlRead,            /* xmlSecKeyDataXmlReadMethod xmlRead; */
153
19.6k
    xmlSecOpenSSLKeyDataX509XmlWrite,           /* xmlSecKeyDataXmlWriteMethod xmlWrite; */
154
19.6k
    NULL,                                       /* xmlSecKeyDataBinReadMethod binRead; */
155
19.6k
    NULL,                                       /* xmlSecKeyDataBinWriteMethod binWrite; */
156
19.6k
157
19.6k
    /* debug */
158
19.6k
    xmlSecOpenSSLKeyDataX509DebugDump,          /* xmlSecKeyDataDebugDumpMethod debugDump; */
159
19.6k
    xmlSecOpenSSLKeyDataX509DebugXmlDump,       /* xmlSecKeyDataDebugDumpMethod debugXmlDump; */
160
19.6k
161
19.6k
    /* reserved for the future */
162
19.6k
    NULL,                                       /* void* reserved0; */
163
19.6k
    NULL,                                       /* void* reserved1; */
164
19.6k
};
165
19.6k
166
19.6k
/**
167
19.6k
 * @brief The OpenSSL X509 key data klass.
168
19.6k
 * @details The OpenSSL X509 key data klass (http://www.w3.org/TR/xmldsig-core/#sec-X509Data).
169
19.6k
 * @return the X509 data klass.
170
19.6k
 */
171
19.6k
xmlSecKeyDataId
172
42.7k
xmlSecOpenSSLKeyDataX509GetKlass(void) {
173
42.7k
    return(&xmlSecOpenSSLKeyDataX509Klass);
174
42.7k
}
175
176
/**
177
 * @brief Gets the certificate from which the key was extracted.
178
 * @param data the pointer to X509 key data.
179
 * @return a borrowed pointer to the key's certificate, or NULL if key data was not used for key
180
 * extraction or an error occurs; the caller must NOT free it.
181
 */
182
X509*
183
0
xmlSecOpenSSLKeyDataX509GetKeyCert(xmlSecKeyDataPtr data) {
184
0
    xmlSecOpenSSLX509DataCtxPtr ctx;
185
186
0
    xmlSecAssert2(xmlSecKeyDataCheckId(data, xmlSecOpenSSLKeyDataX509Id), NULL);
187
188
0
    ctx = xmlSecOpenSSLX509DataGetCtx(data);
189
0
    xmlSecAssert2(ctx != NULL, NULL);
190
191
0
    return(ctx->keyCert);
192
0
}
193
194
195
static int
196
184
xmlSecOpenSSLKeyDataX509AddCertInternal(xmlSecOpenSSLX509DataCtxPtr ctx, X509* cert, int keyCert) {
197
184
    xmlSecOpenSSLSizeT ret;
198
199
184
    xmlSecAssert2(ctx != NULL, -1);
200
184
    xmlSecAssert2(cert != NULL, -1);
201
202
184
    if(ctx->certsList == NULL) {
203
102
        ctx->certsList = sk_X509_new_null();
204
102
        if(ctx->certsList == NULL) {
205
0
            xmlSecOpenSSLError("sk_X509_new_null", NULL);
206
0
            return(-1);
207
0
        }
208
102
    }
209
210
    /* we don't want duplicates: if this exact cert object is already in the list,
211
       remove it so it can be re-inserted below (do not free it - we re-add the
212
       same object) */
213
184
    (void)sk_X509_delete_ptr(ctx->certsList, cert);
214
215
    /* ensure that key cert is the first one */
216
184
    if(keyCert != 0) {
217
0
        ret = sk_X509_insert(ctx->certsList, cert, 0);
218
0
        if(ret <= 0) {
219
0
            xmlSecOpenSSLError("sk_X509_insert(0)", NULL);
220
0
            return(-1);
221
0
        }
222
184
    } else {
223
184
        ret = sk_X509_push(ctx->certsList, cert);
224
184
        if(ret <= 0) {
225
0
            xmlSecOpenSSLError("sk_X509_push", NULL);
226
0
            return(-1);
227
0
        }
228
184
    }
229
230
    /* done */
231
184
    return(0);
232
184
}
233
234
/**
235
 * @brief Adds certificate to the X509 key data and sets it as the key's certificate.
236
 * @details On success, ownership of @p cert transfers to xmlsec; on failure the caller retains ownership.
237
 * This function DOES NOT check if the key matches the key cert
238
 * (use #xmlSecOpenSSLAppKeyCertLoadBIO that performs this check).
239
 * @param data the pointer to X509 key data.
240
 * @param cert the pointer to OpenSSL X509 certificate.
241
 * @return 0 on success or a negative value if an error occurs.
242
 */
243
int
244
0
xmlSecOpenSSLKeyDataX509AdoptKeyCert(xmlSecKeyDataPtr data, X509* cert) {
245
0
    xmlSecOpenSSLX509DataCtxPtr ctx;
246
0
    int ret;
247
248
0
    xmlSecAssert2(xmlSecKeyDataCheckId(data, xmlSecOpenSSLKeyDataX509Id), -1);
249
0
    xmlSecAssert2(cert != NULL, -1);
250
251
0
    ctx = xmlSecOpenSSLX509DataGetCtx(data);
252
0
    xmlSecAssert2(ctx != NULL, -1);
253
0
    xmlSecAssert2(ctx->keyCert == NULL, -1);
254
255
0
    ret = xmlSecOpenSSLKeyDataX509AddCertInternal(ctx, cert, 1); /* key cert */
256
0
    if(ret < 0) {
257
0
        xmlSecInternalError("xmlSecOpenSSLKeyDataX509AddCertInternal", xmlSecKeyDataGetName(data));
258
0
        return(-1);
259
0
    }
260
261
    /* cert is now owned by data, we can't fail or there will be a double free */
262
0
    ctx->keyCert = cert;
263
0
    return(0);
264
0
}
265
266
/**
267
 * @brief Adds certificate to the X509 key data.
268
 * @details On success, ownership of @p cert transfers to xmlsec; on failure the caller retains ownership.
269
 * @param data the pointer to X509 key data.
270
 * @param cert the pointer to OpenSSL X509 certificate.
271
 * @return 0 on success or a negative value if an error occurs.
272
 */
273
int
274
184
xmlSecOpenSSLKeyDataX509AdoptCert(xmlSecKeyDataPtr data, X509* cert) {
275
184
    xmlSecOpenSSLX509DataCtxPtr ctx;
276
184
    int ret;
277
278
184
    xmlSecAssert2(xmlSecKeyDataCheckId(data, xmlSecOpenSSLKeyDataX509Id), -1);
279
184
    xmlSecAssert2(cert != NULL, -1);
280
281
184
    ctx = xmlSecOpenSSLX509DataGetCtx(data);
282
184
    xmlSecAssert2(ctx != NULL, -1);
283
284
    /* pkcs12 files sometimes have key cert twice: as the key cert and as the cert in the chain,
285
     * if this ever changes -- fix xmlSecOpenSSLCreateKey that relies on this check */
286
184
    if((ctx->keyCert != NULL) && ((ctx->keyCert == cert) || (X509_cmp(ctx->keyCert, cert) == 0))) {
287
        /* ownership contract: cert must be a caller-owned object. When it is
288
         * pointer-identical to ctx->keyCert, the caller must have X509_up_ref()'d
289
         * it (as the app.c/pkcs12 paths do) so this X509_free() only drops the
290
         * extra reference and the key cert itself stays alive. */
291
0
        X509_free(cert); /* caller expects data to own the cert on success. */
292
0
        return(0);
293
0
    }
294
184
    ret = xmlSecOpenSSLKeyDataX509AddCertInternal(ctx, cert, 0); /* not a key cert */
295
184
    if(ret < 0) {
296
0
        xmlSecInternalError("xmlSecOpenSSLKeyDataX509AddCertInternal", xmlSecKeyDataGetName(data));
297
0
        return(-1);
298
0
    }
299
300
    /* success: cert is now owned by data */
301
184
    return(0);
302
184
}
303
304
/**
305
 * @brief Gets a certificate from X509 key data.
306
 * @param data the pointer to X509 key data.
307
 * @param pos the desired certificate position, must be less than the number of
308
 * certificates in @p data (see xmlSecOpenSSLKeyDataX509GetCertsSize).
309
 * @return a borrowed pointer to the certificate; the caller must NOT free it.
310
 */
311
X509*
312
0
xmlSecOpenSSLKeyDataX509GetCert(xmlSecKeyDataPtr data, xmlSecSize pos) {
313
0
    xmlSecOpenSSLX509DataCtxPtr ctx;
314
0
    xmlSecOpenSSLSizeT iPos;
315
316
0
    xmlSecAssert2(xmlSecKeyDataCheckId(data, xmlSecOpenSSLKeyDataX509Id), NULL);
317
318
0
    ctx = xmlSecOpenSSLX509DataGetCtx(data);
319
0
    xmlSecAssert2(ctx != NULL, NULL);
320
0
    xmlSecAssert2(ctx->certsList != NULL, NULL);
321
322
    /* to ensure that key cert is always first we put it at the first position
323
     * in xmlSecOpenSSLKeyDataX509AddCertInternal */
324
0
    XMLSEC_OPENSSL_SAFE_CAST_SIZE_TO_SIZE_T(pos, iPos, return(NULL), NULL);
325
0
    xmlSecAssert2(iPos < sk_X509_num(ctx->certsList), NULL);
326
0
    return(sk_X509_value(ctx->certsList, iPos));
327
0
}
328
329
/**
330
 * @brief Gets the number of certificates in @p data.
331
 * @param data the pointer to X509 key data.
332
 * @return the number of certificates in @p data.
333
 */
334
xmlSecSize
335
0
xmlSecOpenSSLKeyDataX509GetCertsSize(xmlSecKeyDataPtr data) {
336
0
    xmlSecOpenSSLX509DataCtxPtr ctx;
337
0
    xmlSecOpenSSLSizeT ret;
338
0
    xmlSecSize res;
339
340
0
    xmlSecAssert2(xmlSecKeyDataCheckId(data, xmlSecOpenSSLKeyDataX509Id), 0);
341
342
0
    ctx = xmlSecOpenSSLX509DataGetCtx(data);
343
0
    xmlSecAssert2(ctx != NULL, 0);
344
345
0
    if(ctx->certsList == NULL) {
346
0
        return(0);
347
0
    }
348
349
0
    ret = sk_X509_num(ctx->certsList);
350
0
    XMLSEC_OPENSSL_SAFE_CAST_SIZE_T_TO_SIZE(ret, res, return(0), NULL);
351
0
    return(res);
352
0
}
353
354
/**
355
 * @brief Adds CRL to the X509 key data.
356
 * @details On success, ownership of @p crl transfers to xmlsec; on failure the caller retains ownership.
357
 * @param data the pointer to X509 key data.
358
 * @param crl the pointer to OpenSSL X509 CRL.
359
 * @return 0 on success or a negative value if an error occurs.
360
 */
361
int
362
0
xmlSecOpenSSLKeyDataX509AdoptCrl(xmlSecKeyDataPtr data, X509_CRL* crl) {
363
0
    xmlSecOpenSSLX509DataCtxPtr ctx;
364
0
    xmlSecOpenSSLSizeT ret;
365
366
0
    xmlSecAssert2(xmlSecKeyDataCheckId(data, xmlSecOpenSSLKeyDataX509Id), -1);
367
0
    xmlSecAssert2(crl != NULL, -1);
368
369
0
    ctx = xmlSecOpenSSLX509DataGetCtx(data);
370
0
    xmlSecAssert2(ctx != NULL, -1);
371
372
0
    if(ctx->crlsList == NULL) {
373
0
        ctx->crlsList = sk_X509_CRL_new_null();
374
0
        if(ctx->crlsList == NULL) {
375
0
            xmlSecOpenSSLError("sk_X509_CRL_new_null", xmlSecKeyDataGetName(data));
376
0
            return(-1);
377
0
        }
378
0
    }
379
380
0
    ret = sk_X509_CRL_push(ctx->crlsList, crl);
381
0
    if(ret <= 0) {
382
0
        xmlSecOpenSSLError("sk_X509_CRL_push", xmlSecKeyDataGetName(data));
383
0
        return(-1);
384
0
    }
385
386
0
    return(0);
387
0
}
388
389
/**
390
 * @brief Gets a CRL from X509 key data.
391
 * @param data the pointer to X509 key data.
392
 * @param pos the desired CRL position, must be less than the number of CRLs
393
 * in @p data (see xmlSecOpenSSLKeyDataX509GetCrlsSize).
394
 * @return a borrowed pointer to the CRL; the caller must NOT free it.
395
 */
396
X509_CRL*
397
0
xmlSecOpenSSLKeyDataX509GetCrl(xmlSecKeyDataPtr data, xmlSecSize pos) {
398
0
    xmlSecOpenSSLX509DataCtxPtr ctx;
399
0
    xmlSecOpenSSLSizeT iPos;
400
401
0
    xmlSecAssert2(xmlSecKeyDataCheckId(data, xmlSecOpenSSLKeyDataX509Id), NULL);
402
403
0
    ctx = xmlSecOpenSSLX509DataGetCtx(data);
404
0
    xmlSecAssert2(ctx != NULL, NULL);
405
406
0
    xmlSecAssert2(ctx->crlsList != NULL, NULL);
407
408
0
    XMLSEC_OPENSSL_SAFE_CAST_SIZE_TO_SIZE_T(pos, iPos, return(NULL), NULL);
409
0
    xmlSecAssert2(iPos < sk_X509_CRL_num(ctx->crlsList), NULL);
410
0
    return(sk_X509_CRL_value(ctx->crlsList, iPos));
411
0
}
412
413
/**
414
 * @brief Gets the number of CRLs in @p data.
415
 * @param data the pointer to X509 key data.
416
 * @return the number of CRLs in @p data.
417
 */
418
xmlSecSize
419
0
xmlSecOpenSSLKeyDataX509GetCrlsSize(xmlSecKeyDataPtr data) {
420
0
    xmlSecOpenSSLX509DataCtxPtr ctx;
421
0
    xmlSecOpenSSLSizeT ret;
422
0
    xmlSecSize res;
423
424
0
    xmlSecAssert2(xmlSecKeyDataCheckId(data, xmlSecOpenSSLKeyDataX509Id), 0);
425
426
0
    ctx = xmlSecOpenSSLX509DataGetCtx(data);
427
0
    xmlSecAssert2(ctx != NULL, 0);
428
429
0
    if(ctx->crlsList == NULL) {
430
0
        return(0);
431
0
    }
432
433
0
    ret = sk_X509_CRL_num(ctx->crlsList);
434
0
    XMLSEC_OPENSSL_SAFE_CAST_SIZE_T_TO_SIZE(ret, res, return(0), NULL);
435
0
    return(res);
436
0
}
437
438
439
STACK_OF(X509)*
440
0
xmlSecOpenSSLKeyDataX509GetCerts(xmlSecKeyDataPtr data) {
441
0
    xmlSecOpenSSLX509DataCtxPtr ctx;
442
443
0
    xmlSecAssert2(xmlSecKeyDataCheckId(data, xmlSecOpenSSLKeyDataX509Id), NULL);
444
445
0
    ctx = xmlSecOpenSSLX509DataGetCtx(data);
446
0
    xmlSecAssert2(ctx != NULL, NULL);
447
448
0
    return(ctx->certsList);
449
0
}
450
451
STACK_OF(X509_CRL)*
452
0
xmlSecOpenSSLKeyDataX509GetCrls(xmlSecKeyDataPtr data) {
453
0
    xmlSecOpenSSLX509DataCtxPtr ctx;
454
455
0
    xmlSecAssert2(xmlSecKeyDataCheckId(data, xmlSecOpenSSLKeyDataX509Id), NULL);
456
457
0
    ctx = xmlSecOpenSSLX509DataGetCtx(data);
458
0
    xmlSecAssert2(ctx != NULL, NULL);
459
460
0
    return(ctx->crlsList);
461
0
}
462
463
static int
464
2.29k
xmlSecOpenSSLKeyDataX509Initialize(xmlSecKeyDataPtr data) {
465
2.29k
    xmlSecOpenSSLX509DataCtxPtr ctx;
466
467
2.29k
    xmlSecAssert2(xmlSecKeyDataCheckId(data, xmlSecOpenSSLKeyDataX509Id), -1);
468
469
2.29k
    ctx = xmlSecOpenSSLX509DataGetCtx(data);
470
2.29k
    xmlSecAssert2(ctx != NULL, -1);
471
472
2.29k
    memset(ctx, 0, sizeof(xmlSecOpenSSLX509DataCtx));
473
2.29k
    return(0);
474
2.29k
}
475
476
static void
477
2.29k
xmlSecOpenSSLKeyDataX509Finalize(xmlSecKeyDataPtr data) {
478
2.29k
    xmlSecOpenSSLX509DataCtxPtr ctx;
479
480
2.29k
    xmlSecAssert(xmlSecKeyDataCheckId(data, xmlSecOpenSSLKeyDataX509Id));
481
482
2.29k
    ctx = xmlSecOpenSSLX509DataGetCtx(data);
483
2.29k
    xmlSecAssert(ctx != NULL);
484
485
2.29k
    if(ctx->certsList != NULL) {
486
102
        sk_X509_pop_free(ctx->certsList, X509_free);
487
102
    }
488
2.29k
    if(ctx->crlsList != NULL) {
489
0
        sk_X509_CRL_pop_free(ctx->crlsList, X509_CRL_free);
490
0
    }
491
2.29k
    OPENSSL_cleanse(ctx, sizeof(xmlSecOpenSSLX509DataCtx));
492
2.29k
}
493
494
#if defined(XMLSEC_OPENSSL_NO_DEEP_COPY)
495
496
static STACK_OF(X509)*
497
xmlSecOpenSSLKeyDataX509DeepCopyCerts(STACK_OF(X509)* certsListSrc) {
498
    xmlSecOpenSSLSizeT size, ii;
499
    STACK_OF(X509)* certsListDst;
500
    X509* certSrc;
501
    X509* certDst;
502
    xmlSecOpenSSLSizeT ret;
503
504
    xmlSecAssert2(certsListSrc != NULL, NULL);
505
506
    certsListDst = sk_X509_new_null();
507
    if(certsListDst == NULL) {
508
        xmlSecOpenSSLError("sk_X509_new_null", NULL);
509
        return(NULL);
510
    }
511
    size = sk_X509_num(certsListSrc);
512
    for(ii = 0; ii < size; ++ii) {
513
        certSrc = sk_X509_value(certsListSrc, ii);
514
        if(certSrc == NULL) {
515
            continue;
516
        }
517
        certDst = X509_dup(certSrc);
518
        if(certDst == NULL) {
519
            xmlSecOpenSSLError("X509_dup", NULL);
520
            sk_X509_pop_free(certsListDst, X509_free);
521
            return(NULL);
522
        }
523
        ret = sk_X509_push(certsListDst, certDst);
524
        if(ret <= 0) {
525
            xmlSecOpenSSLError("sk_X509_push", NULL);
526
            X509_free(certDst);
527
            sk_X509_pop_free(certsListDst, X509_free);
528
            return(NULL);
529
        }
530
    }
531
    return(certsListDst);
532
}
533
534
static STACK_OF(X509_CRL)*
535
xmlSecOpenSSLKeyDataX509DeepCopyCrls(STACK_OF(X509_CRL)* crlsListSrc) {
536
    xmlSecOpenSSLSizeT size, ii;
537
    STACK_OF(X509_CRL)* crlsListDst;
538
    X509_CRL* crlSrc;
539
    X509_CRL* crlDst;
540
    xmlSecOpenSSLSizeT ret;
541
542
    xmlSecAssert2(crlsListSrc != NULL, NULL);
543
544
    crlsListDst = sk_X509_CRL_new_null();
545
    if(crlsListDst == NULL) {
546
        xmlSecOpenSSLError("sk_X509_CRL_new_null", NULL);
547
        return(NULL);
548
    }
549
    size = sk_X509_CRL_num(crlsListSrc);
550
    for(ii = 0; ii < size; ++ii) {
551
        crlSrc = sk_X509_CRL_value(crlsListSrc, ii);
552
        if(crlSrc == NULL) {
553
            continue;
554
        }
555
        crlDst = X509_CRL_dup(crlSrc);
556
        if(crlDst == NULL) {
557
            xmlSecOpenSSLError("X509_CRL_dup", NULL);
558
            sk_X509_CRL_pop_free(crlsListDst, X509_CRL_free);
559
            return(NULL);
560
        }
561
        ret = sk_X509_CRL_push(crlsListDst, crlDst);
562
        if(ret <= 0) {
563
            xmlSecOpenSSLError("sk_X509_CRL_push", NULL);
564
            X509_CRL_free(crlDst);
565
            sk_X509_CRL_pop_free(crlsListDst, X509_CRL_free);
566
            return(NULL);
567
        }
568
    }
569
    return(crlsListDst);
570
}
571
572
#endif /* defined(XMLSEC_OPENSSL_NO_DEEP_COPY) */
573
574
static int
575
0
xmlSecOpenSSLKeyDataX509Duplicate(xmlSecKeyDataPtr dst, xmlSecKeyDataPtr src) {
576
0
    xmlSecOpenSSLX509DataCtxPtr ctxSrc, ctxDst;
577
578
0
    xmlSecAssert2(xmlSecKeyDataCheckId(dst, xmlSecOpenSSLKeyDataX509Id), -1);
579
0
    xmlSecAssert2(xmlSecKeyDataCheckId(src, xmlSecOpenSSLKeyDataX509Id), -1);
580
581
0
    ctxSrc = xmlSecOpenSSLX509DataGetCtx(src);
582
0
    xmlSecAssert2(ctxSrc != NULL, -1);
583
584
    /* dst should not have any data */
585
0
    ctxDst = xmlSecOpenSSLX509DataGetCtx(dst);
586
0
    xmlSecAssert2(ctxDst != NULL, -1);
587
0
    xmlSecAssert2(ctxDst->keyCert == NULL, -1);
588
0
    xmlSecAssert2(ctxDst->certsList == NULL, -1);
589
0
    xmlSecAssert2(ctxDst->crlsList == NULL, -1);
590
591
    /* certs */
592
0
    if(ctxSrc->certsList != NULL) {
593
0
#ifndef XMLSEC_OPENSSL_NO_DEEP_COPY
594
0
#if !defined(XMLSEC_OPENSSL_API_111)
595
0
        ctxDst->certsList = sk_X509_deep_copy(ctxSrc->certsList, X509_dup, X509_free);
596
#else  /* !defined(XMLSEC_OPENSSL_API_111) */
597
        ctxDst->certsList = sk_X509_deep_copy(ctxSrc->certsList, (sk_X509_copyfunc)X509_dup, X509_free);
598
#endif /* !defined(XMLSEC_OPENSSL_API_111) */
599
0
        if(ctxDst->certsList == NULL) {
600
0
            xmlSecOpenSSLError("sk_X509_deep_copy", xmlSecKeyDataGetName(dst));
601
0
            return(-1);
602
0
        }
603
#else /* XMLSEC_OPENSSL_NO_DEEP_COPY */
604
        ctxDst->certsList = xmlSecOpenSSLKeyDataX509DeepCopyCerts(ctxSrc->certsList);
605
        if(ctxDst->certsList == NULL) {
606
            xmlSecOpenSSLError("xmlSecOpenSSLKeyDataX509DeepCopyCerts", xmlSecKeyDataGetName(dst));
607
            return(-1);
608
        }
609
#endif /* XMLSEC_OPENSSL_NO_DEEP_COPY */
610
0
    }
611
612
    /* crls */
613
0
    if(ctxSrc->crlsList != NULL) {
614
0
#ifndef XMLSEC_OPENSSL_NO_DEEP_COPY
615
0
#if !defined(XMLSEC_OPENSSL_API_111)
616
0
        ctxDst->crlsList = sk_X509_CRL_deep_copy(ctxSrc->crlsList, X509_CRL_dup, X509_CRL_free);
617
#else  /* !defined(XMLSEC_OPENSSL_API_111) */
618
        ctxDst->crlsList = sk_X509_CRL_deep_copy(ctxSrc->crlsList, (sk_X509_CRL_copyfunc)X509_CRL_dup, X509_CRL_free);
619
#endif /* !defined(XMLSEC_OPENSSL_API_111) */
620
0
        if(ctxDst->crlsList == NULL) {
621
0
            xmlSecOpenSSLError("sk_X509_CRL_deep_copy", xmlSecKeyDataGetName(dst));
622
0
            return(-1);
623
0
        }
624
#else /* XMLSEC_OPENSSL_NO_DEEP_COPY */
625
        ctxDst->crlsList = xmlSecOpenSSLKeyDataX509DeepCopyCrls(ctxSrc->crlsList);
626
        if(ctxDst->crlsList == NULL) {
627
            xmlSecOpenSSLError("xmlSecOpenSSLKeyDataX509DeepCopyCrls", xmlSecKeyDataGetName(dst));
628
            return(-1);
629
        }
630
#endif /* XMLSEC_OPENSSL_NO_DEEP_COPY */
631
0
    }
632
633
    /* keyCert: should be in the same position in certsList after copy */
634
0
    if(ctxSrc->keyCert != NULL) {
635
0
        xmlSecOpenSSLSizeT ii, len;
636
637
0
        len = sk_X509_num(ctxSrc->certsList);
638
0
        xmlSecAssert2(len == sk_X509_num(ctxDst->certsList), -1);
639
0
        for(ii = 0; ii < len; ++ii) {
640
0
            X509* cert = sk_X509_value(ctxSrc->certsList, ii);
641
0
            if(cert == ctxSrc->keyCert) {
642
0
                ctxDst->keyCert = sk_X509_value(ctxDst->certsList, ii);
643
0
                break;
644
0
            }
645
0
        }
646
        /* just to double check */
647
0
        xmlSecAssert2(ctxDst->keyCert != NULL, -1);
648
0
        xmlSecAssert2(X509_cmp(ctxSrc->keyCert, ctxDst->keyCert) == 0, -1);
649
0
    }
650
651
    /* done */
652
0
    return(0);
653
0
}
654
655
656
static int
657
2.29k
xmlSecOpenSSLKeyDataX509XmlRead(xmlSecKeyDataId id, xmlSecKeyPtr key, xmlNodePtr node, xmlSecKeyInfoCtxPtr keyInfoCtx) {
658
2.29k
    xmlSecKeyDataPtr data;
659
2.29k
    int ret;
660
661
2.29k
    xmlSecAssert2(id == xmlSecOpenSSLKeyDataX509Id, -1);
662
2.29k
    xmlSecAssert2(key != NULL, -1);
663
664
2.29k
    data = xmlSecKeyDataCreate(xmlSecOpenSSLKeyDataX509Id);
665
2.29k
    if(data == NULL) {
666
0
        xmlSecInternalError("xmlSecKeyDataCreate(xmlSecOpenSSLKeyDataX509Id)", xmlSecKeyDataKlassGetName(id));
667
0
        return(-1);
668
0
    }
669
670
2.29k
    ret = xmlSecKeyDataX509XmlRead(key, data, node, keyInfoCtx, xmlSecOpenSSLKeyDataX509Read);
671
2.29k
    if(ret < 0) {
672
500
        xmlSecInternalError("xmlSecKeyDataX509XmlRead", xmlSecKeyDataKlassGetName(id));
673
500
        xmlSecKeyDataDestroy(data);
674
500
        return(-1);
675
500
    }
676
677
    /* did we find the key already? */
678
1.79k
    if(xmlSecKeyGetValue(key) != NULL) {
679
0
        xmlSecKeyDataDestroy(data);
680
0
        return(0);
681
0
    }
682
683
    /* if not, then try to extract the key from certificates */
684
1.79k
    ret = xmlSecOpenSSLVerifyAndAdoptX509KeyData(key, data, keyInfoCtx);
685
1.79k
    if(ret < 0) {
686
0
        xmlSecInternalError("xmlSecOpenSSLVerifyAndAdoptX509KeyData", xmlSecKeyDataKlassGetName(id));
687
0
        xmlSecKeyDataDestroy(data);
688
0
        return(-1);
689
1.79k
    } else if(ret != 1) {
690
        /* no errors but key was not found and data was not adopted */
691
1.79k
        xmlSecKeyDataDestroy(data);
692
1.79k
        return(0);
693
1.79k
    }
694
0
    data = NULL; /* owned by key now */
695
696
    /* success */
697
0
    return(0);
698
1.79k
}
699
700
static int
701
xmlSecOpenSSLKeyDataX509XmlWrite(xmlSecKeyDataId id, xmlSecKeyPtr key,
702
0
                                xmlNodePtr node, xmlSecKeyInfoCtxPtr keyInfoCtx) {
703
0
    xmlSecKeyDataPtr data;
704
0
    xmlSecOpenSSLKeyDataX509Context context;
705
0
    int ret;
706
707
0
    xmlSecAssert2(id == xmlSecOpenSSLKeyDataX509Id, -1);
708
0
    xmlSecAssert2(key != NULL, -1);
709
710
    /* get x509 data */
711
0
    data = xmlSecKeyGetData(key, id);
712
0
    if(data == NULL) {
713
        /* no x509 data in the key */
714
0
        return(0);
715
0
    }
716
717
    /* setup context */
718
0
    context.crtPos = context.crlPos = 0;
719
0
    context.crtSize = xmlSecOpenSSLKeyDataX509GetCertsSize(data);
720
0
    context.crlSize = xmlSecOpenSSLKeyDataX509GetCrlsSize(data);
721
722
0
    ret = xmlSecKeyDataX509XmlWrite(data, node, keyInfoCtx,
723
0
        xmlSecBase64GetDefaultLineSize(), 1, /* add line breaks */
724
0
        xmlSecOpenSSLKeyDataX509Write, &context);
725
0
    if(ret < 0) {
726
0
        xmlSecInternalError3("xmlSecKeyDataX509XmlWrite",
727
0
            xmlSecKeyDataKlassGetName(id),
728
0
            "crtSize=" XMLSEC_SIZE_FMT "; crlSize=" XMLSEC_SIZE_FMT,
729
0
            context.crtSize, context.crlSize);
730
0
        return(-1);
731
0
    }
732
733
    /* success */
734
0
    return(0);
735
0
}
736
737
static void
738
0
xmlSecOpenSSLKeyDataX509DebugDump(xmlSecKeyDataPtr data, FILE* output) {
739
0
    X509* cert;
740
0
    xmlSecSize size, pos;
741
742
0
    xmlSecAssert(xmlSecKeyDataCheckId(data, xmlSecOpenSSLKeyDataX509Id));
743
0
    xmlSecAssert(output != NULL);
744
745
0
    fprintf(output, "=== X509 Data:\n");
746
0
    cert = xmlSecOpenSSLKeyDataX509GetKeyCert(data);
747
0
    if(cert != NULL) {
748
0
        fprintf(output, "==== Key Certificate:\n");
749
0
        xmlSecOpenSSLX509CertDebugDump(cert, output);
750
0
    }
751
752
0
    size = xmlSecOpenSSLKeyDataX509GetCertsSize(data);
753
0
    for(pos = 0; pos < size; ++pos) {
754
0
        cert = xmlSecOpenSSLKeyDataX509GetCert(data, pos);
755
0
        if(cert == NULL) {
756
0
            xmlSecInternalError2("xmlSecOpenSSLKeyDataX509GetCert",
757
0
                                 xmlSecKeyDataGetName(data),
758
0
                                 "pos=" XMLSEC_SIZE_FMT, pos);
759
0
            return;
760
0
        }
761
0
        fprintf(output, "==== Certificate:\n");
762
0
        xmlSecOpenSSLX509CertDebugDump(cert, output);
763
0
    }
764
765
    /* we don't print out crls */
766
0
}
767
768
static void
769
0
xmlSecOpenSSLKeyDataX509DebugXmlDump(xmlSecKeyDataPtr data, FILE* output) {
770
0
    X509* cert;
771
0
    xmlSecSize size, pos;
772
773
0
    xmlSecAssert(xmlSecKeyDataCheckId(data, xmlSecOpenSSLKeyDataX509Id));
774
0
    xmlSecAssert(output != NULL);
775
776
0
    fprintf(output, "<X509Data>\n");
777
0
    cert = xmlSecOpenSSLKeyDataX509GetKeyCert(data);
778
0
    if(cert != NULL) {
779
0
        fprintf(output, "<KeyCertificate>\n");
780
0
        xmlSecOpenSSLX509CertDebugXmlDump(cert, output);
781
0
        fprintf(output, "</KeyCertificate>\n");
782
0
    }
783
784
0
    size = xmlSecOpenSSLKeyDataX509GetCertsSize(data);
785
0
    for(pos = 0; pos < size; ++pos) {
786
0
        cert = xmlSecOpenSSLKeyDataX509GetCert(data, pos);
787
0
        if(cert == NULL) {
788
0
            xmlSecInternalError2("xmlSecOpenSSLKeyDataX509GetCert",
789
0
                                 xmlSecKeyDataGetName(data),
790
0
                                 "pos=" XMLSEC_SIZE_FMT, pos);
791
0
            break;
792
0
        }
793
0
        fprintf(output, "<Certificate>\n");
794
0
        xmlSecOpenSSLX509CertDebugXmlDump(cert, output);
795
0
        fprintf(output, "</Certificate>\n");
796
0
    }
797
798
    /* we don't print out crls */
799
0
    fprintf(output, "</X509Data>\n");
800
0
}
801
802
/* xmlSecKeyDataX509Read: 0 on success and a negative value otherwise */
803
static int
804
xmlSecOpenSSLKeyDataX509Read(xmlSecKeyDataPtr data, xmlSecKeyX509DataValuePtr x509Value,
805
    xmlSecKeysMngrPtr keysMngr, unsigned int flags
806
12.8k
) {
807
12.8k
    X509* cert = NULL;
808
12.8k
    X509_CRL* crl = NULL;
809
12.8k
    int ret;
810
12.8k
    int res = -1;
811
812
12.8k
    xmlSecAssert2(data != NULL, -1);
813
12.8k
    xmlSecAssert2(xmlSecKeyDataCheckId(data, xmlSecOpenSSLKeyDataX509Id), -1);
814
12.8k
    xmlSecAssert2(x509Value != NULL, -1);
815
12.8k
    xmlSecAssert2(keysMngr != NULL, -1);
816
817
    /* read CERT or CRL */
818
12.8k
    if(xmlSecBufferGetSize(&(x509Value->cert)) > 0) {
819
314
        cert = xmlSecOpenSSLX509CertDerRead(xmlSecBufferGetData(&(x509Value->cert)),
820
314
            xmlSecBufferGetSize(&(x509Value->cert)));
821
314
        if(cert == NULL) {
822
130
            xmlSecInternalError("xmlSecOpenSSLX509CertDerRead", xmlSecKeyDataGetName(data));
823
130
            goto done;
824
130
        }
825
314
    }
826
12.7k
    if(xmlSecBufferGetSize(&(x509Value->crl)) > 0) {
827
0
        crl = xmlSecOpenSSLX509CrlDerRead(xmlSecBufferGetData(&(x509Value->crl)),
828
0
            xmlSecBufferGetSize(&(x509Value->crl)));
829
0
        if(crl == NULL) {
830
0
            xmlSecInternalError("xmlSecOpenSSLX509CrlDerRead", xmlSecKeyDataGetName(data));
831
0
            goto done;
832
0
        }
833
0
    }
834
835
    /* if there is no cert in the X509Data node then try to find one */
836
12.7k
    if(cert == NULL) {
837
12.5k
        xmlSecKeyDataStorePtr x509Store;
838
12.5k
        X509* storeCert = NULL;
839
12.5k
        int stopOnUnknownCert = 0;
840
841
12.5k
        x509Store = xmlSecKeysMngrGetDataStore(keysMngr, xmlSecOpenSSLX509StoreId);
842
12.5k
        if (x509Store == NULL) {
843
0
            xmlSecInternalError("xmlSecKeysMngrGetDataStore", xmlSecKeyDataGetName(data));
844
0
            goto done;
845
0
        }
846
847
        /* determine what to do */
848
12.5k
        if((flags & XMLSEC_KEYINFO_FLAGS_X509DATA_STOP_ON_UNKNOWN_CERT) != 0) {
849
0
            stopOnUnknownCert = 1;
850
0
        }
851
12.5k
        storeCert = xmlSecOpenSSLX509StoreFindCertByValue(x509Store, x509Value);
852
12.5k
        if((storeCert == NULL) && (stopOnUnknownCert != 0)) {
853
0
            xmlSecOtherError(XMLSEC_ERRORS_R_CERT_NOT_FOUND, xmlSecKeyDataGetName(data), "cert lookup");
854
0
            goto done;
855
0
        }
856
        /* if we found cert in a store, then duplicate it for key data */
857
12.5k
        if(storeCert != NULL) {
858
0
            cert = X509_dup(storeCert);
859
0
            if(cert == NULL) {
860
0
                xmlSecOpenSSLError("X509_dup", xmlSecKeyDataGetName(data));
861
0
                goto done;
862
0
            }
863
0
        }
864
12.5k
    }
865
866
    /* if we found a cert or a crl, then add it to the data */
867
12.7k
    if(cert != NULL) {
868
184
        ret = xmlSecOpenSSLKeyDataX509AdoptCert(data, cert);
869
184
        if(ret < 0) {
870
0
            xmlSecInternalError("xmlSecOpenSSLKeyDataX509AdoptCert", xmlSecKeyDataGetName(data));
871
0
            goto done;
872
0
        }
873
184
        cert = NULL; /* owned by data now */
874
184
    }
875
12.7k
    if(crl != NULL) {
876
0
        ret = xmlSecOpenSSLKeyDataX509AdoptCrl(data, crl);
877
0
        if(ret < 0) {
878
0
            xmlSecInternalError("xmlSecOpenSSLKeyDataX509AdoptCrl", xmlSecKeyDataGetName(data));
879
0
            goto done;
880
0
        }
881
0
        crl = NULL; /* owned by data now */
882
0
    }
883
884
    /* success */
885
12.7k
    res = 0;
886
887
12.8k
done:
888
    /* cleanup */
889
12.8k
    if(cert != NULL) {
890
0
        X509_free(cert);
891
0
    }
892
12.8k
    if(crl != NULL) {
893
0
        X509_CRL_free(crl);
894
0
    }
895
12.8k
    return(res);
896
12.7k
}
897
898
static int
899
0
xmlSecOpenSSLX509CertDerWrite(X509* cert, xmlSecBufferPtr buf) {
900
0
    BIO *mem = NULL;
901
0
    xmlSecByte *data = NULL;
902
0
    xmlSecSize size;
903
0
    long len;
904
0
    int ret;
905
0
    int res = -1;
906
907
0
    xmlSecAssert2(cert != NULL, -1);
908
0
    xmlSecAssert2(buf != NULL, -1);
909
910
0
    mem = xmlSecOpenSSLCreateMemBio();
911
0
    if(mem == NULL) {
912
0
        xmlSecInternalError("xmlSecOpenSSLCreateMemBio", NULL);
913
0
        goto done;
914
0
    }
915
916
0
    ret = i2d_X509_bio(mem, cert);
917
0
    if(ret != 1) {
918
0
        xmlSecOpenSSLError("i2d_X509_bio", NULL);
919
0
        goto done;
920
0
    }
921
0
    ret = BIO_flush(mem);
922
0
    if(ret != 1) {
923
0
        xmlSecOpenSSLError("BIO_flush", NULL);
924
0
        goto done;
925
0
    }
926
927
0
    len = BIO_get_mem_data(mem, (char**)&data);
928
0
    if((len <= 0) || (data == NULL)) {
929
0
        xmlSecOpenSSLError("BIO_get_mem_data", NULL);
930
0
        goto done;
931
0
    }
932
0
    XMLSEC_SAFE_CAST_LONG_TO_SIZE(len, size, goto done, NULL);
933
934
0
    ret = xmlSecBufferSetData(buf, data, size);
935
0
    if(ret < 0) {
936
0
        xmlSecInternalError("xmlSecBufferSetData", NULL);
937
0
        goto done;
938
0
    }
939
940
    /* success */
941
0
    res = 0;
942
943
0
done:
944
0
    if(mem != NULL) {
945
0
        BIO_free_all(mem);
946
0
    }
947
0
    return(res);
948
0
}
949
950
static int
951
0
xmlSecOpenSSLX509CrlDerWrite(X509_CRL* crl, xmlSecBufferPtr buf) {
952
0
    BIO *mem = NULL;
953
0
    xmlSecByte *data = NULL;
954
0
    xmlSecSize size;
955
0
    long len;
956
0
    int ret;
957
0
    int res = -1;
958
959
0
    xmlSecAssert2(crl != NULL, -1);
960
0
    xmlSecAssert2(buf != NULL, -1);
961
962
0
    mem = xmlSecOpenSSLCreateMemBio();
963
0
    if(mem == NULL) {
964
0
        xmlSecInternalError("xmlSecOpenSSLCreateMemBio", NULL);
965
0
        goto done;
966
0
    }
967
968
0
    ret = i2d_X509_CRL_bio(mem, crl);
969
0
    if(ret != 1) {
970
0
        xmlSecOpenSSLError("i2d_X509_CRL_bio", NULL);
971
0
        goto done;
972
0
    }
973
0
    ret = BIO_flush(mem);
974
0
    if(ret != 1) {
975
0
        xmlSecOpenSSLError("BIO_flush", NULL);
976
0
        goto done;
977
0
    }
978
979
0
    len = BIO_get_mem_data(mem, (char**)&data);
980
0
    if((len <= 0) || (data == NULL)) {
981
0
        xmlSecOpenSSLError("BIO_get_mem_data", NULL);
982
0
        goto done;
983
0
    }
984
0
    XMLSEC_SAFE_CAST_LONG_TO_SIZE(len, size, goto done, NULL);
985
986
0
    ret = xmlSecBufferSetData(buf, data, size);
987
0
    if(ret < 0) {
988
0
        xmlSecInternalError2("xmlSecBufferSetData", NULL,
989
0
            "size=" XMLSEC_SIZE_FMT, size);
990
0
        goto done;
991
0
    }
992
993
    /* success */
994
0
    res = 0;
995
996
0
done:
997
0
    if(mem != NULL) {
998
0
        BIO_free_all(mem);
999
0
    }
1000
0
    return(res);
1001
0
}
1002
1003
static int
1004
0
xmlSecOpenSSLX509SKIWrite(X509* cert, xmlSecBufferPtr buf) {
1005
0
    XMLSEC_OPENSSL400_CONST X509_EXTENSION *ext;
1006
0
    ASN1_OCTET_STRING *keyId = NULL;
1007
0
    const xmlSecByte* keyIdData;
1008
0
    int index, keyIdLen;
1009
0
    xmlSecSize keyIdSize;
1010
0
    int ret;
1011
0
    int res = -1;
1012
1013
0
    xmlSecAssert2(cert != NULL, -1);
1014
0
    xmlSecAssert2(buf != NULL, -1);
1015
1016
0
    index = X509_get_ext_by_NID(cert, NID_subject_key_identifier, -1);
1017
0
    if (index < 0) {
1018
0
        xmlSecInvalidDataError("certificate without SubjectKeyIdentifier extension", NULL);
1019
0
        goto done;
1020
0
    }
1021
1022
0
    ext = X509_get_ext(cert, index);
1023
0
    if (ext == NULL) {
1024
0
        xmlSecOpenSSLError("X509_get_ext", NULL);
1025
0
        goto done;
1026
0
    }
1027
1028
0
    keyId = (ASN1_OCTET_STRING *)X509V3_EXT_d2i(ext);
1029
0
    if (keyId == NULL) {
1030
0
        xmlSecOpenSSLError("X509V3_EXT_d2i", NULL);
1031
0
        goto done;
1032
0
    }
1033
1034
0
    keyIdData = ASN1_STRING_get0_data(keyId);
1035
0
    if(keyIdData == NULL) {
1036
0
        xmlSecOpenSSLError("ASN1_STRING_get0_data", NULL);
1037
0
        goto done;
1038
0
    }
1039
0
    keyIdLen = ASN1_STRING_length(keyId);
1040
0
    if(keyIdLen <= 0) {
1041
0
        xmlSecOpenSSLError("ASN1_STRING_length", NULL);
1042
0
        goto done;
1043
0
    }
1044
0
    XMLSEC_SAFE_CAST_INT_TO_SIZE(keyIdLen, keyIdSize, goto done, NULL);
1045
1046
0
    ret = xmlSecBufferSetData(buf, keyIdData, keyIdSize);
1047
0
    if(ret < 0) {
1048
0
        xmlSecInternalError2("xmlSecBufferSetData", NULL,
1049
0
            "keyIdSize=" XMLSEC_SIZE_FMT, keyIdSize);
1050
0
        goto done;
1051
0
    }
1052
1053
    /* success */
1054
0
    res = 0;
1055
1056
1057
0
done:
1058
0
    if(keyId != NULL) {
1059
0
        ASN1_OCTET_STRING_free(keyId);
1060
0
    }
1061
0
    return(res);
1062
0
}
1063
1064
const EVP_MD *
1065
1.44k
xmlSecOpenSSLX509GetDigestFromAlgorithm(const xmlChar* href) {
1066
    /* use SHA256 by default */
1067
1.44k
    if(href == NULL) {
1068
0
#ifndef XMLSEC_NO_SHA256
1069
0
        return(EVP_sha256());
1070
#else  /* XMLSEC_NO_SHA256 */
1071
        xmlSecOtherError2(XMLSEC_ERRORS_R_INVALID_ALGORITHM, NULL,
1072
            "SHA256 is disabled; href=%s", xmlSecErrorsSafeString(href));
1073
        return(NULL);
1074
#endif /* XMLSEC_NO_SHA256 */
1075
0
    } else
1076
1077
1.44k
#ifndef XMLSEC_NO_SHA1
1078
1.44k
    if(xmlStrcmp(href, xmlSecHrefSha1) == 0) {
1079
64
        return(EVP_sha1());
1080
64
    } else
1081
1.38k
#endif /* XMLSEC_NO_SHA1 */
1082
1083
1.38k
#ifndef XMLSEC_NO_SHA224
1084
1.38k
    if(xmlStrcmp(href, xmlSecHrefSha224) == 0) {
1085
28
        return(EVP_sha224());
1086
28
    } else
1087
1.35k
#endif /* XMLSEC_NO_SHA224 */
1088
1089
1.35k
#ifndef XMLSEC_NO_SHA256
1090
1.35k
    if(xmlStrcmp(href, xmlSecHrefSha256) == 0) {
1091
24
        return(EVP_sha256());
1092
24
    } else
1093
1.32k
#endif /* XMLSEC_NO_SHA256 */
1094
1095
1.32k
#ifndef XMLSEC_NO_SHA384
1096
1.32k
    if(xmlStrcmp(href, xmlSecHrefSha384) == 0) {
1097
28
        return(EVP_sha384());
1098
28
    } else
1099
1.30k
#endif /* XMLSEC_NO_SHA384 */
1100
1101
1.30k
#ifndef XMLSEC_NO_SHA512
1102
1.30k
    if(xmlStrcmp(href, xmlSecHrefSha512) == 0) {
1103
72
        return(EVP_sha512());
1104
72
    } else
1105
1.22k
#endif /* XMLSEC_NO_SHA512 */
1106
1107
1.22k
#ifndef XMLSEC_NO_SHA3
1108
1.22k
    if(xmlStrcmp(href, xmlSecHrefSha3_224) == 0) {
1109
28
        return(EVP_sha3_224());
1110
1.20k
    } else if(xmlStrcmp(href, xmlSecHrefSha3_256) == 0) {
1111
12
        return(EVP_sha3_256());
1112
1.18k
    } else if(xmlStrcmp(href, xmlSecHrefSha3_384) == 0) {
1113
4
        return(EVP_sha3_384());
1114
1.18k
    } else if(xmlStrcmp(href, xmlSecHrefSha3_512) == 0) {
1115
380
        return(EVP_sha3_512());
1116
380
    } else
1117
1118
804
#endif /* XMLSEC_NO_SHA3 */
1119
804
    {
1120
804
        xmlSecOtherError2(XMLSEC_ERRORS_R_INVALID_ALGORITHM, NULL,
1121
804
            "href=%s", xmlSecErrorsSafeString(href));
1122
804
        return(NULL);
1123
804
    }
1124
1.44k
}
1125
1126
static int
1127
0
xmlSecOpenSSLX509DigestWrite(X509* cert, const xmlChar* algorithm, xmlSecBufferPtr buf) {
1128
0
    const EVP_MD * digest;
1129
0
    xmlSecByte md[EVP_MAX_MD_SIZE];
1130
0
    unsigned int len = 0;
1131
0
    int ret;
1132
1133
0
    xmlSecAssert2(cert != NULL, -1);
1134
0
    xmlSecAssert2(buf != NULL, -1);
1135
1136
1137
0
    digest = xmlSecOpenSSLX509GetDigestFromAlgorithm(algorithm);
1138
0
    if(digest == NULL) {
1139
0
        xmlSecInternalError("xmlSecOpenSSLX509GetDigestFromAlgorithm", NULL);
1140
0
        return(-1);
1141
0
    }
1142
1143
0
    ret = X509_digest(cert, digest, md, &len);
1144
0
    if((ret != 1) || (len <= 0)) {
1145
0
        xmlSecOpenSSLError("X509_digest", NULL);
1146
0
        return(-1);
1147
0
    }
1148
1149
0
    ret = xmlSecBufferSetData(buf, md, len);
1150
0
    if(ret < 0) {
1151
0
        xmlSecInternalError("xmlSecBufferSetData", NULL);
1152
0
        return(-1);
1153
0
    }
1154
1155
    /* success */
1156
0
    return(0);
1157
0
}
1158
1159
static xmlChar*
1160
0
xmlSecOpenSSLX509NameWrite(XMLSEC_OPENSSL400_CONST X509_NAME* nm) {
1161
0
    xmlChar* res = NULL;
1162
0
    BIO *mem = NULL;
1163
0
    xmlChar* buf = NULL;
1164
0
    xmlSecOpenSSLSizeT memBufSize;
1165
0
    xmlSecSize sizeBuf;
1166
0
    int lenBuf, lenRead;
1167
0
    int ret;
1168
1169
0
    xmlSecAssert2(nm != NULL, NULL);
1170
1171
0
    mem = xmlSecOpenSSLCreateMemBio();
1172
0
    if(mem == NULL) {
1173
0
        xmlSecInternalError("xmlSecOpenSSLCreateMemBio", NULL);
1174
0
        goto done;
1175
0
    }
1176
1177
    /*
1178
     * X509_NAME_print_ex() returns the number of characters written on
1179
     * success and -1 on failure; 0 is a valid result for an empty name
1180
     * (RFC 5280 section 4.1.2.6 permits an empty subject name)
1181
     */
1182
0
    if(X509_NAME_print_ex(mem, nm, 0, XN_FLAG_RFC2253) < 0) {
1183
0
        xmlSecOpenSSLError("X509_NAME_print_ex", NULL);
1184
0
        goto done;
1185
0
    }
1186
1187
0
    ret = BIO_flush(mem);
1188
0
    if(ret != 1) {
1189
0
        xmlSecOpenSSLError("BIO_flush", NULL);
1190
0
        goto done;
1191
0
    }
1192
1193
0
    memBufSize = BIO_pending(mem);
1194
0
#if !defined(XMLSEC_OPENSSL_IS_BORINGSSL) && !defined(XMLSEC_OPENSSL_IS_AWSLC)
1195
0
    if(memBufSize < 0) {
1196
0
        xmlSecOpenSSLError("BIO_pending", NULL);
1197
0
        goto done;
1198
0
    }
1199
0
#endif /* !defined(XMLSEC_OPENSSL_IS_BORINGSSL) && !defined(XMLSEC_OPENSSL_IS_AWSLC) */
1200
0
    XMLSEC_OPENSSL_SAFE_CAST_SIZE_T_TO_SIZE(memBufSize, sizeBuf, goto done, NULL);
1201
0
    XMLSEC_OPENSSL_SAFE_CAST_SIZE_T_TO_INT(memBufSize, lenBuf, goto done, NULL);
1202
1203
0
    buf = (xmlChar *)xmlMalloc(sizeBuf + 1);
1204
0
    if(buf == NULL) {
1205
0
        xmlSecMallocError(sizeBuf + 1, NULL);
1206
0
        goto done;
1207
0
    }
1208
0
    memset(buf, 0, sizeBuf + 1);
1209
1210
0
    if(lenBuf > 0) {
1211
        /*
1212
         * BIO_read() returns -1 for a zero-length request on an empty
1213
         * memory BIO, so the read must be skipped for an empty name
1214
         */
1215
0
        lenRead = BIO_read(mem, buf, lenBuf);
1216
0
        if(lenRead != lenBuf) {
1217
0
            xmlSecOpenSSLError("BIO_read", NULL);
1218
0
            goto done;
1219
0
        }
1220
0
    }
1221
1222
    /* success */
1223
0
    buf[sizeBuf] = '\0';
1224
0
    res = buf;
1225
0
    buf = NULL;
1226
1227
0
done:
1228
0
    if(buf != NULL) {
1229
0
        xmlFree(buf);
1230
0
    }
1231
0
    if(mem != NULL) {
1232
0
        BIO_free_all(mem);
1233
0
    }
1234
0
    return(res);
1235
0
}
1236
1237
static xmlChar*
1238
0
xmlSecOpenSSLASN1IntegerWrite(ASN1_INTEGER *asn1) {
1239
0
    xmlChar *res = NULL;
1240
0
    BIGNUM *bn;
1241
0
    char *p;
1242
1243
0
    xmlSecAssert2(asn1 != NULL, NULL);
1244
1245
0
    bn = ASN1_INTEGER_to_BN(asn1, NULL);
1246
0
    if(bn == NULL) {
1247
0
        xmlSecOpenSSLError("ASN1_INTEGER_to_BN", NULL);
1248
0
        return(NULL);
1249
0
    }
1250
1251
0
    p = BN_bn2dec(bn);
1252
0
    if (p == NULL) {
1253
0
        xmlSecOpenSSLError("BN_bn2dec", NULL);
1254
0
        BN_clear_free(bn);
1255
0
        return(NULL);
1256
0
    }
1257
0
    BN_clear_free(bn);
1258
0
    bn = NULL;
1259
1260
    /* OpenSSL and LibXML2 can have different memory callbacks, i.e.
1261
       when the data is allocated by OpenSSL it should be freed with the
1262
       OpenSSL method, not with the LibXML2 method.
1263
     */
1264
0
    res = xmlCharStrdup(p);
1265
0
    if(res == NULL) {
1266
0
        xmlSecStrdupError(BAD_CAST p, NULL);
1267
0
        OPENSSL_free(p);
1268
0
        return(NULL);
1269
0
    }
1270
0
    OPENSSL_free(p);
1271
0
    p = NULL;
1272
0
    return(res);
1273
0
}
1274
1275
/* xmlSecKeyDataX509Write: returns 1 on success, 0 if no more certs/crls are available,
1276
 * or a negative value if an error occurs.
1277
 */
1278
static int
1279
xmlSecOpenSSLKeyDataX509Write(xmlSecKeyDataPtr data,  xmlSecKeyX509DataValuePtr x509Value,
1280
0
                              int content, void* context) {
1281
0
    xmlSecOpenSSLKeyDataX509Context* ctx;
1282
0
    int ret;
1283
1284
0
    xmlSecAssert2(data != NULL, -1);
1285
0
    xmlSecAssert2(xmlSecKeyDataCheckId(data, xmlSecOpenSSLKeyDataX509Id), -1);
1286
0
    xmlSecAssert2(x509Value != NULL, -1);
1287
0
    xmlSecAssert2(context != NULL, -1);
1288
1289
0
    ctx = (xmlSecOpenSSLKeyDataX509Context*)context;
1290
0
    if(ctx->crtPos < ctx->crtSize) {
1291
        /* write cert */
1292
0
        X509* cert = xmlSecOpenSSLKeyDataX509GetCert(data, ctx->crtPos);
1293
0
        if(cert == NULL) {
1294
0
            xmlSecInternalError2("xmlSecOpenSSLKeyDataX509GetCert",
1295
0
                xmlSecKeyDataGetName(data),
1296
0
                "pos=" XMLSEC_SIZE_FMT, ctx->crtPos);
1297
0
            return(-1);
1298
0
        }
1299
0
        if (XMLSEC_X509DATA_HAS_EMPTY_NODE(content, XMLSEC_X509DATA_CERTIFICATE_NODE)) {
1300
0
            ret = xmlSecOpenSSLX509CertDerWrite(cert, &(x509Value->cert));
1301
0
            if(ret < 0) {
1302
0
                xmlSecInternalError2("xmlSecOpenSSLX509CertDerWrite",
1303
0
                    xmlSecKeyDataGetName(data),
1304
0
                    "pos=" XMLSEC_SIZE_FMT, ctx->crtPos);
1305
0
                return(-1);
1306
0
            }
1307
0
        }
1308
0
        if (XMLSEC_X509DATA_HAS_EMPTY_NODE(content, XMLSEC_X509DATA_SKI_NODE)) {
1309
0
            ret = xmlSecOpenSSLX509SKIWrite(cert, &(x509Value->ski));
1310
0
            if(ret < 0) {
1311
0
                xmlSecInternalError2("xmlSecOpenSSLX509SKIWrite",
1312
0
                    xmlSecKeyDataGetName(data),
1313
0
                    "pos=" XMLSEC_SIZE_FMT, ctx->crtPos);
1314
0
                return(-1);
1315
0
            }
1316
0
        }
1317
0
        if (XMLSEC_X509DATA_HAS_EMPTY_NODE(content, XMLSEC_X509DATA_SUBJECTNAME_NODE)) {
1318
0
            xmlSecAssert2(x509Value->subject == NULL, -1);
1319
1320
0
            x509Value->subject = xmlSecOpenSSLX509NameWrite(X509_get_subject_name(cert));
1321
0
            if(x509Value->subject == NULL) {
1322
0
                xmlSecInternalError2("xmlSecOpenSSLX509NameWrite(X509_get_subject_name)",
1323
0
                    xmlSecKeyDataGetName(data),
1324
0
                    "pos=" XMLSEC_SIZE_FMT, ctx->crtPos);
1325
0
                return(-1);
1326
0
            }
1327
0
        }
1328
0
        if (XMLSEC_X509DATA_HAS_EMPTY_NODE(content, XMLSEC_X509DATA_ISSUERSERIAL_NODE)) {
1329
0
            xmlSecAssert2(x509Value->issuerName == NULL, -1);
1330
0
            xmlSecAssert2(x509Value->issuerSerial == NULL, -1);
1331
1332
0
            x509Value->issuerName = xmlSecOpenSSLX509NameWrite(X509_get_issuer_name(cert));
1333
0
            if(x509Value->issuerName == NULL) {
1334
0
                xmlSecInternalError2("xmlSecOpenSSLX509NameWrite(X509_get_issuer_name)",
1335
0
                    xmlSecKeyDataGetName(data),
1336
0
                    "pos=" XMLSEC_SIZE_FMT, ctx->crtPos);
1337
0
                return(-1);
1338
0
            }
1339
0
            x509Value->issuerSerial = xmlSecOpenSSLASN1IntegerWrite(X509_get_serialNumber(cert));
1340
0
            if(x509Value->issuerSerial == NULL) {
1341
0
                xmlSecInternalError2("xmlSecOpenSSLASN1IntegerWrite(X509_get_serialNumber)",
1342
0
                    xmlSecKeyDataGetName(data),
1343
0
                    "pos=" XMLSEC_SIZE_FMT, ctx->crtPos);
1344
0
                return(-1);
1345
0
            }
1346
0
        }
1347
0
        if((XMLSEC_X509DATA_HAS_EMPTY_NODE(content, XMLSEC_X509DATA_DIGEST_NODE)) && (x509Value->digestAlgorithm != NULL)) {
1348
0
            ret = xmlSecOpenSSLX509DigestWrite(cert, x509Value->digestAlgorithm, &(x509Value->digest));
1349
0
            if(ret < 0) {
1350
0
                xmlSecInternalError2("xmlSecOpenSSLX509DigestWrite",
1351
0
                    xmlSecKeyDataGetName(data),
1352
0
                    "pos=" XMLSEC_SIZE_FMT, ctx->crtPos);
1353
0
                return(-1);
1354
0
            }
1355
0
        }
1356
0
        ++ctx->crtPos;
1357
0
    } else if(ctx->crlPos < ctx->crlSize) {
1358
        /* write crl */
1359
0
        X509_CRL* crl = xmlSecOpenSSLKeyDataX509GetCrl(data, ctx->crlPos);
1360
0
        if(crl == NULL) {
1361
0
            xmlSecInternalError2("xmlSecOpenSSLKeyDataX509GetCrl",
1362
0
                xmlSecKeyDataGetName(data),
1363
0
                "pos=" XMLSEC_SIZE_FMT, ctx->crlPos);
1364
0
            return(-1);
1365
0
        }
1366
1367
0
        if (XMLSEC_X509DATA_HAS_EMPTY_NODE(content, XMLSEC_X509DATA_CRL_NODE)) {
1368
0
            ret = xmlSecOpenSSLX509CrlDerWrite(crl, &(x509Value->crl));
1369
0
            if(ret < 0) {
1370
0
                xmlSecInternalError2("xmlSecOpenSSLX509CrlDerWrite",
1371
0
                    xmlSecKeyDataGetName(data),
1372
0
                    "pos=" XMLSEC_SIZE_FMT, ctx->crlPos);
1373
0
                return(-1);
1374
0
            }
1375
0
        }
1376
0
        ++ctx->crlPos;
1377
0
    } else {
1378
        /* no more certs or crls */
1379
0
        return(0);
1380
0
    }
1381
1382
    /* success */
1383
0
    return(1);
1384
0
}
1385
1386
1387
#ifdef HAVE_TIMEGM
1388
1389
/* easy case */
1390
extern time_t timegm (struct tm *tm);
1391
1392
#elif !defined(XMLSEC_WINDOWS)
1393
1394
/* Absolutely not the best way but it's the only ANSI compatible way I know.
1395
 * If your system has a native struct tm --> GMT time_t conversion function
1396
 * (like timegm) use it instead.
1397
 */
1398
static time_t
1399
0
my_timegm(struct tm *t) {
1400
0
    time_t tl, tb;
1401
0
    struct tm *tg;
1402
1403
0
    tl = mktime (t);
1404
0
    if(tl == -1) {
1405
0
        t->tm_hour--;
1406
0
        tl = mktime (t);
1407
0
        if (tl == -1) {
1408
0
            return (-1);
1409
0
        }
1410
0
        tl += 3600;
1411
0
    }
1412
0
    tg = gmtime (&tl);
1413
0
    if(tg == NULL) {
1414
0
        return (-1);
1415
0
    }
1416
0
    tg->tm_isdst = 0;
1417
0
    tb = mktime (tg);
1418
0
    if (tb == -1) {
1419
0
        tg->tm_hour--;
1420
0
        tb = mktime (tg);
1421
0
        if (tb == -1) {
1422
0
            return (-1);
1423
0
        }
1424
0
        tb += 3600;
1425
0
    }
1426
0
    return (tl - (tb - tl));
1427
0
}
1428
1429
0
#define timegm(tm) my_timegm(tm)
1430
1431
#elif defined(_MSC_VER)
1432
1433
/* Windows build with MSVC */
1434
static time_t
1435
my_timegm(struct tm *t) {
1436
    long seconds = 0;
1437
    time_t utcTime;
1438
1439
    if(_get_timezone(&seconds) != 0) {
1440
        return(-1);
1441
    }
1442
    utcTime = mktime(t);
1443
    if(utcTime == (time_t)-1) {
1444
        return((time_t)-1);
1445
    }
1446
    return (utcTime - seconds);
1447
}
1448
#define timegm(tm) my_timegm(tm)
1449
1450
#else  /* defined(_MSC_VER) */
1451
1452
/* Windows build with MinGW, Cygwin, etc */
1453
static time_t
1454
my_timegm(struct tm *t) {
1455
    time_t utcTime;
1456
1457
    utcTime = mktime(t);
1458
    if(utcTime == (time_t)-1) {
1459
        return((time_t)-1);
1460
    }
1461
    return (utcTime - _timezone);
1462
}
1463
#define timegm(tm) my_timegm(tm)
1464
1465
#endif /* HAVE_TIMEGM */
1466
1467
#ifndef XMLSEC_OPENSSL_NO_ASN1_TIME_TO_TM
1468
1469
int
1470
0
xmlSecOpenSSLX509Asn1TimeToTime(const ASN1_TIME * t, time_t * res) {
1471
0
    struct tm tm;
1472
0
    int ret;
1473
1474
0
    xmlSecAssert2(t != NULL, -1);
1475
0
    xmlSecAssert2(res != NULL, -1);
1476
1477
0
    if(!ASN1_TIME_check(t)) {
1478
0
        xmlSecOpenSSLError("ASN1_TIME_check", NULL);
1479
0
        return(-1);
1480
0
    }
1481
1482
0
    memset(&tm, 0, sizeof(tm));
1483
0
    ret = ASN1_TIME_to_tm(t, &tm);
1484
0
    if(ret != 1) {
1485
0
        xmlSecOpenSSLError("ASN1_TIME_to_tm", NULL);
1486
0
        return(-1);
1487
0
    }
1488
1489
0
    (*res) = timegm(&tm);
1490
0
    if((*res) == (time_t)-1) {
1491
        /*
1492
         * timegm() returns (time_t)-1 on failure. A (time_t)-1 is also a valid
1493
         * time (1969-12-31 23:59:59 UTC), but a certificate date is never in
1494
         * 1969, so treat it as a conversion error.
1495
         */
1496
0
        xmlSecOpenSSLError("timegm", NULL);
1497
0
        return(-1);
1498
0
    }
1499
0
    return (0);
1500
0
}
1501
1502
#else  /* XMLSEC_OPENSSL_NO_ASN1_TIME_TO_TM */
1503
1504
int
1505
xmlSecOpenSSLX509Asn1TimeToTime(const ASN1_TIME * t, time_t * res) {
1506
    struct tm tm;
1507
    int offset;
1508
    time_t utcTime;
1509
1510
    xmlSecAssert2(t != NULL, -1);
1511
    xmlSecAssert2(res != NULL, -1);
1512
1513
    if(!ASN1_TIME_check(t)) {
1514
        xmlSecOpenSSLError("ASN1_TIME_check", NULL);
1515
        return(-1);
1516
    }
1517
1518
    memset(&tm, 0, sizeof(tm));
1519
1520
#define g2(p) (((p)[0]-'0')*10+(p)[1]-'0')
1521
    if(t->type == V_ASN1_UTCTIME) {
1522
        if(t->length <= 12) {
1523
            xmlSecOpenSSLError("invalid ASN1_TIME length", NULL);
1524
            return(-1);
1525
        }
1526
1527
        /* this code is copied from OpenSSL asn1/a_utctm.c file */
1528
        tm.tm_year = g2(t->data);
1529
        if(tm.tm_year < 50) {
1530
            tm.tm_year += 100;
1531
        }
1532
        tm.tm_mon  = g2(t->data + 2) - 1;
1533
        tm.tm_mday = g2(t->data + 4);
1534
        tm.tm_hour = g2(t->data + 6);
1535
        tm.tm_min  = g2(t->data + 8);
1536
        tm.tm_sec  = g2(t->data + 10);
1537
        if(t->data[12] == 'Z') {
1538
            offset = 0;
1539
        } else {
1540
            if(t->length <= 16) {
1541
                xmlSecOpenSSLError("invalid ASN1_TIME length", NULL);
1542
                return(-1);
1543
            }
1544
1545
            offset = g2(t->data + 13) * 60 + g2(t->data + 15);
1546
            if(t->data[12] == '-') {
1547
                offset = -offset;
1548
            }
1549
        }
1550
        /*
1551
         * match OpenSSL's own ASN1_TIME_to_tm(), which leaves tm_isdst at 0:
1552
         * the Windows timegm() fallback below computes mktime() minus the
1553
         * standard-time offset, and letting mktime() pick DST (tm_isdst=-1)
1554
         * would shift wall-clock times inside a DST period by 3600s
1555
         */
1556
        tm.tm_isdst = 0;
1557
    } else {
1558
        int offStart = 14;
1559
        if(t->length <= 14) {
1560
            xmlSecOpenSSLError("invalid ASN1_TIME length", NULL);
1561
            return(-1);
1562
        }
1563
1564
        tm.tm_year = g2(t->data) * 100 + g2(t->data + 2) - 1900;
1565
        tm.tm_mon  = g2(t->data + 4) - 1;
1566
        tm.tm_mday = g2(t->data + 6);
1567
        tm.tm_hour = g2(t->data + 8);
1568
        tm.tm_min  = g2(t->data + 10);
1569
        tm.tm_sec  = g2(t->data + 12);
1570
        if(t->data[14] == '.') {
1571
            /* skip fractional seconds */
1572
            offStart = 15;
1573
            while((offStart < t->length) && ((t->data[offStart] >= '0') && (t->data[offStart] <= '9'))) {
1574
                offStart++;
1575
            }
1576
        }
1577
1578
        if(offStart >= t->length) {
1579
            xmlSecOpenSSLError("invalid ASN1_TIME length", NULL);
1580
            return(-1);
1581
        }
1582
        if(t->data[offStart] == 'Z') {
1583
            offset = 0;
1584
        } else {
1585
            if(t->length <= (offStart + 4)) {
1586
                xmlSecOpenSSLError("invalid ASN1_TIME length", NULL);
1587
                return(-1);
1588
            }
1589
1590
            offset = g2(t->data + offStart + 1) * 60 + g2(t->data + offStart + 3);
1591
            if(t->data[offStart] == '-') {
1592
                offset = -offset;
1593
            }
1594
        }
1595
        /* see the comment above: tm_isdst must be 0 */
1596
        tm.tm_isdst = 0;
1597
    }
1598
#undef g2
1599
1600
    /*
1601
     * validate the parsed fields; out-of-range values make timegm() fail and
1602
     * that failure is not reliably detectable from its return value on all
1603
     * platforms (e.g. Windows)
1604
     */
1605
    if((tm.tm_mon < 0) || (tm.tm_mon > 11) ||
1606
       (tm.tm_mday < 1) || (tm.tm_mday > 31) ||
1607
       (tm.tm_hour < 0) || (tm.tm_hour > 23) ||
1608
       (tm.tm_min < 0) || (tm.tm_min > 59) ||
1609
       (tm.tm_sec < 0) || (tm.tm_sec > 61)
1610
    ) {
1611
        xmlSecOpenSSLError("invalid ASN1_TIME fields", NULL);
1612
        return(-1);
1613
    }
1614
1615
    utcTime = timegm(&tm);
1616
    if(utcTime == (time_t)-1) {
1617
        /*
1618
         * timegm() returns (time_t)-1 on failure. A (time_t)-1 is also a valid
1619
         * time (1969-12-31 23:59:59 UTC), but a certificate date is never in
1620
         * 1969, so treat it as a conversion error.
1621
         */
1622
        xmlSecOpenSSLError("timegm", NULL);
1623
        return(-1);
1624
    }
1625
    (*res) = utcTime - (time_t)(offset * 60);
1626
    return (0);
1627
}
1628
#endif /* XMLSEC_OPENSSL_NO_ASN1_TIME_TO_TM */
1629
1630
/* returns 1 if cert was found and verified and also data was adopted, 0 if not, or negative value if an error occurs */
1631
static int
1632
1.79k
xmlSecOpenSSLVerifyAndAdoptX509KeyData(xmlSecKeyPtr key, xmlSecKeyDataPtr data, xmlSecKeyInfoCtxPtr keyInfoCtx) {
1633
1.79k
    xmlSecOpenSSLX509DataCtxPtr ctx;
1634
1.79k
    xmlSecKeyDataStorePtr x509Store;
1635
1.79k
    xmlSecKeyDataPtr keyValue;
1636
1.79k
    X509* cert;
1637
1.79k
    X509* keyCert;
1638
1.79k
    time_t origNotValidBefore;
1639
1.79k
    time_t origNotValidAfter;
1640
1.79k
    int ret;
1641
1642
1.79k
    xmlSecAssert2(xmlSecKeyDataCheckId(data, xmlSecOpenSSLKeyDataX509Id), -1);
1643
1.79k
    xmlSecAssert2(key != NULL, -1);
1644
1.79k
    xmlSecAssert2(keyInfoCtx != NULL, -1);
1645
1646
    /* keyInfoCtx->keysMngr is optional (see xmlSecKeyInfoCtxCreate) */
1647
1.79k
    if(keyInfoCtx->keysMngr == NULL) {
1648
0
        return(0);
1649
0
    }
1650
1651
1.79k
    ctx = xmlSecOpenSSLX509DataGetCtx(data);
1652
1.79k
    xmlSecAssert2(ctx != NULL, -1);
1653
1.79k
    xmlSecAssert2(ctx->keyCert == NULL, -1);
1654
1655
1.79k
    if((ctx->certsList == NULL) || (xmlSecKeyGetValue(key) != NULL)) {
1656
        /* no certs or key was already found -> nothing to do (this shouldn't really happen) */
1657
1.69k
        return(0);
1658
1.69k
    }
1659
1660
    /* let's find a cert we can verify */
1661
98
    x509Store = xmlSecKeysMngrGetDataStore(keyInfoCtx->keysMngr, xmlSecOpenSSLX509StoreId);
1662
98
    if(x509Store == NULL) {
1663
0
        xmlSecInternalError("xmlSecKeysMngrGetDataStore", xmlSecKeyDataGetName(data));
1664
0
        return(-1);
1665
0
    }
1666
98
    cert = xmlSecOpenSSLX509StoreVerify(x509Store, ctx->certsList, ctx->crlsList, keyInfoCtx);
1667
98
    if(cert == NULL) {
1668
        /* check if we want to fail if cert is not found */
1669
98
        if((keyInfoCtx->flags & XMLSEC_KEYINFO_FLAGS_X509DATA_STOP_ON_INVALID_CERT) != 0) {
1670
0
            xmlSecOtherError(XMLSEC_ERRORS_R_CERT_NOT_FOUND, xmlSecKeyDataGetName(data), NULL);
1671
0
            return(-1);
1672
0
        }
1673
98
        return(0);
1674
98
    }
1675
1676
    /* cert is a borrowed pointer owned by the store's certsList: duplicate it
1677
     * so the x509 data owns its own copy (add-internal's delete_ptr matches by
1678
     * pointer identity and would not displace the original chain entry, so the
1679
     * duplicated content does end up serialized twice alongside the original
1680
     * chain entry -- an accepted consequence of keeping store data immutable).
1681
     */
1682
0
    keyCert = X509_dup(cert);
1683
0
    if(keyCert == NULL) {
1684
0
        xmlSecOpenSSLError("X509_dup", xmlSecKeyDataGetName(data));
1685
0
        return(-1);
1686
0
    }
1687
0
    ret = xmlSecOpenSSLKeyDataX509AdoptKeyCert(data, keyCert);
1688
0
    if(ret < 0) {
1689
0
        xmlSecInternalError("xmlSecOpenSSLKeyDataX509AdoptKeyCert", xmlSecKeyDataGetName(data));
1690
0
        X509_free(keyCert);
1691
0
        return(-1);
1692
0
    }
1693
0
    cert = keyCert = NULL; /* we should be using ctx->keyCert for everything */
1694
1695
    /* extract key from cert and verify that the key matches our expectations */
1696
0
    keyValue = xmlSecOpenSSLX509CertGetKey(ctx->keyCert);
1697
0
    if(keyValue == NULL) {
1698
0
        xmlSecInternalError("xmlSecOpenSSLX509CertGetKey", xmlSecKeyDataGetName(data));
1699
0
        return(-1);
1700
0
    }
1701
    /* note: a clean non-match (return 0) is folded into the error branch on
1702
     * purpose: at this point a certificate has already been verified, so a key
1703
     * that does not satisfy keyReq is treated as a hard failure (fail-closed)
1704
     * rather than the lenient not-found used above for unverified certs. */
1705
0
    if(xmlSecKeyReqMatchKeyValue(&(keyInfoCtx->keyReq), keyValue) != 1) {
1706
0
        xmlSecInternalError("xmlSecKeyReqMatchKeyValue", xmlSecKeyDataGetName(data));
1707
0
        xmlSecKeyDataDestroy(keyValue);
1708
0
        return(-1);
1709
0
    }
1710
    /*
1711
     * from this point on we mutate the caller's key (set its value and validity
1712
     * times). save the original validity times so we can restore the key if a
1713
     * later step fails; the key value is guaranteed to be NULL here (see the
1714
     * check at the beginning of this function)
1715
     */
1716
0
    origNotValidBefore = key->notValidBefore;
1717
0
    origNotValidAfter = key->notValidAfter;
1718
1719
0
    ret = xmlSecKeySetValue(key, keyValue);
1720
0
    if(ret < 0) {
1721
0
        xmlSecInternalError("xmlSecKeySetValue", xmlSecKeyDataGetName(data));
1722
0
        xmlSecKeyDataDestroy(keyValue);
1723
0
        return(-1);
1724
0
    }
1725
0
    keyValue = NULL; /* owned by key now */
1726
1727
    /* copy cert not before / not after times from the cert */
1728
0
    if(X509_get0_notBefore(ctx->keyCert) != NULL) {
1729
0
        ret = xmlSecOpenSSLX509Asn1TimeToTime(X509_get0_notBefore(ctx->keyCert), &(key->notValidBefore));
1730
0
        if(ret < 0) {
1731
0
            xmlSecInternalError("xmlSecOpenSSLX509Asn1TimeToTime(notValidBefore)", xmlSecKeyDataGetName(data));
1732
0
            goto restore;
1733
0
        }
1734
0
    } else {
1735
0
        key->notValidBefore = 0;
1736
0
    }
1737
0
    if(X509_get0_notAfter(ctx->keyCert) != NULL) {
1738
0
        ret = xmlSecOpenSSLX509Asn1TimeToTime(X509_get0_notAfter(ctx->keyCert), &(key->notValidAfter));
1739
0
        if(ret < 0) {
1740
0
            xmlSecInternalError("xmlSecOpenSSLX509Asn1TimeToTime(notValidAfter)", xmlSecKeyDataGetName(data));
1741
0
            goto restore;
1742
0
        }
1743
0
    } else {
1744
0
        key->notValidAfter = 0;
1745
0
    }
1746
1747
    /* THIS MUST BE THE LAST THING WE DO: add data to the key
1748
     * if we do it sooner and fail later then both the caller and the key will free data
1749
     * which would lead to double free */
1750
0
    ret = xmlSecKeyAdoptData(key, data);
1751
0
    if(ret < 0) {
1752
0
        xmlSecInternalError("xmlSecKeyAdoptData", xmlSecKeyDataGetName(data));
1753
0
        goto restore;
1754
0
    }
1755
1756
    /* success: cert found and data was adopted */
1757
0
    return(1);
1758
1759
0
restore:
1760
    /* restore the key to its original state */
1761
0
    ret = xmlSecKeySetValue(key, NULL);
1762
0
    if(ret < 0) {
1763
0
        xmlSecInternalError("xmlSecKeySetValue", xmlSecKeyDataGetName(data));
1764
        /* continue restoring the original state even if setting the value to NULL failed */
1765
0
    }
1766
0
    key->notValidBefore = origNotValidBefore;
1767
0
    key->notValidAfter = origNotValidAfter;
1768
0
    return(-1);
1769
0
}
1770
1771
/**
1772
 * @brief Extracts public key from the @p cert.
1773
 * @param cert the certificate.
1774
 * @return a new key data that the caller owns and must destroy with xmlSecKeyDataDestroy(), or NULL if an error occurs.
1775
 */
1776
xmlSecKeyDataPtr
1777
0
xmlSecOpenSSLX509CertGetKey(X509* cert) {
1778
0
    xmlSecKeyDataPtr data;
1779
0
    EVP_PKEY *pKey = NULL;
1780
1781
0
    xmlSecAssert2(cert != NULL, NULL);
1782
1783
0
    pKey = X509_get_pubkey(cert);
1784
0
    if(pKey == NULL) {
1785
0
        xmlSecOpenSSLError("X509_get_pubkey", NULL);
1786
0
        return(NULL);
1787
0
    }
1788
1789
0
    data = xmlSecOpenSSLEvpKeyAdopt(pKey);
1790
0
    if(data == NULL) {
1791
0
        xmlSecInternalError("xmlSecOpenSSLEvpKeyAdopt", NULL);
1792
0
        EVP_PKEY_free(pKey);
1793
0
        return(NULL);
1794
0
    }
1795
1796
0
    return(data);
1797
0
}
1798
1799
1800
X509*
1801
316
xmlSecOpenSSLX509CertLoadBIO(BIO* bio, xmlSecKeyDataFormat format) {
1802
316
    X509* tmp = NULL;
1803
316
    X509* res = NULL;
1804
1805
316
    xmlSecAssert2(bio != NULL, NULL);
1806
316
    xmlSecAssert2(format != xmlSecKeyDataFormatUnknown, NULL);
1807
1808
    /* create certificate object to hold the cert we are going to read */
1809
316
    tmp = X509_new_ex(xmlSecOpenSSLGetLibCtx(), NULL);
1810
316
    if(tmp == NULL) {
1811
0
        xmlSecOpenSSLError("X509_new_ex", NULL);
1812
0
        goto done;
1813
0
    }
1814
1815
    /* read the cert */
1816
316
    switch(format) {
1817
0
    case xmlSecKeyDataFormatPem:
1818
0
    case xmlSecKeyDataFormatCertPem:
1819
0
        res = PEM_read_bio_X509_AUX(bio, &tmp, NULL, NULL);
1820
0
        if(res == NULL) {
1821
0
            xmlSecOpenSSLError("PEM_read_bio_X509_AUX", NULL);
1822
0
            goto done;
1823
0
        }
1824
0
        tmp = NULL; /* now it's res */
1825
0
        break;
1826
316
    case xmlSecKeyDataFormatDer:
1827
316
    case xmlSecKeyDataFormatCertDer:
1828
316
        res = d2i_X509_bio(bio, &tmp);
1829
316
        if(res == NULL) {
1830
112
            xmlSecOpenSSLError("d2i_X509_bio", NULL);
1831
112
            goto done;
1832
112
        }
1833
204
        tmp = NULL; /* now it's res */
1834
204
        break;
1835
0
    default:
1836
0
        xmlSecOtherError2(XMLSEC_ERRORS_R_INVALID_FORMAT, NULL,
1837
0
            "format=" XMLSEC_ENUM_FMT, XMLSEC_ENUM_CAST(format));
1838
0
        goto done;
1839
316
    }
1840
1841
316
done:
1842
316
    if(tmp != NULL) {
1843
56
        X509_free(tmp);
1844
56
    }
1845
316
    return(res);
1846
316
}
1847
1848
1849
X509_CRL*
1850
0
xmlSecOpenSSLX509CrlLoadBIO(BIO* bio, xmlSecKeyDataFormat format) {
1851
0
    X509_CRL* tmp = NULL;
1852
0
    X509_CRL* res = NULL;
1853
1854
0
    xmlSecAssert2(bio != NULL, NULL);
1855
0
    xmlSecAssert2(format != xmlSecKeyDataFormatUnknown, NULL);
1856
1857
    /* create CRL object to hold the CRL we are going to read */
1858
0
    tmp = X509_CRL_new_ex(xmlSecOpenSSLGetLibCtx(), NULL);
1859
0
    if(tmp == NULL) {
1860
0
        xmlSecOpenSSLError("X509_CRL_new_ex", NULL);
1861
0
        goto done;
1862
0
    }
1863
1864
    /* read the CRL */
1865
0
    switch(format) {
1866
0
    case xmlSecKeyDataFormatPem:
1867
0
    case xmlSecKeyDataFormatCertPem:
1868
0
        res = PEM_read_bio_X509_CRL(bio, &tmp, NULL, NULL);
1869
0
        if(res == NULL) {
1870
0
            xmlSecOpenSSLError("PEM_read_bio_X509_CRL", NULL);
1871
0
            goto done;
1872
0
        }
1873
0
        tmp = NULL; /* now it's res */
1874
0
        break;
1875
0
    case xmlSecKeyDataFormatDer:
1876
0
    case xmlSecKeyDataFormatCertDer:
1877
0
        res = d2i_X509_CRL_bio(bio, &tmp);
1878
0
        if(res == NULL) {
1879
0
            xmlSecOpenSSLError("d2i_X509_CRL_bio", NULL);
1880
0
            goto done;
1881
0
        }
1882
0
        tmp = NULL; /* now it's res */
1883
0
        break;
1884
0
    default:
1885
0
        xmlSecOtherError2(XMLSEC_ERRORS_R_INVALID_FORMAT, NULL,
1886
0
            "format=" XMLSEC_ENUM_FMT, XMLSEC_ENUM_CAST(format));
1887
0
        goto done;
1888
0
    }
1889
1890
0
done:
1891
0
    if(tmp != NULL) {
1892
0
        X509_CRL_free(tmp);
1893
0
    }
1894
0
    return(res);
1895
0
}
1896
1897
static X509*
1898
316
xmlSecOpenSSLX509CertDerRead(const xmlSecByte* buf, xmlSecSize size) {
1899
316
    X509 *cert = NULL;
1900
316
    BIO * bio = NULL;
1901
1902
316
    xmlSecAssert2(buf != NULL, NULL);
1903
316
    xmlSecAssert2(size > 0, NULL);
1904
1905
316
    bio = xmlSecOpenSSLCreateMemBufBio(buf, size);
1906
316
    if(bio == NULL) {
1907
0
        xmlSecInternalError2("xmlSecOpenSSLCreateMemBufBio", NULL,
1908
0
            "size=" XMLSEC_SIZE_FMT, size);
1909
0
        goto done;
1910
0
    }
1911
1912
316
    cert = xmlSecOpenSSLX509CertLoadBIO(bio, xmlSecKeyDataFormatDer);
1913
316
    if(cert == NULL) {
1914
112
        xmlSecInternalError("xmlSecOpenSSLX509CertLoadBIO", NULL);
1915
112
        goto done;
1916
112
    }
1917
1918
    /* check if any bytes remaining */
1919
204
    if(BIO_ctrl_pending(bio) > 0) {
1920
20
        xmlSecInvalidSizeDataError("Remaining in buffer", BIO_ctrl_pending(bio), "0 bytes",  NULL);
1921
20
        X509_free(cert);
1922
20
        cert = NULL;
1923
20
        goto done;
1924
20
    }
1925
1926
316
done:
1927
316
    if(bio != NULL) {
1928
316
        BIO_free_all(bio);
1929
316
    }
1930
316
    return(cert);
1931
204
}
1932
1933
static X509_CRL*
1934
0
xmlSecOpenSSLX509CrlDerRead(const xmlSecByte* buf, xmlSecSize size) {
1935
0
    X509_CRL *crl = NULL;
1936
0
    X509_CRL *res = NULL;
1937
0
    BIO *bio = NULL;
1938
1939
0
    xmlSecAssert2(buf != NULL, NULL);
1940
0
    xmlSecAssert2(size > 0, NULL);
1941
1942
0
    bio = xmlSecOpenSSLCreateMemBufBio(buf, size);
1943
0
    if(bio == NULL) {
1944
0
        xmlSecInternalError2("xmlSecOpenSSLCreateMemBufBio", NULL, "size=" XMLSEC_SIZE_FMT, size);
1945
0
        goto done;
1946
0
    }
1947
0
    crl = xmlSecOpenSSLX509CrlLoadBIO(bio, xmlSecKeyDataFormatDer);
1948
0
    if(crl == NULL) {
1949
0
        xmlSecInternalError("xmlSecOpenSSLX509CrlLoadBIO", NULL);
1950
0
        goto done;
1951
0
    }
1952
1953
    /* check if any bytes remaining */
1954
0
    if(BIO_ctrl_pending(bio) > 0) {
1955
0
        xmlSecInvalidSizeDataError("Remaining in buffer", BIO_ctrl_pending(bio), "0 bytes",  NULL);
1956
0
        goto done;
1957
0
    }
1958
1959
    /* success */
1960
0
    res = crl;
1961
0
    crl = NULL;
1962
1963
0
done:
1964
    /* cleanup */
1965
0
    if(crl != NULL) {
1966
0
        X509_CRL_free(crl);
1967
0
    }
1968
0
    if(bio != NULL) {
1969
0
        BIO_free_all(bio);
1970
0
    }
1971
0
    return(res);
1972
0
}
1973
1974
int
1975
348
xmlSecOpenSSLX509NameToString(XMLSEC_OPENSSL400_CONST X509_NAME* name, char* buf, int bufLen) {
1976
348
    BIO* mem = NULL;
1977
348
    char* data = NULL;
1978
348
    long len;
1979
348
    size_t lenSize;
1980
348
    int res = -1;
1981
1982
348
    xmlSecAssert2(buf != NULL, -1);
1983
348
    xmlSecAssert2(bufLen > 0, -1);
1984
1985
348
    buf[0] = '\0';
1986
348
    if(name == NULL) {
1987
        /* no name: leave buf empty */
1988
0
        return(0);
1989
0
    }
1990
1991
348
    mem = BIO_new(BIO_s_mem());
1992
348
    if(mem == NULL) {
1993
0
        xmlSecOpenSSLError("BIO_new", NULL);
1994
0
        goto done;
1995
0
    }
1996
    /*
1997
     * X509_NAME_print_ex() returns the number of characters written on
1998
     * success and -1 on failure; 0 is a valid result for an empty name
1999
     * (RFC 5280 section 4.1.2.6 permits an empty subject name)
2000
     */
2001
348
    if(X509_NAME_print_ex(mem, name, 0, XN_FLAG_RFC2253) < 0) {
2002
0
        xmlSecOpenSSLError("X509_NAME_print_ex", NULL);
2003
0
        goto done;
2004
0
    }
2005
348
    len = BIO_get_mem_data(mem, &data);
2006
348
    if((len < 0) || ((len > 0) && (data == NULL))) {
2007
0
        xmlSecOpenSSLError("BIO_get_mem_data", NULL);
2008
0
        goto done;
2009
0
    }
2010
2011
    /* truncate the name if needed */
2012
348
    if(len > bufLen - 1) {
2013
0
        long pos;
2014
0
        long charLen;
2015
0
        unsigned char leadByte;
2016
2017
0
        len = bufLen - 1;
2018
2019
        /*
2020
         * XN_FLAG_RFC2253 output is UTF-8: back off to a character boundary
2021
         * so we do not split a multi-byte character when truncating the
2022
         * diagnostic text. Locate the lead byte of the last character and
2023
         * drop the character if it does not fit entirely within the
2024
         * truncated length.
2025
         */
2026
0
        pos = len - 1;
2027
0
        while((pos >= 0) && ((((unsigned char)data[pos]) & 0xC0) == 0x80)) {
2028
0
            pos--;
2029
0
        }
2030
0
        if(pos >= 0) {
2031
0
            leadByte = (unsigned char)data[pos];
2032
0
            if(leadByte >= 0xF0) {
2033
0
                charLen = 4;
2034
0
            } else if(leadByte >= 0xE0) {
2035
0
                charLen = 3;
2036
0
            } else if(leadByte >= 0xC0) {
2037
0
                charLen = 2;
2038
0
            } else {
2039
0
                charLen = 1;
2040
0
            }
2041
0
            if(pos + charLen > len) {
2042
0
                len = pos;
2043
0
            }
2044
0
        }
2045
0
    }
2046
348
    XMLSEC_SAFE_CAST_LONG_TO_SIZE(len, lenSize, goto done, NULL);
2047
348
    if(lenSize > 0) {
2048
        /*
2049
         * BIO_get_mem_data() returns a NULL data pointer together with a
2050
         * zero length for an empty memory BIO, so the copy is only
2051
         * performed for a non-empty name
2052
         */
2053
348
        memcpy(buf, data, lenSize);
2054
348
    }
2055
348
    buf[len] = '\0';
2056
2057
    /* success */
2058
348
    res = 0;
2059
2060
348
done:
2061
348
    if(mem != NULL) {
2062
348
        BIO_free(mem);
2063
348
    }
2064
348
    return(res);
2065
348
}
2066
2067
static void
2068
0
xmlSecOpenSSLX509CertDebugDump(X509* cert, FILE* output) {
2069
0
    const ASN1_INTEGER* serial;
2070
0
    char buf[1024];
2071
0
    BIGNUM *bn = NULL;
2072
0
    int ret;
2073
2074
0
    xmlSecAssert(cert != NULL);
2075
0
    xmlSecAssert(output != NULL);
2076
2077
0
    ret = xmlSecOpenSSLX509NameToString(X509_get_subject_name(cert), buf, sizeof(buf));
2078
0
    if(ret >= 0) {
2079
0
        fprintf(output, "==== Subject Name: %s\n", buf);
2080
0
    } else {
2081
0
        fprintf(output, "==== Subject Name: unknown\n");
2082
0
    }
2083
0
    ret = xmlSecOpenSSLX509NameToString(X509_get_issuer_name(cert), buf, sizeof(buf));
2084
0
    if(ret >= 0) {
2085
0
        fprintf(output, "==== Issuer Name: %s\n", buf);
2086
0
    } else {
2087
0
        fprintf(output, "==== Issuer Name: unknown\n");
2088
0
    }
2089
0
    fprintf(output, "==== Issuer Serial: ");
2090
0
    serial = X509_get_serialNumber(cert);
2091
0
    if(serial != NULL) {
2092
0
        bn = ASN1_INTEGER_to_BN(serial, NULL);
2093
0
    }
2094
0
    if(bn != NULL) {
2095
        /* debug output only: the result of BN_print_fp() is not checked */
2096
0
        (void) BN_print_fp(output, bn);
2097
0
        BN_clear_free(bn);
2098
0
        fprintf(output, "\n");
2099
0
    } else {
2100
0
        fprintf(output, "unknown\n");
2101
0
    }
2102
0
}
2103
2104
2105
static void
2106
0
xmlSecOpenSSLX509CertDebugXmlDump(X509* cert, FILE* output) {
2107
0
    const ASN1_INTEGER* serial;
2108
0
    char buf[1024];
2109
0
    BIGNUM *bn = NULL;
2110
0
    int ret;
2111
2112
0
    xmlSecAssert(cert != NULL);
2113
0
    xmlSecAssert(output != NULL);
2114
2115
0
    fprintf(output, "<SubjectName>");
2116
0
    ret = xmlSecOpenSSLX509NameToString(X509_get_subject_name(cert), buf, sizeof(buf));
2117
0
    if(ret >= 0) {
2118
0
        xmlSecPrintXmlString(output, BAD_CAST buf);
2119
0
    }
2120
0
    fprintf(output, "</SubjectName>\n");
2121
2122
2123
0
    fprintf(output, "<IssuerName>");
2124
0
    ret = xmlSecOpenSSLX509NameToString(X509_get_issuer_name(cert), buf, sizeof(buf));
2125
0
    if(ret >= 0) {
2126
0
        xmlSecPrintXmlString(output, BAD_CAST buf);
2127
0
    }
2128
0
    fprintf(output, "</IssuerName>\n");
2129
2130
0
    fprintf(output, "<SerialNumber>");
2131
0
    serial = X509_get_serialNumber(cert);
2132
0
    if(serial != NULL) {
2133
0
        bn = ASN1_INTEGER_to_BN(serial, NULL);
2134
0
    }
2135
0
    if(bn != NULL) {
2136
        /* debug output only: the result of BN_print_fp() is not checked */
2137
0
        (void) BN_print_fp(output, bn);
2138
0
        BN_clear_free(bn);
2139
0
    }
2140
0
    fprintf(output, "</SerialNumber>\n");
2141
0
}
2142
2143
2144
/******************************************************************************
2145
 *
2146
 * Raw X509 Certificate processing
2147
 *
2148
 *****************************************************************************/
2149
static int              xmlSecOpenSSLKeyDataRawX509CertBinRead  (xmlSecKeyDataId id,
2150
                                                                 xmlSecKeyPtr key,
2151
                                                                 const xmlSecByte* buf,
2152
                                                                 xmlSecSize bufSize,
2153
                                                                 xmlSecKeyInfoCtxPtr keyInfoCtx);
2154
2155
static xmlSecKeyDataKlass xmlSecOpenSSLKeyDataRawX509CertKlass = {
2156
    sizeof(xmlSecKeyDataKlass),
2157
    sizeof(xmlSecKeyData),
2158
2159
    /* data */
2160
    xmlSecNameRawX509Cert,
2161
    xmlSecKeyDataUsageReadFromFile | xmlSecKeyDataUsageRetrievalMethodNodeBin,
2162
                                                /* xmlSecKeyDataUsage usage; */
2163
    xmlSecHrefRawX509Cert,                      /* const xmlChar* href; */
2164
    NULL,                                       /* const xmlChar* dataNodeName; */
2165
    xmlSecDSigNs,                               /* const xmlChar* dataNodeNs; */
2166
2167
    /* constructors/destructor */
2168
    NULL,                                       /* xmlSecKeyDataInitMethod initialize; */
2169
    NULL,                                       /* xmlSecKeyDataDuplicateMethod duplicate; */
2170
    NULL,                                       /* xmlSecKeyDataFinalizeMethod finalize; */
2171
    NULL,                                       /* xmlSecKeyDataGenerateMethod generate; */
2172
2173
    /* get info */
2174
    NULL,                                       /* xmlSecKeyDataGetTypeMethod getType; */
2175
    NULL,                                       /* xmlSecKeyDataGetSizeMethod getSize; */
2176
    NULL,                                       /* DEPRECATED xmlSecKeyDataGetIdentifier getIdentifier; */
2177
2178
    /* read/write */
2179
    NULL,                                       /* xmlSecKeyDataXmlReadMethod xmlRead; */
2180
    NULL,                                       /* xmlSecKeyDataXmlWriteMethod xmlWrite; */
2181
    xmlSecOpenSSLKeyDataRawX509CertBinRead,     /* xmlSecKeyDataBinReadMethod binRead; */
2182
    NULL,                                       /* xmlSecKeyDataBinWriteMethod binWrite; */
2183
2184
    /* debug */
2185
    NULL,                                       /* xmlSecKeyDataDebugDumpMethod debugDump; */
2186
    NULL,                                       /* xmlSecKeyDataDebugDumpMethod debugXmlDump; */
2187
2188
    /* reserved for the future */
2189
    NULL,                                       /* void* reserved0; */
2190
    NULL,                                       /* void* reserved1; */
2191
};
2192
2193
/**
2194
 * @brief The raw X509 certificates key data klass.
2195
 * @return raw X509 certificates key data klass.
2196
 */
2197
xmlSecKeyDataId
2198
3
xmlSecOpenSSLKeyDataRawX509CertGetKlass(void) {
2199
3
    return(&xmlSecOpenSSLKeyDataRawX509CertKlass);
2200
3
}
2201
2202
static int
2203
xmlSecOpenSSLKeyDataRawX509CertBinRead(xmlSecKeyDataId id, xmlSecKeyPtr key,
2204
    const xmlSecByte* buf, xmlSecSize bufSize, xmlSecKeyInfoCtxPtr keyInfoCtx
2205
2
) {
2206
2
    xmlSecKeyDataPtr data;
2207
2
    X509* cert;
2208
2
    int ret;
2209
2210
2
    xmlSecAssert2(id == xmlSecOpenSSLKeyDataRawX509CertId, -1);
2211
2
    xmlSecAssert2(key != NULL, -1);
2212
2
    xmlSecAssert2(buf != NULL, -1);
2213
2
    xmlSecAssert2(bufSize > 0, -1);
2214
2
    xmlSecAssert2(keyInfoCtx != NULL, -1);
2215
2216
2
    cert = xmlSecOpenSSLX509CertDerRead(buf, bufSize);
2217
2
    if(cert == NULL) {
2218
2
        xmlSecInternalError("xmlSecOpenSSLX509CertDerRead", NULL);
2219
2
        return(-1);
2220
2
    }
2221
2222
0
    data = xmlSecKeyDataCreate(xmlSecOpenSSLKeyDataX509Id);
2223
0
    if(data == NULL) {
2224
0
        xmlSecInternalError("xmlSecKeyDataCreate(xmlSecOpenSSLKeyDataX509Id)", xmlSecKeyDataKlassGetName(id));
2225
0
        X509_free(cert);
2226
0
        return(-1);
2227
0
    }
2228
2229
0
    ret = xmlSecOpenSSLKeyDataX509AdoptCert(data, cert);
2230
0
    if(ret < 0) {
2231
0
        xmlSecInternalError("xmlSecOpenSSLKeyDataX509AdoptCert", xmlSecKeyDataKlassGetName(id));
2232
0
        X509_free(cert);
2233
0
        xmlSecKeyDataDestroy(data);
2234
0
        return(-1);
2235
0
    }
2236
0
    cert = NULL; /* owned by data now */
2237
2238
0
    ret = xmlSecOpenSSLVerifyAndAdoptX509KeyData(key, data, keyInfoCtx);
2239
0
    if(ret < 0) {
2240
0
        xmlSecInternalError("xmlSecOpenSSLVerifyAndAdoptX509KeyData", xmlSecKeyDataKlassGetName(id));
2241
0
        xmlSecKeyDataDestroy(data);
2242
0
        return(-1);
2243
0
    } else if(ret != 1) {
2244
        /* no errors but key was not found and data was not adopted */
2245
0
        xmlSecKeyDataDestroy(data);
2246
0
        return(0);
2247
0
    }
2248
0
    data = NULL; /* owned by key now */
2249
2250
    /* success */
2251
0
    return(0);
2252
0
}
2253
2254
#else /* XMLSEC_NO_X509 */
2255
2256
/* ISO C forbids an empty translation unit */
2257
typedef int make_iso_compilers_happy;
2258
2259
#endif /* XMLSEC_NO_X509 */