Coverage Report

Created: 2026-10-16 07:31

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/openssl/crypto/x509/v3_utl.c
Line
Count
Source
1
/*
2
 * Copyright 1999-2026 The OpenSSL Project Authors. All Rights Reserved.
3
 *
4
 * Licensed under the Apache License 2.0 (the "License").  You may not use
5
 * this file except in compliance with the License.  You can obtain a copy
6
 * in the file LICENSE in the source distribution or at
7
 * https://www.openssl.org/source/license.html
8
 */
9
10
/* X509 v3 extension utilities */
11
12
#include "internal/e_os.h"
13
#include "internal/cryptlib.h"
14
#include <stdio.h>
15
#include <string.h>
16
#include "crypto/ctype.h"
17
#include <openssl/conf.h>
18
#include <openssl/crypto.h>
19
#include <openssl/x509v3.h>
20
#include "crypto/x509.h"
21
#include <openssl/bn.h>
22
#include "ext_dat.h"
23
#include "x509_local.h"
24
25
static char *strip_spaces(char *name);
26
static int sk_strcmp(const char *const *a, const char *const *b);
27
static STACK_OF(OPENSSL_STRING) *get_email(const X509_NAME *name,
28
    GENERAL_NAMES *gens);
29
static void str_free(OPENSSL_STRING str);
30
static int append_ia5(STACK_OF(OPENSSL_STRING) **sk,
31
    const ASN1_IA5STRING *email);
32
33
static int ipv4_from_asc(unsigned char *v4, const char *in);
34
static int ipv6_from_asc(unsigned char *v6, const char *in);
35
static int ipv6_cb(const char *elem, int len, void *usr);
36
static int ipv6_hex(unsigned char *out, const char *in, int inlen);
37
38
/* Add a CONF_VALUE name value pair to stack */
39
40
static int x509v3_add_len_value(const char *name, const char *value,
41
    size_t vallen, STACK_OF(CONF_VALUE) **extlist)
42
0
{
43
0
    CONF_VALUE *vtmp = NULL;
44
0
    char *tname = NULL, *tvalue = NULL;
45
0
    int sk_allocated = (*extlist == NULL);
46
47
0
    if (name != NULL && (tname = OPENSSL_strdup(name)) == NULL)
48
0
        goto err;
49
0
    if (value != NULL) {
50
        /* We don't allow embedded NUL characters */
51
0
        if (memchr(value, 0, vallen) != NULL)
52
0
            goto err;
53
0
        tvalue = OPENSSL_strndup(value, vallen);
54
0
        if (tvalue == NULL)
55
0
            goto err;
56
0
    }
57
0
    if ((vtmp = OPENSSL_malloc(sizeof(*vtmp))) == NULL)
58
0
        goto err;
59
0
    if (sk_allocated && (*extlist = sk_CONF_VALUE_new_null()) == NULL) {
60
0
        ERR_raise(ERR_LIB_X509V3, ERR_R_CRYPTO_LIB);
61
0
        goto err;
62
0
    }
63
0
    vtmp->section = NULL;
64
0
    vtmp->name = tname;
65
0
    vtmp->value = tvalue;
66
0
    if (!sk_CONF_VALUE_push(*extlist, vtmp))
67
0
        goto err;
68
0
    return 1;
69
0
err:
70
0
    if (sk_allocated) {
71
0
        sk_CONF_VALUE_free(*extlist);
72
0
        *extlist = NULL;
73
0
    }
74
0
    OPENSSL_free(vtmp);
75
0
    OPENSSL_free(tname);
76
0
    OPENSSL_free(tvalue);
77
0
    return 0;
78
0
}
79
80
int X509V3_add_value(const char *name, const char *value,
81
    STACK_OF(CONF_VALUE) **extlist)
82
0
{
83
0
    return x509v3_add_len_value(name, value,
84
0
        value != NULL ? strlen((const char *)value) : 0,
85
0
        extlist);
86
0
}
87
88
int X509V3_add_value_uchar(const char *name, const unsigned char *value,
89
    STACK_OF(CONF_VALUE) **extlist)
90
0
{
91
0
    return x509v3_add_len_value(name, (const char *)value,
92
0
        value != NULL ? strlen((const char *)value) : 0,
93
0
        extlist);
94
0
}
95
96
int x509v3_add_len_value_uchar(const char *name, const unsigned char *value,
97
    size_t vallen, STACK_OF(CONF_VALUE) **extlist)
98
0
{
99
0
    return x509v3_add_len_value(name, (const char *)value, vallen, extlist);
100
0
}
101
102
/* Free function for STACK_OF(CONF_VALUE) */
103
104
void X509V3_conf_free(CONF_VALUE *conf)
105
0
{
106
0
    if (!conf)
107
0
        return;
108
0
    OPENSSL_free(conf->name);
109
0
    OPENSSL_free(conf->value);
110
0
    OPENSSL_free(conf->section);
111
0
    OPENSSL_free(conf);
112
0
}
113
114
int X509V3_add_value_bool(const char *name, int asn1_bool,
115
    STACK_OF(CONF_VALUE) **extlist)
116
0
{
117
0
    if (asn1_bool)
118
0
        return X509V3_add_value(name, "TRUE", extlist);
119
0
    return X509V3_add_value(name, "FALSE", extlist);
120
0
}
121
122
int X509V3_add_value_bool_nf(const char *name, int asn1_bool,
123
    STACK_OF(CONF_VALUE) **extlist)
124
0
{
125
0
    if (asn1_bool)
126
0
        return X509V3_add_value(name, "TRUE", extlist);
127
0
    return 1;
128
0
}
129
130
static char *bignum_to_string(const BIGNUM *bn)
131
0
{
132
0
    char *tmp, *ret = NULL;
133
134
    /*
135
     * Display large numbers in hex and small numbers in decimal. Converting to
136
     * decimal takes quadratic time and is no more useful than hex for large
137
     * numbers.
138
     */
139
0
    if (BN_num_bits(bn) < 128)
140
0
        return BN_bn2dec(bn);
141
142
0
    tmp = BN_bn2hex(bn);
143
0
    if (tmp == NULL)
144
0
        return NULL;
145
146
    /* Prepend "0x", but place it after the "-" if negative. */
147
0
    if (tmp[0] == '-')
148
0
        (void)ossl_asprintf(&ret, "-0x%s", tmp + 1);
149
0
    else
150
0
        (void)ossl_asprintf(&ret, "0x%s", tmp);
151
0
    OPENSSL_free(tmp);
152
0
    return ret;
153
0
}
154
155
char *i2s_ASN1_ENUMERATED(X509V3_EXT_METHOD *method, const ASN1_ENUMERATED *a)
156
0
{
157
0
    BIGNUM *bntmp = NULL;
158
0
    char *strtmp = NULL;
159
160
0
    if (!a)
161
0
        return NULL;
162
0
    if ((bntmp = ASN1_ENUMERATED_to_BN(a, NULL)) == NULL)
163
0
        ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB);
164
0
    else if ((strtmp = bignum_to_string(bntmp)) == NULL)
165
0
        ERR_raise(ERR_LIB_X509V3, ERR_R_X509V3_LIB);
166
0
    BN_free(bntmp);
167
0
    return strtmp;
168
0
}
169
170
char *i2s_ASN1_INTEGER(X509V3_EXT_METHOD *method, const ASN1_INTEGER *a)
171
0
{
172
0
    BIGNUM *bntmp = NULL;
173
0
    char *strtmp = NULL;
174
175
0
    if (!a)
176
0
        return NULL;
177
0
    if ((bntmp = ASN1_INTEGER_to_BN(a, NULL)) == NULL)
178
0
        ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB);
