Coverage Report

Created: 2026-03-09 06:55

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/openssl/crypto/evp/bio_b64.c
Line
Count
Source
1
/*
2
 * Copyright 1995-2025 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
#include <stdio.h>
11
#include <errno.h>
12
#include "internal/cryptlib.h"
13
#include <openssl/buffer.h>
14
#include <openssl/evp.h>
15
#include "internal/bio.h"
16
#include "crypto/evp.h"
17
18
static int b64_write(BIO *h, const char *buf, int num);
19
static int b64_read(BIO *h, char *buf, int size);
20
static int b64_puts(BIO *h, const char *str);
21
static long b64_ctrl(BIO *h, int cmd, long arg1, void *arg2);
22
static int b64_new(BIO *h);
23
static int b64_free(BIO *data);
24
static long b64_callback_ctrl(BIO *h, int cmd, BIO_info_cb *fp);
25
0
#define B64_BLOCK_SIZE 1024
26
#define B64_BLOCK_SIZE2 768
27
0
#define B64_NONE 0
28
0
#define B64_ENCODE 1
29
0
#define B64_DECODE 2
30
31
typedef struct b64_struct {
32
    /*
33
     * BIO *bio; moved to the BIO structure
34
     */
35
    int buf_len;
36
    int buf_off;
37
    int tmp_len; /* used to find the start when decoding */
38
    int tmp_nl; /* If true, scan until '\n' */
39
    int encode;
40
    int start; /* have we started decoding yet? */
41
    int cont; /* <= 0 when finished */
42
    EVP_ENCODE_CTX *base64;
43
    unsigned char buf[EVP_ENCODE_LENGTH(B64_BLOCK_SIZE) + 10];
44
    unsigned char tmp[B64_BLOCK_SIZE];
45
    unsigned char *encoded_buf;
46
    size_t encoded_buf_len;
47
} BIO_B64_CTX;
48
49
static const BIO_METHOD methods_b64 = {
50
    BIO_TYPE_BASE64,
51
    "base64 encoding",
52
    bwrite_conv,
53
    b64_write,
54
    bread_conv,
55
    b64_read,
56
    b64_puts,
57
    NULL, /* b64_gets, */
58
    b64_ctrl,
59
    b64_new,
60
    b64_free,
61
    b64_callback_ctrl,
62
};
63
64
const BIO_METHOD *BIO_f_base64(void)
65
0
{
66
0
    return &methods_b64;
67
0
}
68
69
static int b64_new(BIO *bi)
70
0
{
71
0
    BIO_B64_CTX *ctx;
72
73
0
    if ((ctx = OPENSSL_zalloc(sizeof(*ctx))) == NULL)
74
0
        return 0;
75
76
0
    ctx->cont = 1;
77
0
    ctx->start = 1;
78
0
    ctx->encoded_buf = NULL;
79
0
    ctx->encoded_buf_len = 0;
80
0
    ctx->base64 = EVP_ENCODE_CTX_new();
81
0
    if (ctx->base64 == NULL) {
82
0
        OPENSSL_free(ctx);
83
0
        return 0;
84
0
    }
85
86
0
    BIO_set_data(bi, ctx);
87
0
    BIO_set_init(bi, 1);
88
89
0
    return 1;
90
0
}
91
92
static int b64_free(BIO *a)
93
0
{
94
0
    BIO_B64_CTX *ctx;
95
96
0
    if (a == NULL)
97
0
        return 0;
98
99
0
    ctx = BIO_get_data(a);
100
0
    if (ctx == NULL)
101
0
        return 0;
102
103
0
    OPENSSL_free(ctx->encoded_buf);
104
0
    ctx->encoded_buf = NULL;
105
0
    ctx->encoded_buf_len = 0;
106
0
    EVP_ENCODE_CTX_free(ctx->base64);
107
0
    OPENSSL_free(ctx);
108
0
    BIO_set_data(a, NULL);
109
0
    BIO_set_init(a, 0);
110
111
0
    return 1;
112
0
}
113
114
/*
115
 * Unless `BIO_FLAGS_BASE64_NO_NL` is set, this BIO ignores leading lines that
116
 * aren't exclusively composed of valid Base64 characters (followed by <CRLF>
117
 * or <LF>).  Once a valid Base64 line is found, `ctx->start` is set to 0 and
118
 * lines are processed until EOF or the first line that contains invalid Base64
119
 * characters.  In a nod to PEM, lines that start with a '-' (hyphen) are
120
 * treated as a soft EOF, rather than an error.
121
 */
