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