179
0
    else if ((strtmp = bignum_to_string(bntmp)) == NULL)
180
0
        ERR_raise(ERR_LIB_X509V3, ERR_R_X509V3_LIB);
181
0
    BN_free(bntmp);
182
0
    return strtmp;
183
0
}
184
185
ASN1_INTEGER *s2i_ASN1_INTEGER(X509V3_EXT_METHOD *method, const char *value)
186
0
{
187
0
    BIGNUM *bn = NULL;
188
0
    ASN1_INTEGER *aint;
189
0
    int isneg, ishex;
190
0
    int ret;
191
192
0
    if (value == NULL) {
193
0
        ERR_raise(ERR_LIB_X509V3, X509V3_R_INVALID_NULL_VALUE);
194
0
        return NULL;
195
0
    }
196
0
    bn = BN_new();
197
0
    if (bn == NULL) {
198
0
        ERR_raise(ERR_LIB_X509V3, ERR_R_BN_LIB);
199
0
        return NULL;
200
0
    }
201
0
    if (value[0] == '-') {
202
0
        value++;
203
0
        isneg = 1;
204
0
    } else {
205
0
        isneg = 0;
206
0
    }
207
208
0
    if (value[0] == '0' && ((value[1] == 'x') || (value[1] == 'X'))) {
209
0
        value += 2;
210
0
        ishex = 1;
211
0
    } else {
212
0
        ishex = 0;
213
0
    }
214
215
0
    if (ishex)
216
0
        ret = BN_hex2bn(&bn, value);
217
0
    else
218
0
        ret = BN_dec2bn(&bn, value);
219
220
0
    if (!ret || value[ret]) {
221
0
        BN_free(bn);
222
0
        ERR_raise(ERR_LIB_X509V3, X509V3_R_BN_DEC2BN_ERROR);
223
0
        return NULL;
224
0
    }
225
226
0
    if (isneg && BN_is_zero(bn))
227
0
        isneg = 0;
228
229
0
    aint = BN_to_ASN1_INTEGER(bn, NULL);
230
0
    BN_free(bn);
231
0
    if (!aint) {
232
0
        ERR_raise(ERR_LIB_X509V3, X509V3_R_BN_TO_ASN1_INTEGER_ERROR);
233
0
        return NULL;
234
0
    }
235
0
    if (isneg)
236
0
        aint->type |= V_ASN1_NEG;
237
0
    return aint;
238
0
}
239
240
int X509V3_add_value_int(const char *name, const ASN1_INTEGER *aint,
241
    STACK_OF(CONF_VALUE) **extlist)
242
0
{
243
0
    char *strtmp;
244
0
    int ret;
245
246
0
    if (!aint)
247
0
        return 1;
248
0
    if ((strtmp = i2s_ASN1_INTEGER(NULL, aint)) == NULL)
249
0
        return 0;
250
0
    ret = X509V3_add_value(name, strtmp, extlist);
251
0
    OPENSSL_free(strtmp);
252
0
    return ret;
253
0
}
254
255
int X509V3_get_value_bool(const CONF_VALUE *value, int *asn1_bool)
256
0
{
257
0
    const char *btmp;
258
259
0
    if ((btmp = value->value) == NULL)
260
0
        goto err;
261
0
    if (strcmp(btmp, "TRUE") == 0
262
0
        || strcmp(btmp, "true") == 0
263
0
        || strcmp(btmp, "Y") == 0
264
0
        || strcmp(btmp, "y") == 0
265
0
        || strcmp(btmp, "YES") == 0
266
0
        || strcmp(btmp, "yes") == 0) {
267
0
        *asn1_bool = 0xff;
268
0
        return 1;
269
0
    }
270
0
    if (strcmp(btmp, "FALSE") == 0
271
0
        || strcmp(btmp, "false") == 0
272
0
        || strcmp(btmp, "N") == 0
273
0
        || strcmp(btmp, "n") == 0
274
0
        || strcmp(btmp, "NO") == 0
275
0
        || strcmp(btmp, "no") == 0) {
276
0
        *asn1_bool = 0;
277
0
        return 1;
278
0
    }
279
0
err:
280
0
    ERR_raise(ERR_LIB_X509V3, X509V3_R_INVALID_BOOLEAN_STRING);
281
0
    X509V3_conf_add_error_name_value(value);
282
0
    return 0;
283
0
}
284
285
int X509V3_get_value_int(const CONF_VALUE *value, ASN1_INTEGER **aint)
286
0
{
287
0
    ASN1_INTEGER *itmp;
288
289
0
    if ((itmp = s2i_ASN1_INTEGER(NULL, value->value)) == NULL) {
290
0
        X509V3_conf_add_error_name_value(value);
291
0
        return 0;
292
0
    }
293
0
    *aint = itmp;
294
0
    return 1;
295
0
}
296
297
0
#define HDR_NAME 1
298
0
#define HDR_VALUE 2
299
300
/*
301
 * #define DEBUG
302
 */
303
304
STACK_OF(CONF_VALUE) *X509V3_parse_list(const char *line)
305
0
{
306
0
    char *p, *q, c;
307
0
    char *ntmp, *vtmp;
308
0
    STACK_OF(CONF_VALUE) *values = NULL;
309
0
    char *linebuf;
310
0
    int state;
311
312
    /* We are going to modify the line so copy it first */
313
0
    linebuf = OPENSSL_strdup(line);
314
0
    if (linebuf == NULL)
315
0
        goto err;
316
0
    state = HDR_NAME;
317
0
    ntmp = NULL;
318
    /* Go through all characters */
319
0
    for (p = linebuf, q = linebuf; (c = *p) && (c != '\r') && (c != '\n');
320
0
        p++) {
321
322
0
        switch (state) {
323
0
        case HDR_NAME:
324
0
            if (c == ':') {
325
0
                state = HDR_VALUE;
326
0
                *p = 0;
327
0
                ntmp = strip_spaces(q);
328
0
                if (!ntmp) {
329
0
                    ERR_raise(ERR_LIB_X509V3, X509V3_R_INVALID_EMPTY_NAME);
330
0
                    goto err;
331
0
                }
332
0
                q = p + 1;
333
0
            } else if (c == ',') {
334
0
                *p = 0;
335
0
                ntmp = strip_spaces(q);
336
0
                q = p + 1;
337
0
                if (!ntmp) {
338
0
                    ERR_raise(ERR_LIB_X509V3, X509V3_R_INVALID_EMPTY_NAME);
339
0
                    goto err;
340
0
                }
341
0
                if (!X509V3_add_value(ntmp, NULL, &values)) {
342
0
                    goto err;
343
0
                }
344
0
            }
345
0
            break;
346
347
0
        case HDR_VALUE:
348
0
            if (c == ',') {
349
0
                state = HDR_NAME;
350
0
                *p = 0;
351
0
                vtmp = strip_spaces(q);
352
0
                if (!vtmp) {
353
0
                    ERR_raise(ERR_LIB_X509V3, X509V3_R_INVALID_NULL_VALUE);
354
0
                    goto err;
355
0
                }
356
0
                if (!X509V3_add_value(ntmp, vtmp, &values)) {
357
0
                    goto err;
358
0
                }
359
0
                ntmp = NULL;
360
0
                q = p + 1;
361
0
            }
362
0
        }
363
0
    }
364
365
0
    if (state == HDR_VALUE) {
366
0
        vtmp = strip_spaces(q);
367
0
        if (!vtmp) {
368
0
            ERR_raise(ERR_LIB_X509V3, X509V3_R_INVALID_NULL_VALUE);
369
0
            goto err;
370
0
        }
371
0
        if (!X509V3_add_value(ntmp, vtmp, &values)) {
372
0
            goto err;
373
0
        }
374
0
    } else {
375
0
        ntmp = strip_spaces(q);
376
0
        if (!ntmp) {
377
0
            ERR_raise(ERR_LIB_X509V3, X509V3_R_INVALID_EMPTY_NAME);
378
0
            goto err;
379
0
        }
380
0
        if (!X509V3_add_value(ntmp, NULL, &values)) {
381
0
            goto err;
382
0
        }
383
0
    }
384
0
    OPENSSL_free(linebuf);
385
0
    return values;
386
387
0
err:
388
0
    OPENSSL_free(linebuf);
389
0
    sk_CONF_VALUE_pop_free(values, X509V3_conf_free);
390
0
    return NULL;
391
0
}
392
393
/* Delete leading and trailing spaces from a string */
394
static char *strip_spaces(char *name)
395
0
{
396
0
    char *p, *q;
397
398
    /* Skip over leading spaces */
399
0
    p = name;
400
0
    while (*p && ossl_isspace(*p))
401
0
        p++;
402
0
    if (*p == '\0')
403
0
        return NULL;
404
0
    q = p + strlen(p) - 1;
405
0
    while ((q != p) && ossl_isspace(*q))
406
0
        q--;
407
0
    if (p != q)
408
0
        q[1] = 0;
409
0
    if (*p == '\0')
410
0
        return NULL;
411
0
    return p;
412
0
}
413
414
/*
415
 * V2I name comparison function: returns zero if 'name' matches cmp or cmp.*
416
 */