122
static int b64_read(BIO *b, char *out, int outl)
123
0
{
124
0
    int ret = 0, i, ii, j, k, x, n, num, ret_code;
125
0
    BIO_B64_CTX *ctx;
126
0
    unsigned char *p, *q;
127
0
    BIO *next;
128
129
0
    if (out == NULL)
130
0
        return 0;
131
0
    ctx = (BIO_B64_CTX *)BIO_get_data(b);
132
133
0
    next = BIO_next(b);
134
0
    if (ctx == NULL || next == NULL)
135
0
        return 0;
136
137
0
    BIO_clear_retry_flags(b);
138
139
0
    if (ctx->encode != B64_DECODE) {
140
0
        ctx->encode = B64_DECODE;
141
0
        ctx->buf_len = 0;
142
0
        ctx->buf_off = 0;
143
0
        ctx->tmp_len = 0;
144
0
        EVP_DecodeInit(ctx->base64);
145
0
    }
146
147
    /* First check if there are buffered bytes already decoded */
148
0
    if (ctx->buf_len > 0) {
149
0
        if (!ossl_assert(ctx->buf_len >= ctx->buf_off)) {
150
0
            ERR_raise(ERR_LIB_BIO, ERR_R_INTERNAL_ERROR);
151
0
            return -1;
152
0
        }
153
0
        i = ctx->buf_len - ctx->buf_off;
154
0
        if (i > outl)
155
0
            i = outl;
156
0
        if (!ossl_assert(ctx->buf_off + i < (int)sizeof(ctx->buf))) {
157
0
            ERR_raise(ERR_LIB_BIO, ERR_R_INTERNAL_ERROR);
158
0
            return -1;
159
0
        }
160
0
        memcpy(out, &(ctx->buf[ctx->buf_off]), i);
161
0
        ret = i;
162
0
        out += i;
163
0
        outl -= i;
164
0
        ctx->buf_off += i;
165
0
        if (ctx->buf_len == ctx->buf_off) {
166
0
            ctx->buf_len = 0;
167
0
            ctx->buf_off = 0;
168
0
        }
169
0
    }
170
171
    /* Restore any non-retriable error condition (ctx->cont < 0) */
172
0
    ret_code = ctx->cont < 0 ? ctx->cont : 0;
173
174
    /*
175
     * At this point, we have room of outl bytes and an either an empty buffer,
176
     * or outl == 0, so we'll attempt to read in some more.
177
     */
178
0
    while (outl > 0) {
179
0
        int again = ctx->cont;
180
181
0
        if (again <= 0)
182
0
            break;
183
184
0
        i = BIO_read(next, &(ctx->tmp[ctx->tmp_len]),
185
0
            B64_BLOCK_SIZE - ctx->tmp_len);
186
187
0
        if (i <= 0) {
188
0
            ret_code = i;
189
190
            /* Should we continue next time we are called? */
191
0
            if (!BIO_should_retry(next)) {
192
                /* Incomplete final Base64 chunk in the decoder is an error */
193
0
                if (ctx->tmp_len == 0) {
194
0
                    if (EVP_DecodeFinal(ctx->base64, NULL, &num) < 0)
195
0
                        ret_code = -1;
196
0
                    EVP_DecodeInit(ctx->base64);
197
0
                }
198
0
                ctx->cont = ret_code;
199
0
            }
200
0
            if (ctx->tmp_len == 0)
201
0
                break;
202
            /* Fall through and process what we have */
203
0
            i = 0;
204
            /* But don't loop to top-up even if the buffer is not full! */
205
0
            again = 0;
206
0
        }
207
208
0
        i += ctx->tmp_len;
209
0
        ctx->tmp_len = i;
210
211
        /*
212
         * We need to scan, a line at a time until we have a valid line if we
213
         * are starting.
214
         */
215
0
        if (ctx->start && (BIO_get_flags(b) & BIO_FLAGS_BASE64_NO_NL) != 0) {
216
0
            ctx->tmp_len = 0;
217
0
        } else if (ctx->start) {
218
0
            q = p = ctx->tmp;
219
0
            num = 0;
220
0
            for (j = 0; j < i; j++) {
221
0
                if (*(q++) != '\n')
222
0
                    continue;
223
224
                /*
225
                 * due to a previous very long line, we need to keep on
226
                 * scanning for a '\n' before we even start looking for
227
                 * base64 encoded stuff.
228
                 */
229
0
                if (ctx->tmp_nl) {
230
0
                    p = q;
231
0
                    ctx->tmp_nl = 0;
232
0
                    continue;
233
0
                }
234
235
0
                k = EVP_DecodeUpdate(ctx->base64, ctx->buf, &num, p, (int)(q - p));
236
0
                EVP_DecodeInit(ctx->base64);
237
0
                if (k <= 0 && num == 0) {
238
0
                    p = q;
239
0
                    continue;
240
0
                }
241
242
0
                ctx->start = 0;
243
0
                if (p != ctx->tmp) {
244
0
                    i -= (int)(p - ctx->tmp);
245
0
                    for (x = 0; x < i; x++)
246
0
                        ctx->tmp[x] = p[x];
247
0
                }
248
0
                break;
249
0
            }
250
251
            /* we fell off the end without starting */
252
0
            if (ctx->start) {
253
                /*
254
                 * Is this is one long chunk?, if so, keep on reading until a
255
                 * new line.
256
                 */
257
0
                if (p == ctx->tmp) {
258
                    /* Check buffer full */
259
0
                    if (i == B64_BLOCK_SIZE) {
260
0
                        ctx->tmp_nl = 1;
261
0
                        ctx->tmp_len = 0;
262
0
                    }
263
0
                } else if (p != q) {
264
                    /* Retain partial line at end of buffer */
265
0
                    n = (int)(q - p);
266
0
                    for (ii = 0; ii < n; ii++)
267
0
                        ctx->tmp[ii] = p[ii];
268
0
                    ctx->tmp_len = n;
269
0
                } else {
270
                    /* All we have is newline terminated non-start data */
271
0
                    ctx->tmp_len = 0;
272
0
                }
273
                /*
274
                 * Try to read more if possible, otherwise we can't make
275
                 * progress unless the underlying BIO is retriable and may
276
                 * produce more data next time we're called.
277
                 */
278
0
                if (again > 0)
279
0
                    continue;
280
0
                else
281
0
                    break;
282
0
            } else {
283
0
                ctx->tmp_len = 0;
284
0
            }
285
0
        } else if (i < B64_BLOCK_SIZE && again > 0) {
286
            /*
287
             * If buffer isn't full and we can retry then restart to read in
288
             * more data.
289
             */
290
0
            continue;
291
0
        }
292
293
0
        i = EVP_DecodeUpdate(ctx->base64, ctx->buf, &ctx->buf_len,
294
0
            ctx->tmp, i);
295
0
        ctx->tmp_len = 0;
296
        /*
297
         * If eof or an error was signalled, then the condition
298
         * 'ctx->cont <= 0' will prevent b64_read() from reading
299
         * more data on subsequent calls. This assignment was
300
         * deleted accidentally in commit 5562cfaca4f3.
301
         */
302
0
        ctx->cont = i;
303
304
0
        ctx->buf_off = 0;
305
0
        if (i < 0) {
306
0
            ret_code = ctx->start ? 0 : i;
307
0
            ctx->buf_len = 0;
308
0
            break;
309
0
        }
310
311
0
        if (ctx->buf_len <= outl)
312
0
            i = ctx->buf_len;
313
0
        else
314
0
            i = outl;
315
316
0
        memcpy(out, ctx->buf, i);
317
0
        ret += i;
318
0
        ctx->buf_off = i;
319
0
        if (ctx->buf_off == ctx->buf_len) {
320
0
            ctx->buf_len = 0;
321
0
            ctx->buf_off = 0;
322
0
        }
323
0
        outl -= i;
324
0
        out += i;
325
0
    }
326
0
    BIO_copy_next_retry(b);
327
0
    return ret == 0 ? ret_code : ret;
328
0
}
329
330
static int b64_write(BIO *b, const char *in, int inl)
331
0
{
332
0
    int ret = 0;
333
0
    int n;
334
0
    int i;
335
0
    BIO_B64_CTX *ctx;
336
0
    BIO *next;
337
0
    int encoded_length;
338
0
    unsigned char *encoded;
339
0
    int n_bytes_enc;
340
341
0
    ctx = (BIO_B64_CTX *)BIO_get_data(b);
342
0
    next = BIO_next(b);
343
0
    if (ctx == NULL || next == NULL)
344
0
        return 0;
345
346
0
    BIO_clear_retry_flags(b);
347
348
0
    if (ctx->encode != B64_ENCODE) {
349
0
        ctx->encode = B64_ENCODE;
350
0
        ctx->buf_len = 0;
351
0
        ctx->buf_off = 0;
352
0
        ctx->tmp_len = 0;
353
0
        EVP_EncodeInit(ctx->base64);
354
0
        if (BIO_get_flags(b) & BIO_FLAGS_BASE64_NO_NL)
355
0
            evp_encode_ctx_set_flags(ctx->base64, EVP_ENCODE_CTX_NO_NEWLINES);
356
0
    }
357
0
    if (!ossl_assert(ctx->buf_off < (int)sizeof(ctx->buf))) {
358
0
        ERR_raise(ERR_LIB_BIO, ERR_R_INTERNAL_ERROR);
359
0
        return -1;
360
0
    }
361
0
    if (!ossl_assert(ctx->buf_len <= (int)sizeof(ctx->buf))) {
362
0
        ERR_raise(ERR_LIB_BIO, ERR_R_INTERNAL_ERROR);
363
0
        return -1;
364
0
    }
365
0
    if (!ossl_assert(ctx->buf_len >= ctx->buf_off)) {
366
0
        ERR_raise(ERR_LIB_BIO, ERR_R_INTERNAL_ERROR);
367
0
        return -1;
368
0
    }
369
0
    n = ctx->buf_len - ctx->buf_off;
370
0
    while (n > 0) {
371
0
        i = BIO_write(next, &(ctx->buf[ctx->buf_off]), n);
372
0
        if (i <= 0) {
373
0
            BIO_copy_next_retry(b);
374
0
            return i;
375
0
        }
376
0
        ctx->buf_off += i;
377
0
        if (!ossl_assert(ctx->buf_off <= (int)sizeof(ctx->buf))) {
378
0
            ERR_raise(ERR_LIB_BIO, ERR_R_INTERNAL_ERROR);
379
0
            return -1;
380
0
        }
381
0
        if (!ossl_assert(ctx->buf_len >= ctx->buf_off)) {
382
0
            ERR_raise(ERR_LIB_BIO, ERR_R_INTERNAL_ERROR);
383
0
            return -1;
384
0
        }
385
0
        n -= i;
386
0
    }
387
    /* at this point all pending data has been written */
388
0
    ctx->buf_off = 0;
389
0
    ctx->buf_len = 0;
390
391
0
    if (in == NULL || inl <= 0)
392
0
        return 0;
393
394
0
    encoded_length = EVP_ENCODE_LENGTH(inl);
395
396
0
    if (ctx->encoded_buf == NULL || (size_t)encoded_length > ctx->encoded_buf_len) {
397
0
        OPENSSL_free(ctx->encoded_buf);
398
0
        ctx->encoded_buf = OPENSSL_malloc(encoded_length);
399
0
        if (ctx->encoded_buf == NULL) {
400
0
            ERR_raise(ERR_LIB_BIO, ERR_R_MALLOC_FAILURE);
401
0
            return -1;
402
0
        }
403
0
        ctx->encoded_buf_len = encoded_length;
404
0
    }
405
406
0
    encoded = ctx->encoded_buf;
407
408
0
    if (encoded == NULL) {
409
0
        ERR_raise(ERR_LIB_BIO, ERR_R_MALLOC_FAILURE);
410
0
        return -1;
411
0
    }
412
0
    n_bytes_enc = 0;
413
0
    if (!EVP_EncodeUpdate(ctx->base64, encoded, &n_bytes_enc,
414
0
            (unsigned char *)in, inl)) {
415
0
        return -1;
416
0
    }
417
0
    ret += inl;
418
0
    i = BIO_write(next, encoded, n_bytes_enc);
419
0
    if (i <= 0)
420
0
        BIO_copy_next_retry(b);
421
0
    return ret;
422
0
}
423
424
static long b64_ctrl(BIO *b, int cmd, long num, void *ptr)
425
0
{
426
0
    BIO_B64_CTX *ctx;
427
0
    long ret = 1;
428
0
    int i;
429
0
    BIO *next;
430
431
0
    ctx = (BIO_B64_CTX *)BIO_get_data(b);
432
0
    next = BIO_next(b);
433
    /*
434
     * If there is no ctx or no next BIO, BIO_read() returns 0, which means EOF.
435
     * BIO_eof() should return 1 in this case.
436
     */
437
0
    if (ctx == NULL || next == NULL)
438
0
        return cmd == BIO_CTRL_EOF;
439
440
0
    switch (cmd) {
441
0
    case BIO_CTRL_RESET:
442
0
        ctx->cont = 1;
443
0
        ctx->start = 1;
444
0
        ctx->encode = B64_NONE;
445
0
        ret = BIO_ctrl(next, cmd, num, ptr);
446
0
        break;
447
0
    case BIO_CTRL_EOF: /* More to read */
448
0
        if (ctx->cont <= 0)
449
0
            ret = 1;
450
0
        else
451
0
            ret = BIO_ctrl(next, cmd, num, ptr);
452
0
        break;
453
0
    case BIO_CTRL_WPENDING: /* More to write in buffer */
454
0
        if (!ossl_assert(ctx->buf_len >= ctx->buf_off)) {
455
0
            ERR_raise(ERR_LIB_BIO, ERR_R_INTERNAL_ERROR);
456
0
            return -1;
457
0
        }
458
0
        ret = ctx->buf_len - ctx->buf_off;
459
0
        if (ret == 0 && ctx->encode != B64_NONE
460
0
            && EVP_ENCODE_CTX_num(ctx->base64) != 0)
461
0
            ret = 1;
462
0
        else if (ret <= 0)
463
0
            ret = BIO_ctrl(next, cmd, num, ptr);
464
0
        break;
465
0
    case BIO_CTRL_PENDING: /* More to read in buffer */
466
0
        if (!ossl_assert(ctx->buf_len >= ctx->buf_off)) {
467
0
            ERR_raise(ERR_LIB_BIO, ERR_R_INTERNAL_ERROR);
468
0
            return -1;
469
0
        }
470
0
        ret = ctx->buf_len - ctx->buf_off;
471
0
        if (ret <= 0)
472
0
            ret = BIO_ctrl(next, cmd, num, ptr);
473
0
        break;
474
0
    case BIO_CTRL_FLUSH:
475
0
        if (ctx->encode == B64_ENCODE) {
476
            /* do a final write */
477
0
        again:
478
0
            while (ctx->buf_len != ctx->buf_off) {
479
0
                i = b64_write(b, NULL, 0);
480
0
                if (i < 0)
481
0
                    return i;
482
0
            }
483
0
            if (EVP_ENCODE_CTX_num(ctx->base64) != 0) {
484
0
                ctx->buf_off = 0;
485
0
                EVP_EncodeFinal(ctx->base64, ctx->buf, &(ctx->buf_len));
486
                /* push out the bytes */
487
0
                goto again;
488
0
            }
489
0
        }
490
        /* Finally flush the underlying BIO */
491
0
        BIO_clear_retry_flags(b);
492
0
        ret = BIO_ctrl(next, cmd, num, ptr);
493
0
        BIO_copy_next_retry(b);
494
0
        break;
495
496
0
    case BIO_C_DO_STATE_MACHINE:
497
0
        BIO_clear_retry_flags(b);
498
0
        ret = BIO_ctrl(next, cmd, num, ptr);
499
0
        BIO_copy_next_retry(b);
500
0
        break;
501
502
0
    case BIO_CTRL_DUP:
503
0
        break;
504
0
    case BIO_CTRL_INFO:
505
0
    case BIO_CTRL_GET:
506
0
    case BIO_CTRL_SET:
507
0
    default:
508
0
        ret = BIO_ctrl(next, cmd, num, ptr);
509
0
        break;
510
0
    }
511
0
    return ret;
512
0
}
513
514
static long b64_callback_ctrl(BIO *b, int cmd, BIO_info_cb *fp)
515
0
{
516
0
    BIO *next = BIO_next(b);
517
518
0
    if (next == NULL)
519
0
        return 0;
520
521
0
    return BIO_callback_ctrl(next, cmd, fp);
522
0
}
523
524
static int b64_puts(BIO *b, const char *str)
525
0
{
526
0
    size_t len = strlen(str);
527
528
0
    if (len > INT_MAX)
529
0
        return -1;
530
0
    return b64_write(b, str, (int)len);
531
0
}