417
418
int ossl_v3_name_cmp(const char *name, const char *cmp)
419
0
{
420
0
    size_t len;
421
0
    int ret;
422
0
    char c;
423
424
0
    len = strlen(cmp);
425
0
    if ((ret = strncmp(name, cmp, len)))
426
0
        return ret;
427
0
    c = name[len];
428
0
    if (!c || (c == '.'))
429
0
        return 0;
430
0
    return 1;
431
0
}
432
433
static int sk_strcmp(const char *const *a, const char *const *b)
434
0
{
435
0
    return strcmp(*a, *b);
436
0
}
437
438
STACK_OF(OPENSSL_STRING) *X509_get1_email(const X509 *x)
439
0
{
440
0
    GENERAL_NAMES *gens;
441
0
    STACK_OF(OPENSSL_STRING) *ret;
442
443
0
    gens = X509_get_ext_d2i(x, NID_subject_alt_name, NULL, NULL);
444
0
    ret = get_email(X509_get_subject_name(x), gens);
445
0
    sk_GENERAL_NAME_pop_free(gens, GENERAL_NAME_free);
446
0
    return ret;
447
0
}
448
449
STACK_OF(OPENSSL_STRING) *X509_get1_ocsp(const X509 *x)
450
0
{
451
0
    AUTHORITY_INFO_ACCESS *info;
452
0
    STACK_OF(OPENSSL_STRING) *ret = NULL;
453
0
    int i;
454
455
0
    info = X509_get_ext_d2i(x, NID_info_access, NULL, NULL);
456
0
    if (!info)
457
0
        return NULL;
458
0
    for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
459
0
        ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
460
0
        if (OBJ_obj2nid(ad->method) == NID_ad_OCSP) {
461
0
            if (ad->location->type == GEN_URI) {
462
0
                if (!append_ia5(&ret, ad->location->d.uniformResourceIdentifier))
463
0
                    break;
464
0
            }
465
0
        }
466
0
    }
467
0
    AUTHORITY_INFO_ACCESS_free(info);
468
0
    return ret;
469
0
}
470
471
STACK_OF(OPENSSL_STRING) *X509_REQ_get1_email(const X509_REQ *x)
472
0
{
473
0
    GENERAL_NAMES *gens;
474
0
    STACK_OF(X509_EXTENSION) *exts;
475
0
    STACK_OF(OPENSSL_STRING) *ret;
476
477
0
    exts = X509_REQ_get_extensions(x);
478
0
    gens = X509V3_get_d2i(exts, NID_subject_alt_name, NULL, NULL);
479
0
    ret = get_email(X509_REQ_get_subject_name(x), gens);
480
0
    sk_GENERAL_NAME_pop_free(gens, GENERAL_NAME_free);
481
0
    sk_X509_EXTENSION_pop_free(exts, X509_EXTENSION_free);
482
0
    return ret;
483
0
}
484
485
static STACK_OF(OPENSSL_STRING) *get_email(const X509_NAME *name,
486
    GENERAL_NAMES *gens)
487
0
{
488
0
    STACK_OF(OPENSSL_STRING) *ret = NULL;
489
0
    const X509_NAME_ENTRY *ne;
490
0
    const ASN1_IA5STRING *email;
491
0
    GENERAL_NAME *gen;
492
0
    int i = -1;
493
494
    /* Now add any email address(es) to STACK */
495
    /* First supplied X509_NAME */
496
0
    while ((i = X509_NAME_get_index_by_NID(name,
497
0
                NID_pkcs9_emailAddress, i))
498
0
        >= 0) {
499
0
        ne = X509_NAME_get_entry(name, i);
500
0
        email = X509_NAME_ENTRY_get_data(ne);
501
0
        if (!append_ia5(&ret, email))
502
0
            return NULL;
503
0
    }
504
0
    for (i = 0; i < sk_GENERAL_NAME_num(gens); i++) {
505
0
        gen = sk_GENERAL_NAME_value(gens, i);
506
0
        if (gen->type != GEN_EMAIL)
507
0
            continue;
508
0
        if (!append_ia5(&ret, gen->d.ia5))
509
0
            return NULL;
510
0
    }
511
0
    return ret;
512
0
}
513
514
static void str_free(OPENSSL_STRING str)
515
0
{
516
0
    OPENSSL_free(str);
517
0
}
518
519
static int append_ia5(STACK_OF(OPENSSL_STRING) **sk,
520
    const ASN1_IA5STRING *email)
521
0
{
522
0
    char *emtmp;
523
524
    /* First some sanity checks */
525
0
    if (email->type != V_ASN1_IA5STRING)
526
0
        return 1;
527
0
    if (email->data == NULL || email->length == 0)
528
0
        return 1;
529
0
    if (memchr(email->data, 0, email->length) != NULL)
530
0
        return 1;
531
0
    if (*sk == NULL)
532
0
        *sk = sk_OPENSSL_STRING_new(sk_strcmp);
533
0
    if (*sk == NULL)
534
0
        return 0;
535
536
0
    emtmp = OPENSSL_strndup((char *)email->data, email->length);
537
0
    if (emtmp == NULL) {
538
0
        X509_email_free(*sk);
539
0
        *sk = NULL;
540
0
        return 0;
541
0
    }
542
543
    /* Don't add duplicates */
544
0
    if (sk_OPENSSL_STRING_find(*sk, emtmp) != -1) {
545
0
        OPENSSL_free(emtmp);
546
0
        return 1;
547
0
    }
548
0
    if (!sk_OPENSSL_STRING_push(*sk, emtmp)) {
549
0
        OPENSSL_free(emtmp); /* free on push failure */
550
0
        X509_email_free(*sk);
551
0
        *sk = NULL;
552
0
        return 0;
553
0
    }
554
0
    return 1;
555
0
}
556
557
void X509_email_free(STACK_OF(OPENSSL_STRING) *sk)
558
0
{
559
0
    sk_OPENSSL_STRING_pop_free(sk, str_free);
560
0
}
561
562
typedef int (*equal_fn)(const unsigned char *pattern, size_t pattern_len,
563
    const unsigned char *subject, size_t subject_len,
564
    unsigned int flags);
565
566
/* Skip pattern prefix to match "wildcard" subject */
567
static void skip_prefix(const unsigned char **p, size_t *plen,
568
    size_t subject_len,
569
    unsigned int flags)
570
0
{
571
0
    const unsigned char *pattern = *p;
572
0
    size_t pattern_len = *plen;
573
574
    /*
575
     * If subject starts with a leading '.' followed by more octets, and
576
     * pattern is longer, compare just an equal-length suffix with the
577
     * full subject (starting at the '.'), provided the prefix contains
578
     * no NULs.
579
     */
580
0
    if ((flags & _X509_CHECK_FLAG_DOT_SUBDOMAINS) == 0)
581
0
        return;
582
583
0
    while (pattern_len > subject_len && *pattern) {
584
0
        if ((flags & X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS) && *pattern == '.')
585
0
            break;
586
0
        ++pattern;
587
0
        --pattern_len;
588
0
    }
589
590
    /* Skip if entire prefix acceptable */
591
0
    if (pattern_len == subject_len) {
592
0
        *p = pattern;
593
0
        *plen = pattern_len;
594
0
    }
595
0
}
596
597
/* Compare while ASCII ignoring case. */
598
static int equal_nocase(const unsigned char *pattern, size_t pattern_len,
599
    const unsigned char *subject, size_t subject_len,
600
    unsigned int flags)
601
0
{
602
0
    skip_prefix(&pattern, &pattern_len, subject_len, flags);
603
0
    if (pattern_len != subject_len)
604
0
        return 0;
605
0
    while (pattern_len != 0) {
606
0
        unsigned char l = *pattern;
607
0
        unsigned char r = *subject;
608
609
        /* The pattern must not contain NUL characters. */
610
0
        if (l == 0)
611
0
            return 0;
612
0
        if (l != r) {
613
0
            if ('A' <= l && l <= 'Z')
614
0
                l = (l - 'A') + 'a';
615
0
            if ('A' <= r && r <= 'Z')
616
0
                r = (r - 'A') + 'a';
617
0
            if (l != r)
618
0
                return 0;
619
0
        }
620
0
        ++pattern;
621
0
        ++subject;
622
0
        --pattern_len;
623
0
    }
624
0
    return 1;
625
0
}
626
627
/* Compare using memcmp. */
628
static int equal_case(const unsigned char *pattern, size_t pattern_len,
629
    const unsigned char *subject, size_t subject_len,
630
    unsigned int flags)
631
0
{
632
0
    skip_prefix(&pattern, &pattern_len, subject_len, flags);
633
0
    if (pattern_len != subject_len)
634
0
        return 0;
635
0
    return !memcmp(pattern, subject, pattern_len);
636
0
}
637
638
/*
639
 * RFC 5280, section 7.5, requires that only the domain is compared in a
640
 * case-insensitive manner.
641
 */
642
static int equal_email(const unsigned char *a, size_t a_len,
643
    const unsigned char *b, size_t b_len,
644
    unsigned int unused_flags)
645
0
{
646
0
    size_t i = a_len;
647
648
0
    if (a_len != b_len)
649
0
        return 0;
650
    /*
651
     * We search backwards for the '@' character, so that we do not have to
652
     * deal with quoted local-parts.  The domain part is compared in a
653
     * case-insensitive manner.
654
     */
655
0
    while (i > 0) {
656
0
        --i;
657
0
        if (a[i] == '@' || b[i] == '@') {
658
0
            if (!equal_nocase(a + i, a_len - i, b + i, a_len - i, 0))
659
0
                return 0;
660
0
            break;
661
0
        }
662
0
    }
663
0
    if (i == 0)
664
0
        i = a_len;
665
0
    return equal_case(a, i, b, i, 0);
666
0
}
667
668
/*
669
 * Compare the prefix and suffix with the subject, and check that the
670
 * characters in-between are valid.
671
 */
672
static int wildcard_match(const unsigned char *prefix, size_t prefix_len,
673
    const unsigned char *suffix, size_t suffix_len,
674
    const unsigned char *subject, size_t subject_len,
675
    unsigned int flags)
676
0
{
677
0
    const unsigned char *wildcard_start;
678
0
    const unsigned char *wildcard_end;
679
0
    const unsigned char *p;
680
0
    int allow_multi = 0;
681
0
    int allow_idna = 0;
682
683
0
    if (subject_len < prefix_len + suffix_len)
684
0
        return 0;
685
0
    if (!equal_nocase(prefix, prefix_len, subject, prefix_len, flags))
686
0
        return 0;
687
0
    wildcard_start = subject + prefix_len;
688
0
    wildcard_end = subject + (subject_len - suffix_len);
689
0
    if (!equal_nocase(wildcard_end, suffix_len, suffix, suffix_len, flags))
690
0
        return 0;
691
    /*
692
     * If the wildcard makes up the entire first label, it must match at
693
     * least one character.
694
     */
695
0
    if (prefix_len == 0 && *suffix == '.') {
696
0
        if (wildcard_start == wildcard_end)
697
0
            return 0;
698
0
        allow_idna = 1;
699
0
        if (flags & X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS)
700
0
            allow_multi = 1;
701
0
    }
702
    /* IDNA labels cannot match partial wildcards */
703
0
    if (!allow_idna && subject_len >= 4 && HAS_CASE_PREFIX((const char *)subject, "xn--"))
704
0
        return 0;
705
    /* The wildcard may match a literal '*' */
706
0
    if (wildcard_end == wildcard_start + 1 && *wildcard_start == '*')
707
0
        return 1;
708
    /*
709
     * Check that the part matched by the wildcard contains only
710
     * permitted characters and only matches a single label unless
711
     * allow_multi is set.
712
     */
713
0
    for (p = wildcard_start; p != wildcard_end; ++p)
714
0
        if (!(('0' <= *p && *p <= '9') || ('A' <= *p && *p <= 'Z') || ('a' <= *p && *p <= 'z') || *p == '-' || (allow_multi && *p == '.')))
715
0
            return 0;
716
0
    return 1;
717
0
}
718
719
0
#define LABEL_START (1 << 0)
720
#define LABEL_END (1 << 1)
721
0
#define LABEL_HYPHEN (1 << 2)
722
0
#define LABEL_IDNA (1 << 3)
723
724
static const unsigned char *valid_star(const unsigned char *p, size_t len,
725
    unsigned int flags)
726
0
{
727
0
    const unsigned char *star = 0;
728
0
    size_t i;
729
0
    int state = LABEL_START;
730
0
    int dots = 0;
731
732
0
    for (i = 0; i < len; ++i) {
733
        /*
734
         * Locate first and only legal wildcard, either at the start
735
         * or end of a non-IDNA first and not final label.
736
         */
737
0
        if (p[i] == '*') {
738
0
            int atstart = (state & LABEL_START);
739
0
            int atend = (i == len - 1 || p[i + 1] == '.');
740
            /*-
741
             * At most one wildcard per pattern.
742
             * No wildcards in IDNA labels.
743
             * No wildcards after the first label.
744
             */
745
0
            if (star != NULL || (state & LABEL_IDNA) != 0 || dots)
746
0
                return NULL;
747
            /* Only full-label '*.example.com' wildcards? */
748
0
            if ((flags & X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS)
749
0
                && (!atstart || !atend))
750
0
                return NULL;
751
            /* No 'foo*bar' wildcards */
752
0
            if (!atstart && !atend)
753
0
                return NULL;
754
0
            star = &p[i];
755
0
            state &= ~LABEL_START;
756
0
        } else if (('a' <= p[i] && p[i] <= 'z')
757
0
            || ('A' <= p[i] && p[i] <= 'Z')
758
0
            || ('0' <= p[i] && p[i] <= '9')) {
759
0
            if ((state & LABEL_START) != 0
760
0
                && len - i >= 4 && HAS_CASE_PREFIX((const char *)&p[i], "xn--"))
761
0
                state |= LABEL_IDNA;
762
0
            state &= ~(LABEL_HYPHEN | LABEL_START);
763
0
        } else if (p[i] == '.') {
764
0
            if ((state & (LABEL_HYPHEN | LABEL_START)) != 0)
765
0
                return NULL;
766
0
            state = LABEL_START;
767
0
            ++dots;
768
0
        } else if (p[i] == '-') {
769
            /* no domain/subdomain starts with '-' */
770
0
            if ((state & LABEL_START) != 0)
771
0
                return NULL;
772
0
            state |= LABEL_HYPHEN;
773
0
        } else {
774
0
            return NULL;
775
0
        }
776
0
    }
777
778
    /*
779
     * The final label must not end in a hyphen or ".", and
780
     * there must be at least two dots after the star.
781
     */
782
0
    if ((state & (LABEL_START | LABEL_HYPHEN)) != 0 || dots < 2)
783
0
        return NULL;
784
0
    return star;
785
0
}
786
787
/* Compare using wildcards. */
788
static int equal_wildcard(const unsigned char *pattern, size_t pattern_len,
789
    const unsigned char *subject, size_t subject_len,
790
    unsigned int flags)
791
0
{
792
0
    const unsigned char *star = NULL;
793
794
    /*
795
     * Subject names starting with '.' can only match a wildcard pattern
796
     * via a subject sub-domain pattern suffix match.
797
     */
798
0
    if (!(subject_len > 1 && subject[0] == '.'))
799
0
        star = valid_star(pattern, pattern_len, flags);
800
0
    if (star == NULL)
801
0
        return equal_nocase(pattern, pattern_len,
802
0
            subject, subject_len, flags);
803
0
    return wildcard_match(pattern, star - pattern,
804
0
        star + 1, (pattern + pattern_len) - star - 1,
805
0
        subject, subject_len, flags);
806
0
}
807
808
/*
809
 * Compare an ASN1_STRING to a supplied string. If they match return 1. If
810
 * cmp_type > 0 only compare if string matches the type, otherwise convert it
811
 * to UTF8.
812
 */
813
814
static int do_check_string(const ASN1_STRING *a, int cmp_type, equal_fn equal,
815
    unsigned int flags, const char *b, size_t blen,
816
    char **peername)
817
0
{
818
0
    int rv = 0;
819
820
0
    if (!a->data || !a->length)
821
0
        return 0;
822
0
    if (cmp_type > 0) {
823
0
        if (cmp_type != a->type)
824
0
            return 0;
825
0
        if (cmp_type == V_ASN1_IA5STRING)
826
0
            rv = equal(a->data, a->length, (unsigned char *)b, blen, flags);
827
0
        else if (a->length == (int)blen && !memcmp(a->data, b, blen))
828
0
            rv = 1;
829
0
        if (rv > 0 && peername != NULL) {
830
0
            *peername = OPENSSL_strndup((char *)a->data, a->length);
831
0
            if (*peername == NULL)
832
0
                return -1;
833
0
        }
834
0
    } else {
835
0
        int astrlen;
836
0
        unsigned char *astr;
837
0
        astrlen = ASN1_STRING_to_UTF8(&astr, a);
838
0
        if (astrlen < 0) {
839
            /*
840
             * -1 could be an internal malloc failure or a decoding error from
841
             * malformed input; we can't distinguish.
842
             */
843
0
            return -1;
844
0
        }
845
0
        rv = equal(astr, astrlen, (unsigned char *)b, blen, flags);
846
0
        if (rv > 0 && peername != NULL) {
847
0
            *peername = OPENSSL_strndup((char *)astr, astrlen);
848
0
            if (*peername == NULL) {
849
0
                OPENSSL_free(astr);
850
0
                return -1;
851
0
            }
852
0
        }
853
0
        OPENSSL_free(astr);
854
0
    }
855
0
    return rv;
856
0
}
857
858
static int do_x509_check(const X509 *x, const char *chk, size_t chklen,
859
    unsigned int flags, int check_type, int othername_nid, char **peername)
860
0
{
861
0
    GENERAL_NAMES *gens = NULL;
862
0
    const X509_NAME *name = NULL;
863
0
    int i;
864
0
    int cnid = NID_undef;
865
0
    int alt_type;
866
0
    int rv = 0;
867
0
    equal_fn equal;
868
869
    /* See below, this flag is internal-only */
870
0
    flags &= ~_X509_CHECK_FLAG_DOT_SUBDOMAINS;
871
0
    if (check_type == GEN_EMAIL) {
872
0
        cnid = NID_pkcs9_emailAddress;
873
0
        alt_type = V_ASN1_IA5STRING;
874
0
        equal = equal_email;
875
0
    } else if (check_type == GEN_DNS) {
876
0
        cnid = NID_commonName;
877
        /* Implicit client-side DNS sub-domain pattern */
878
0
        if (chklen > 1 && chk[0] == '.')
879
0
            flags |= _X509_CHECK_FLAG_DOT_SUBDOMAINS;
880
0
        alt_type = V_ASN1_IA5STRING;
881
0
        if (flags & X509_CHECK_FLAG_NO_WILDCARDS)
882
0
            equal = equal_nocase;
883
0
        else
884
0
            equal = equal_wildcard;
885
0
    } else {
886
0
        alt_type = V_ASN1_OCTET_STRING;
887
0
        equal = equal_case;
888
0
    }
889
890
0
    if (chklen == 0)
891
0
        chklen = strlen(chk);
892
893
0
    gens = X509_get_ext_d2i(x, NID_subject_alt_name, NULL, NULL);
894
0
    if (gens) {
895
0
        for (i = 0; i < sk_GENERAL_NAME_num(gens); i++) {
896
0
            GENERAL_NAME *gen;
897
0
            ASN1_STRING *cstr;
898
899
0
            gen = sk_GENERAL_NAME_value(gens, i);
900
0
            switch (gen->type) {
901
0
            default:
902
0
                continue;
903
0
            case GEN_OTHERNAME:
904
0
                if (check_type != GEN_OTHERNAME)
905
0
                    continue;
906
0
                switch (OBJ_obj2nid(gen->d.otherName->type_id)) {
907
0
                default:
908
0
                    continue;
909
0
                case NID_id_on_SmtpUTF8Mailbox:
910
                    /*-
911
                     * https://datatracker.ietf.org/doc/html/rfc8398#section-3
912
                     *
913
                     *   Due to name constraint compatibility reasons described
914
                     *   in Section 6, SmtpUTF8Mailbox subjectAltName MUST NOT
915
                     *   be used unless the local-part of the email address
916
                     *   contains non-ASCII characters. When the local-part is
917
                     *   ASCII, rfc822Name subjectAltName MUST be used instead
918
                     *   of SmtpUTF8Mailbox. This is compatible with legacy
919
                     *   software that supports only rfc822Name (and not
920
                     *   SmtpUTF8Mailbox). [...]
921
                     *
922
                     *   SmtpUTF8Mailbox is encoded as UTF8String.
923
                     *
924
                     * If it is not a UTF8String then that is unexpected, and
925
                     * we ignore the invalid SAN, so it is not considered a
926
                     * candidate for equality.
927
                     */
928
0
                    if (othername_nid != NID_id_on_SmtpUTF8Mailbox
929
0
                        || gen->d.otherName->value->type != V_ASN1_UTF8STRING)
930
0
                        continue;
931
0
                    alt_type = 0;
932
0
                    cstr = gen->d.otherName->value->value.utf8string;
933
0
                    break;
934
0
                }
935
0
                break;
936
0
            case GEN_EMAIL:
937
0
                if (check_type != GEN_EMAIL)
938
0
                    continue;
939
0
                cstr = gen->d.rfc822Name;
940
0
                break;
941
0
            case GEN_DNS:
942
0
                if (check_type != GEN_DNS)
943
0
                    continue;
944
0
                cstr = gen->d.dNSName;
945
0
                break;
946
0
            case GEN_IPADD:
947
0
                if (check_type != GEN_IPADD)
948
0
                    continue;
949
0
                cstr = gen->d.iPAddress;
950
0
                break;
951
0
            }
952
            /* Positive on success, negative on error! */
953
0
            if ((rv = do_check_string(cstr, alt_type, equal, flags,
954
0
                     chk, chklen, peername))
955
0
                != 0)
956
0
                break;
957
0
        }
958
0
        GENERAL_NAMES_free(gens);
959
0
        if (rv != 0)
960
0
            return rv;
961
0
    }
962
963
    /*
964
     * The subject DN is not consulted by default: the subject commonName or
965
     * emailAddress is matched only when the caller explicitly opts in with
966
     * X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT, and never when
967
     * X509_CHECK_FLAG_NEVER_CHECK_SUBJECT is set.
968
     */
969
0
    if (cnid == NID_undef
970
0
        || (flags & X509_CHECK_FLAG_NEVER_CHECK_SUBJECT) != 0
971
0
        || (flags & X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT) == 0)
972
0
        return 0;
973
974
0
    i = -1;
975
0
    name = X509_get_subject_name(x);
976
0
    while ((i = X509_NAME_get_index_by_NID(name, cnid, i)) >= 0) {
977
0
        const X509_NAME_ENTRY *ne = X509_NAME_get_entry(name, i);
978
0
        const ASN1_STRING *str = X509_NAME_ENTRY_get_data(ne);
979
980
        /* Positive on success, negative on error! */
981
0
        if ((rv = do_check_string(str, -1, equal, flags,
982
0
                 chk, chklen, peername))
983
0
            != 0)
984
0
            return rv;
985
0
    }
986
0
    return 0;
987
0
}
988
989
int ossl_x509_check_host(const X509 *x, const char *chk, size_t chklen,
990
    unsigned int flags, char **peername)
991
0
{
992
0
    if (chk == NULL)
993
0
        return -2;
994
    /*
995
     * Embedded NULs are disallowed, except as the last character of a
996
     * string of length 2 or more (tolerate caller including terminating
997
     * NUL in string length).
998
     */
999
0
    if (chklen == 0)
1000
0
        chklen = strlen(chk);
1001
0
    else if (memchr(chk, '\0', chklen > 1 ? chklen - 1 : chklen))
1002
0
        return -2;
1003
0
    if (chklen > 1 && chk[chklen - 1] == '\0')
1004
0
        --chklen;
1005
0
    return do_x509_check(x, chk, chklen, flags, GEN_DNS, 0, peername);
1006
0
}
1007
1008
#if !defined(OPENSSL_NO_DEPRECATED_4_1)
1009
int X509_check_host(const X509 *x, const char *chk, size_t chklen,
1010
    unsigned int flags, char **peername)
1011
0
{
1012
0
    return ossl_x509_check_host(x, chk, chklen, flags, peername);
1013
0
}
1014
#endif /* !defined(OPENSSL_NO_DEPRECATED_4_1) */
1015
1016
int ossl_x509_check_rfc822(X509 *x, const char *chk, size_t chklen,
1017
    unsigned int flags)
1018
0
{
1019
0
    return do_x509_check(x, chk, chklen, flags, GEN_EMAIL, 0, NULL) == 1;
1020
0
}
1021
1022
int ossl_x509_check_smtputf8(X509 *x, const char *chk, size_t chklen,
1023
    unsigned int flags)
1024
0
{
1025
0
    return do_x509_check(x, chk, chklen, flags, GEN_OTHERNAME,
1026
0
               NID_id_on_SmtpUTF8Mailbox, NULL)
1027
0
        == 1;
1028
0
}
1029
1030
int ossl_x509_check_ip(const X509 *x, const unsigned char *chk, size_t chklen,
1031
    unsigned int flags)
1032
0
{
1033
0
    if (chk == NULL)
1034
0
        return -2;
1035
0
    return do_x509_check(x, (char *)chk, chklen, flags, GEN_IPADD, 0, NULL);
1036
0
}
1037
1038
#if !defined(OPENSSL_NO_DEPRECATED_4_1)
1039
int X509_check_email(const X509 *x, const char *chk, size_t chklen,
1040
    unsigned int flags)
1041
0
{
1042
0
    if (chk == NULL)
1043
0
        return -2;
1044
    /*
1045
     * Embedded NULs are disallowed, except as the last character of a
1046
     * string of length 2 or more (tolerate caller including terminating
1047
     * NUL in string length).
1048
     */
1049
0
    if (chklen == 0)
1050
0
        chklen = strlen((char *)chk);
1051
0
    else if (memchr(chk, '\0', chklen > 1 ? chklen - 1 : chklen))
1052
0
        return -2;
1053
0
    if (chklen > 1 && chk[chklen - 1] == '\0')
1054
0
        --chklen;
1055
    /*
1056
     * As this is public API, historically it has supported checking
1057
     * whatever is supplied against both RFC822 and SMTPUTF8.
1058
     */
1059
0
    if (do_x509_check(x, chk, chklen, flags, GEN_EMAIL, 0, NULL) == 1)
1060
0
        return 1;
1061
0
    return do_x509_check(x, chk, chklen, flags, GEN_OTHERNAME,
1062
0
        NID_id_on_SmtpUTF8Mailbox, NULL);
1063
0
}
1064
1065
int X509_check_ip(const X509 *x, const unsigned char *chk, size_t chklen,
1066
    unsigned int flags)
1067
0
{
1068
0
    return ossl_x509_check_ip(x, chk, chklen, flags);
1069
0
}
1070
1071
int X509_check_ip_asc(const X509 *x, const char *ipasc, unsigned int flags)
1072
0
{
1073
0
    unsigned char ipout[16];
1074
0
    size_t iplen;
1075
1076
0
    if (ipasc == NULL)
1077
0
        return -2;
1078
0
    iplen = (size_t)ossl_a2i_ipadd(ipout, ipasc);
1079
0
    if (iplen == 0)
1080
0
        return -2;
1081
0
    return do_x509_check(x, (char *)ipout, iplen, flags, GEN_IPADD, 0, NULL);
1082
0
}
1083
#endif /* !defined(OPENSSL_NO_DEPRECATED_4_1) */
1084
1085
char *ossl_ipaddr_to_asc(const unsigned char *p, int len)
1086
0
{
1087
    /*
1088
     * 40 is enough space for the longest IPv6 address + nul terminator byte
1089
     * XXXX:XXXX:XXXX:XXXX:XXXX:XXXX:XXXX:XXXX\0
1090
     */
1091
0
    char buf[40], *out;
1092
0
    int i = 0, remain = 0, bytes = 0;
1093
1094
0
    switch (len) {
1095
0
    case 4: /* IPv4 */
1096
0
        snprintf(buf, sizeof(buf), "%d.%d.%d.%d", p[0], p[1], p[2], p[3]);
1097
0
        break;
1098
0
    case 16: /* IPv6 */
1099
0
        for (out = buf, i = 8, remain = sizeof(buf);
1100
0
            i-- > 0 && bytes >= 0 && remain > 0;
1101
0
            remain -= bytes, out += bytes) {
1102
0
            const char *template = (i > 0 ? "%X:" : "%X");
1103
1104
0
            bytes = snprintf(out, remain, template, p[0] << 8 | p[1]);
1105
0
            p += 2;
1106
0
        }
1107
0
        break;
1108
0
    default:
1109
0
        snprintf(buf, sizeof(buf), "<invalid length=%d>", len);
1110
0
        break;
1111
0
    }
1112
0
    return OPENSSL_strdup(buf);
1113
0
}
1114
1115
/*
1116
 * Convert IP addresses both IPv4 and IPv6 into an OCTET STRING compatible
1117
 * with RFC3280.
1118
 */
1119
1120
ASN1_OCTET_STRING *a2i_IPADDRESS(const char *ipasc)
1121
0
{
1122
0
    unsigned char ipout[16];
1123
0
    ASN1_OCTET_STRING *ret;
1124
0
    int iplen;
1125
1126
    /* If string contains a ':' assume IPv6 */
1127
1128
0
    iplen = ossl_a2i_ipadd(ipout, ipasc);
1129
1130
0
    if (!iplen)
1131
0
        return NULL;
1132
1133
0
    ret = ASN1_OCTET_STRING_new();
1134
0
    if (ret == NULL)
1135
0
        return NULL;
1136
0
    if (!ASN1_OCTET_STRING_set(ret, ipout, iplen)) {
1137
0
        ASN1_OCTET_STRING_free(ret);
1138
0
        return NULL;
1139
0
    }
1140
0
    return ret;
1141
0
}
1142
1143
ASN1_OCTET_STRING *a2i_IPADDRESS_NC(const char *ipasc)
1144
0
{
1145
0
    ASN1_OCTET_STRING *ret = NULL;
1146
0
    unsigned char ipout[32];
1147
0
    char *iptmp = NULL, *p;
1148
0
    const char *slash;
1149
0
    int iplen1, iplen2;
1150
1151
0
    slash = strchr(ipasc, '/');
1152
0
    if (slash == NULL)
1153
0
        return NULL;
1154
0
    iptmp = OPENSSL_strdup(ipasc);
1155
0
    if (iptmp == NULL)
1156
0
        return NULL;
1157
0
    p = iptmp + (slash - ipasc);
1158
0
    *p++ = 0;
1159
1160
0
    iplen1 = ossl_a2i_ipadd(ipout, iptmp);
1161
1162
0
    if (!iplen1)
1163
0
        goto err;
1164
1165
0
    iplen2 = ossl_a2i_ipadd(ipout + iplen1, p);
1166
1167
0
    OPENSSL_free(iptmp);
1168
0
    iptmp = NULL;
1169
1170
0
    if (!iplen2 || (iplen1 != iplen2))
1171
0
        goto err;
1172
1173
0
    ret = ASN1_OCTET_STRING_new();
1174
0
    if (ret == NULL)
1175
0
        goto err;
1176
0
    if (!ASN1_OCTET_STRING_set(ret, ipout, iplen1 + iplen2))
1177
0
        goto err;
1178
1179
0
    return ret;
1180
1181
0
err:
1182
0
    OPENSSL_free(iptmp);
1183
0
    ASN1_OCTET_STRING_free(ret);
1184
0
    return NULL;
1185
0
}
1186
1187
int ossl_a2i_ipadd(unsigned char *ipout, const char *ipasc)
1188
0
{
1189
    /* If string contains a ':' assume IPv6 */
1190
1191
0
    if (strchr(ipasc, ':')) {
1192
0
        if (!ipv6_from_asc(ipout, ipasc))
1193
0
            return 0;
1194
0
        return 16;
1195
0
    } else {
1196
0
        if (!ipv4_from_asc(ipout, ipasc))
1197
0
            return 0;
1198
0
        return 4;
1199
0
    }
1200
0
}
1201
1202
/*
1203
 * get_ipv4_component consumes one IPv4 component, terminated by either '.' or
1204
 * the end of the string, from *str. On success, it returns one, sets *out
1205
 * to the component, and advances *str to the first unconsumed character. On
1206
 * invalid input, it returns zero.
1207
 */
1208
static int get_ipv4_component(uint8_t *out_byte, const char **str)
1209
0
{
1210
    /* Store a slightly larger intermediary so the overflow check is easier. */
1211
0
    uint32_t out = 0;
1212
1213
0
    for (;;) {
1214
0
        if (!ossl_isdigit(**str)) {
1215
0
            return 0;
1216
0
        }
1217
0
        out = (out * 10) + (**str - '0');
1218
0
        if (out > 255) {
1219
            /* Components must be 8-bit. */
1220
0
            return 0;
1221
0
        }
1222
0
        (*str)++;
1223
0
        if ((**str) == '.' || (**str) == '\0') {
1224
0
            *out_byte = (uint8_t)out;
1225
0
            return 1;
1226
0
        }
1227
0
        if (out == 0) {
1228
            /* Reject extra leading zeros. Parsers sometimes treat them as
1229
             * octal, so accepting them would misinterpret input.
1230
             */
1231
0
            return 0;
1232
0
        }
1233
0
    }
1234
0
}
1235
1236
/*
1237
 * get_ipv4_dot consumes a '.' from *str and advances it. It returns one on
1238
 * success and zero if *str does not point to a '.'.
1239
 */
1240
static int get_ipv4_dot(const char **str)
1241
0
{
1242
0
    if (**str != '.') {
1243
0
        return 0;
1244
0
    }
1245
0
    (*str)++;
1246
0
    return 1;
1247
0
}
1248
1249
static int ipv4_from_asc(unsigned char *v4, const char *in)
1250
0
{
1251
0
    if (!get_ipv4_component(&v4[0], &in) || !get_ipv4_dot(&in)
1252
0
        || !get_ipv4_component(&v4[1], &in) || !get_ipv4_dot(&in)
1253
0
        || !get_ipv4_component(&v4[2], &in) || !get_ipv4_dot(&in)
1254
0
        || !get_ipv4_component(&v4[3], &in) || *in != '\0') {
1255
0
        return 0;
1256
0
    }
1257
0
    return 1;
1258
0
}
1259
1260
typedef struct {
1261
    /* Temporary store for IPV6 output */
1262
    unsigned char tmp[16];
1263
    /* Total number of bytes in tmp */
1264
    int total;
1265
    /* The position of a zero (corresponding to '::') */
1266
    int zero_pos;
1267
    /* Number of zeroes */
1268
    int zero_cnt;
1269
} IPV6_STAT;
1270
1271
static int ipv6_from_asc(unsigned char *v6, const char *in)
1272
0
{
1273
0
    IPV6_STAT v6stat;
1274
1275
0
    v6stat.total = 0;
1276
0
    v6stat.zero_pos = -1;
1277
0
    v6stat.zero_cnt = 0;
1278
    /*
1279
     * Treat the IPv6 representation as a list of values separated by ':'.
1280
     * The presence of a '::' will parse as one, two or three zero length
1281
     * elements.
1282
     */
1283
0
    if (!CONF_parse_list(in, ':', 0, ipv6_cb, &v6stat))
1284
0
        return 0;
1285
1286
    /* Now for some sanity checks */
1287
1288
0
    if (v6stat.zero_pos == -1) {
1289
        /* If no '::' must have exactly 16 bytes */
1290
0
        if (v6stat.total != 16)
1291
0
            return 0;
1292
0
    } else {
1293
        /* If '::' must have less than 16 bytes */
1294
0
        if (v6stat.total == 16)
1295
0
            return 0;
1296
        /* More than three zeroes is an error */
1297
0
        if (v6stat.zero_cnt > 3) {
1298
0
            return 0;
1299
            /* Can only have three zeroes if nothing else present */
1300
0
        } else if (v6stat.zero_cnt == 3) {
1301
0
            if (v6stat.total > 0)
1302
0
                return 0;
1303
0
        } else if (v6stat.zero_cnt == 2) {
1304
            /* Can only have two zeroes if at start or end */
1305
0
            if ((v6stat.zero_pos != 0)
1306
0
                && (v6stat.zero_pos != v6stat.total))
1307
0
                return 0;
1308
0
        } else {
1309
            /* Can only have one zero if *not* start or end */
1310
0
            if ((v6stat.zero_pos == 0)
1311
0
                || (v6stat.zero_pos == v6stat.total))
1312
0
                return 0;
1313
0
        }
1314
0
    }
1315
1316
    /* Format result */
1317
1318
0
    if (v6stat.zero_pos >= 0) {
1319
        /* Copy initial part */
1320
0
        memcpy(v6, v6stat.tmp, v6stat.zero_pos);
1321
        /* Zero middle */
1322
0
        memset(v6 + v6stat.zero_pos, 0, 16 - v6stat.total);
1323
        /* Copy final part */
1324
0
        if (v6stat.total != v6stat.zero_pos)
1325
0
            memcpy(v6 + v6stat.zero_pos + 16 - v6stat.total,
1326
0
                v6stat.tmp + v6stat.zero_pos,
1327
0
                v6stat.total - v6stat.zero_pos);
1328
0
    } else {
1329
0
        memcpy(v6, v6stat.tmp, 16);
1330
0
    }
1331
1332
0
    return 1;
1333
0
}
1334
1335
static int ipv6_cb(const char *elem, int len, void *usr)
1336
0
{
1337
0
    IPV6_STAT *s = usr;
1338
1339
    /* Error if 16 bytes written */
1340
0
    if (s->total == 16)
1341
0
        return 0;
1342
0
    if (len == 0) {
1343
        /* Zero length element, corresponds to '::' */
1344
0
        if (s->zero_pos == -1)
1345
0
            s->zero_pos = s->total;
1346
        /* If we've already got a :: its an error */
1347
0
        else if (s->zero_pos != s->total)
1348
0
            return 0;
1349
0
        s->zero_cnt++;
1350
0
    } else {
1351
        /* If more than 4 characters could be final a.b.c.d form */
1352
0
        if (len > 4) {
1353
            /* Need at least 4 bytes left */
1354
0
            if (s->total > 12)
1355
0
                return 0;
1356
            /* Must be end of string */
1357
0
            if (elem[len])
1358
0
                return 0;
1359
0
            if (!ipv4_from_asc(s->tmp + s->total, elem))
1360
0
                return 0;
1361
0
            s->total += 4;
1362
0
        } else {
1363
0
            if (!ipv6_hex(s->tmp + s->total, elem, len))
1364
0
                return 0;
1365
0
            s->total += 2;
1366
0
        }
1367
0
    }
1368
0
    return 1;
1369
0
}
1370
1371
/*
1372
 * Convert a string of up to 4 hex digits into the corresponding IPv6 form.
1373
 */
1374
1375
static int ipv6_hex(unsigned char *out, const char *in, int inlen)
1376
0
{
1377
0
    unsigned char c;
1378
0
    unsigned int num = 0;
1379
0
    int x;
1380
1381
0
    if (inlen > 4)
1382
0
        return 0;
1383
0
    while (inlen--) {
1384
0
        c = *in++;
1385
0
        num <<= 4;
1386
0
        x = OPENSSL_hexchar2int(c);
1387
0
        if (x < 0)
1388
0
            return 0;
1389
0
        num |= (char)x;
1390
0
    }
1391
0
    out[0] = num >> 8;
1392
0
    out[1] = num & 0xff;
1393
0
    return 1;
1394
0
}
1395
1396
int X509V3_NAME_from_section(X509_NAME *nm, STACK_OF(CONF_VALUE) *dn_sk,
1397
    unsigned long chtype)
1398
0
{
1399
0
    CONF_VALUE *v;
1400
0
    int i, mval, spec_char, plus_char;
1401
0
    char *p, *type;
1402
1403
0
    if (!nm)
1404
0
        return 0;
1405
1406
0
    for (i = 0; i < sk_CONF_VALUE_num(dn_sk); i++) {
1407
0
        v = sk_CONF_VALUE_value(dn_sk, i);
1408
0
        type = v->name;
1409
        /*
1410
         * Skip past any leading X. X: X, etc to allow for multiple instances
1411
         */
1412
0
        for (p = type; *p; p++) {
1413
0
#ifndef CHARSET_EBCDIC
1414
0
            spec_char = ((*p == ':') || (*p == ',') || (*p == '.'));
1415
#else
1416
            spec_char = ((*p == os_toascii[':']) || (*p == os_toascii[','])
1417
                || (*p == os_toascii['.']));
1418
#endif
1419
0
            if (spec_char) {
1420
0
                p++;
1421
0
                if (*p)
1422
0
                    type = p;
1423
0
                break;
1424
0
            }
1425
0
        }
1426
0
#ifndef CHARSET_EBCDIC
1427
0
        plus_char = (*type == '+');
1428
#else
1429
        plus_char = (*type == os_toascii['+']);
1430
#endif
1431
0
        if (plus_char) {
1432
0
            mval = -1;
1433
0
            type++;
1434
0
        } else {
1435
0
            mval = 0;
1436
0
        }
1437
0
        if (!X509_NAME_add_entry_by_txt(nm, type, chtype,
1438
0
                (unsigned char *)v->value, -1, -1,
1439
0
                mval))
1440
0
            return 0;
1441
0
    }
1442
0
    return 1;
1443
0
}
1444
1445
int OSSL_GENERAL_NAMES_print(BIO *out, GENERAL_NAMES *gens, int indent)
1446
0
{
1447
0
    int i;
1448
1449
0
    for (i = 0; i < sk_GENERAL_NAME_num(gens); i++) {
1450
0
        if (i > 0)
1451
0
            BIO_puts(out, "\n");
1452
0
        BIO_printf(out, "%*s", indent + 2, "");
1453
0
        GENERAL_NAME_print(out, sk_GENERAL_NAME_value(gens, i));
1454
0
    }
1455
0
    return 1;
1456
0
}
1457
1458
int ossl_bio_print_hex(BIO *out, unsigned char *buf, int len)
1459
0
{
1460
0
    int result;
1461
0
    char *hexbuf;
1462
1463
0
    if (len == 0)
1464
0
        return 1;
1465
1466
0
    hexbuf = OPENSSL_buf2hexstr(buf, len);
1467
0
    if (hexbuf == NULL)
1468
0
        return 0;
1469
0
    result = BIO_puts(out, hexbuf) > 0;
1470
1471
0
    OPENSSL_free(hexbuf);
1472
0
    return result;
1473
0
}