Coverage Report

Created: 2026-10-31 06:20

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/boringssl/crypto/base64/base64.cc
Line
Count
Source
1
// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
2
//
3
// Licensed under the Apache License, Version 2.0 (the "License");
4
// you may not use this file except in compliance with the License.
5
// You may obtain a copy of the License at
6
//
7
//     https://www.apache.org/licenses/LICENSE-2.0
8
//
9
// Unless required by applicable law or agreed to in writing, software
10
// distributed under the License is distributed on an "AS IS" BASIS,
11
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
// See the License for the specific language governing permissions and
13
// limitations under the License.
14
15
#include <openssl/base64.h>
16
17
#include <assert.h>
18
#include <limits.h>
19
#include <string.h>
20
21
#include "../internal.h"
22
#include "../mem_internal.h"
23
24
25
using namespace bssl;
26
27
// constant_time_lt_args_8 behaves like `constant_time_lt_8` but takes `uint8_t`
28
// arguments for a slightly simpler implementation.
29
5.70M
static uint8_t constant_time_lt_args_8(uint8_t a, uint8_t b) {
30
5.70M
  crypto_word_t aw = a;
31
5.70M
  crypto_word_t bw = b;
32
  // `crypto_word_t` is larger than `uint8_t`, so `aw` and `bw` have the same
33
  // MSB. `aw` < `bw` iff MSB(`aw` - `bw`) is 1.
34
5.70M
  return constant_time_msb_w(aw - bw);
35
5.70M
}
36
37
// constant_time_in_range_8 returns `CONSTTIME_TRUE_8` if `min` <= `a` <= `max`
38
// and `CONSTTIME_FALSE_8` otherwise.
39
5.70M
static uint8_t constant_time_in_range_8(uint8_t a, uint8_t min, uint8_t max) {
40
5.70M
  a -= min;
41
5.70M
  return constant_time_lt_args_8(a, max - min + 1);
42
5.70M
}
43
44
// Encoding.
45
46
0
static uint8_t conv_bin2ascii(uint8_t a) {
47
  // Since PEM is sometimes used to carry private keys, we encode base64 data
48
  // itself in constant-time.
49
0
  a &= 0x3f;
50
0
  uint8_t ret = constant_time_select_8(constant_time_eq_8(a, 62), '+', '/');
51
0
  ret =
52
0
      constant_time_select_8(constant_time_lt_args_8(a, 62), a - 52 + '0', ret);
53
0
  ret =
54
0
      constant_time_select_8(constant_time_lt_args_8(a, 52), a - 26 + 'a', ret);
55
0
  ret = constant_time_select_8(constant_time_lt_args_8(a, 26), a + 'A', ret);
56
0
  return ret;
57
0
}
58
59
static_assert(sizeof(((EVP_ENCODE_CTX *)nullptr)->data) % 3 == 0,
60
              "data length must be a multiple of base64 chunk size");
61
62
0
int EVP_EncodedLength(size_t *out_len, size_t len) {
63
0
  if (len + 2 < len) {
64
0
    return 0;
65
0
  }
66
0
  len += 2;
67
0
  len /= 3;
68
69
0
  if (((len << 2) >> 2) != len) {
70
0
    return 0;
71
0
  }
72
0
  len <<= 2;
73
74
0
  if (len + 1 < len) {
75
0
    return 0;
76
0
  }
77
0
  len++;
78
79
0
  *out_len = len;
80
0
  return 1;
81
0
}
82
83
0
EVP_ENCODE_CTX *EVP_ENCODE_CTX_new() { return New<EVP_ENCODE_CTX>(); }
84
85
0
void EVP_ENCODE_CTX_free(EVP_ENCODE_CTX *ctx) { Delete(ctx); }
86
87
0
void EVP_EncodeInit(EVP_ENCODE_CTX *ctx) {
88
0
  OPENSSL_memset(ctx, 0, sizeof(EVP_ENCODE_CTX));
89
0
}
90
91
void EVP_EncodeUpdate(EVP_ENCODE_CTX *ctx, uint8_t *out, int *out_len,
92
0
                      const uint8_t *in, size_t in_len) {
93
0
  size_t total = 0;
94
95
0
  *out_len = 0;
96
0
  if (in_len == 0) {
97
0
    return;
98
0
  }
99
100
0
  assert(ctx->data_used < sizeof(ctx->data));
101
102
0
  if (sizeof(ctx->data) - ctx->data_used > in_len) {
103
0
    OPENSSL_memcpy(&ctx->data[ctx->data_used], in, in_len);
104
0
    ctx->data_used += (unsigned)in_len;
105
0
    return;
106
0
  }
107
108
0
  if (ctx->data_used != 0) {
109
0
    const size_t todo = sizeof(ctx->data) - ctx->data_used;
110
0
    OPENSSL_memcpy(&ctx->data[ctx->data_used], in, todo);
111
0
    in += todo;
112
0
    in_len -= todo;
113
114
0
    size_t encoded = EVP_EncodeBlock(out, ctx->data, sizeof(ctx->data));
115
0
    ctx->data_used = 0;
116
117
0
    out += encoded;
118
0
    *(out++) = '\n';
119
0
    *out = '\0';
120
121
0
    total = encoded + 1;
122
0
  }
123
124
0
  while (in_len >= sizeof(ctx->data)) {
125
0
    size_t encoded = EVP_EncodeBlock(out, in, sizeof(ctx->data));
126
0
    in += sizeof(ctx->data);
127
0
    in_len -= sizeof(ctx->data);
128
129
0
    out += encoded;
130
0
    *(out++) = '\n';
131
0
    *out = '\0';
132
133
0
    if (total + encoded + 1 < total) {
134
0
      *out_len = 0;
135
0
      return;
136
0
    }
137
138
0
    total += encoded + 1;
139
0
  }
140
141
0
  if (in_len != 0) {
142
0
    OPENSSL_memcpy(ctx->data, in, in_len);
143
0
  }
144
145
0
  ctx->data_used = (unsigned)in_len;
146
147
0
  if (total > INT_MAX) {
148
    // We cannot signal an error, but we can at least avoid making *out_len
149
    // negative.
150
0
    total = 0;
151
0
  }
152
0
  *out_len = (int)total;
153
0
}
154
155
0
void EVP_EncodeFinal(EVP_ENCODE_CTX *ctx, uint8_t *out, int *out_len) {
156
0
  if (ctx->data_used == 0) {
157
0
    *out_len = 0;
158
0
    return;
159
0
  }
160
161
0
  size_t encoded = EVP_EncodeBlock(out, ctx->data, ctx->data_used);
162
0
  out[encoded++] = '\n';
163
0
  out[encoded] = '\0';
164
0
  ctx->data_used = 0;
165
166
  // ctx->data_used is bounded by sizeof(ctx->data), so this does not
167
  // overflow.
168
0
  assert(encoded <= INT_MAX);
169
0
  *out_len = (int)encoded;
170
0
}
171
172
0
size_t EVP_EncodeBlock(uint8_t *dst, const uint8_t *src, size_t src_len) {
173
0
  uint32_t l;
174
0
  size_t remaining = src_len, ret = 0;
175
176
0
  while (remaining) {
177
0
    if (remaining >= 3) {
178
0
      l = (((uint32_t)src[0]) << 16L) | (((uint32_t)src[1]) << 8L) | src[2];
179
0
      *(dst++) = conv_bin2ascii(l >> 18L);
180
0
      *(dst++) = conv_bin2ascii(l >> 12L);
181
0
      *(dst++) = conv_bin2ascii(l >> 6L);
182
0
      *(dst++) = conv_bin2ascii(l);
183
0
      remaining -= 3;
184
0
    } else {
185
0
      l = ((uint32_t)src[0]) << 16L;
186
0
      if (remaining == 2) {
187
0
        l |= ((uint32_t)src[1] << 8L);
188
0
      }
189
190
0
      *(dst++) = conv_bin2ascii(l >> 18L);
191
0
      *(dst++) = conv_bin2ascii(l >> 12L);
192
0
      *(dst++) = (remaining == 1) ? '=' : conv_bin2ascii(l >> 6L);
193
0
      *(dst++) = '=';
194
0
      remaining = 0;
195
0
    }
196
0
    ret += 4;
197
0
    src += 3;
198
0
  }
199
200
0
  *dst = '\0';
201
0
  return ret;
202
0
}
203
204
205
// Decoding.
206
207
0
int EVP_DecodedLength(size_t *out_len, size_t len) {
208
0
  if (len % 4 != 0) {
209
0
    return 0;
210
0
  }
211
212
0
  *out_len = (len / 4) * 3;
213
0
  return 1;
214
0
}
215
216
160
void EVP_DecodeInit(EVP_ENCODE_CTX *ctx) {
217
160
  OPENSSL_memset(ctx, 0, sizeof(EVP_ENCODE_CTX));
218
160
}
219
220
1.90M
static uint8_t base64_ascii_to_bin(uint8_t a) {
221
  // Since PEM is sometimes used to carry private keys, we decode base64 data
222
  // itself in constant-time.
223
1.90M
  const uint8_t is_upper = constant_time_in_range_8(a, 'A', 'Z');
224
1.90M
  const uint8_t is_lower = constant_time_in_range_8(a, 'a', 'z');
225
1.90M
  const uint8_t is_digit = constant_time_in_range_8(a, '0', '9');
226
1.90M
  const uint8_t is_plus = constant_time_eq_8(a, '+');
227
1.90M
  const uint8_t is_slash = constant_time_eq_8(a, '/');
228
1.90M
  const uint8_t is_equals = constant_time_eq_8(a, '=');
229
230
1.90M
  uint8_t ret = 0;
231
1.90M
  ret |= is_upper & (a - 'A');       // [0,26)
232
1.90M
  ret |= is_lower & (a - 'a' + 26);  // [26,52)
233
1.90M
  ret |= is_digit & (a - '0' + 52);  // [52,62)
234
1.90M
  ret |= is_plus & 62;
235
1.90M
  ret |= is_slash & 63;
236
  // Invalid inputs, 'A', and '=' have all been mapped to zero. Map invalid
237
  // inputs to 0xff. Note '=' is padding and handled separately by the caller.
238
1.90M
  const uint8_t is_valid =
239
1.90M
      is_upper | is_lower | is_digit | is_plus | is_slash | is_equals;
240
1.90M
  ret |= ~is_valid;
241
1.90M
  return ret;
242
1.90M
}
243
244
// base64_decode_quad decodes a single “quad” (i.e. four characters) of base64
245
// data and writes up to three bytes to `out`. It sets `*out_num_bytes` to the
246
// number of bytes written, which will be less than three if the quad ended
247
// with padding.  It returns one on success or zero on error.
248
static int base64_decode_quad(uint8_t *out, size_t *out_num_bytes,
249
475k
                              const uint8_t *in) {
250
475k
  const uint8_t a = base64_ascii_to_bin(in[0]);
251
475k
  const uint8_t b = base64_ascii_to_bin(in[1]);
252
475k
  const uint8_t c = base64_ascii_to_bin(in[2]);
253
475k
  const uint8_t d = base64_ascii_to_bin(in[3]);
254
475k
  if (a == 0xff || b == 0xff || c == 0xff || d == 0xff) {
255
72
    return 0;
256
72
  }
257
258
475k
  const uint32_t v = ((uint32_t)a) << 18 | ((uint32_t)b) << 12 |
259
475k
                     ((uint32_t)c) << 6 | (uint32_t)d;
260
261
475k
  const unsigned padding_pattern = (in[0] == '=') << 3 | //
262
475k
                                   (in[1] == '=') << 2 | //
263
475k
                                   (in[2] == '=') << 1 | //
264
475k
                                   (in[3] == '=');
265
266
  // In presence of padding, the lowest bits of v are unused. Canonical encoding
267
  // (RFC 4648, section 3.5) requires that these bits all be set to zero. Common
268
  // PEM parsers accept noncanonical base64, adding to the malleability of the
269
  // format. This decoder follows OpenSSL's and Go's PEM parsers and accepts it.
270
475k
  switch (padding_pattern) {
271
475k
    case 0:
272
      // The common case of no padding.
273
475k
      *out_num_bytes = 3;
274
475k
      out[0] = v >> 16;
275
475k
      out[1] = v >> 8;
276
475k
      out[2] = v;
277
475k
      break;
278
279
4
    case 1:  // xxx=
280
4
      *out_num_bytes = 2;
281
4
      out[0] = v >> 16;
282
4
      out[1] = v >> 8;
283
4
      break;
284
285
12
    case 3:  // xx==
286
12
      *out_num_bytes = 1;
287
12
      out[0] = v >> 16;
288
12
      break;
289
290
2
    default:
291
2
      return 0;
292
475k
  }
293
294
475k
  return 1;
295
475k
}
296
297
int EVP_DecodeUpdate(EVP_ENCODE_CTX *ctx, uint8_t *out, int *out_len,
298
160
                     const uint8_t *in, size_t in_len) {
299
160
  *out_len = 0;
300
301
160
  if (ctx->error_encountered) {
302
0
    return -1;
303
0
  }
304
305
160
  size_t bytes_out = 0, i;
306
1.91M
  for (i = 0; i < in_len; i++) {
307
1.91M
    const char c = in[i];
308
1.91M
    switch (c) {
309
357
      case ' ':
310
755
      case '\t':
311
998
      case '\r':
312
8.83k
      case '\n':
313
8.83k
        continue;
314
1.91M
    }
315
316
1.90M
    if (ctx->eof_seen) {
317
1
      ctx->error_encountered = 1;
318
1
      return -1;
319
1
    }
320
321
1.90M
    ctx->data[ctx->data_used++] = c;
322
1.90M
    if (ctx->data_used == 4) {
323
475k
      size_t num_bytes_resulting;
324
475k
      if (!base64_decode_quad(out, &num_bytes_resulting, ctx->data)) {
325
74
        ctx->error_encountered = 1;
326
74
        return -1;
327
74
      }
328
329
475k
      ctx->data_used = 0;
330
475k
      bytes_out += num_bytes_resulting;
331
475k
      out += num_bytes_resulting;
332
333
475k
      if (num_bytes_resulting < 3) {
334
16
        ctx->eof_seen = 1;
335
16
      }
336
475k
    }
337
1.90M
  }
338
339
85
  if (bytes_out > INT_MAX) {
340
0
    ctx->error_encountered = 1;
341
0
    *out_len = 0;
342
0
    return -1;
343
0
  }
344
85
  *out_len = (int)bytes_out;
345
346
85
  if (ctx->eof_seen) {
347
15
    return 0;
348
15
  }
349
350
70
  return 1;
351
85
}
352
353
85
int EVP_DecodeFinal(EVP_ENCODE_CTX *ctx, uint8_t *out, int *out_len) {
354
85
  *out_len = 0;
355
85
  if (ctx->error_encountered || ctx->data_used != 0) {
356
37
    return -1;
357
37
  }
358
359
48
  return 1;
360
85
}
361
362
int EVP_DecodeBase64(uint8_t *out, size_t *out_len, size_t max_out,
363
0
                     const uint8_t *in, size_t in_len) {
364
0
  *out_len = 0;
365
366
0
  if (in_len % 4 != 0) {
367
0
    return 0;
368
0
  }
369
370
0
  size_t max_len;
371
0
  if (!EVP_DecodedLength(&max_len, in_len) || max_out < max_len) {
372
0
    return 0;
373
0
  }
374
375
0
  size_t i, bytes_out = 0;
376
0
  for (i = 0; i < in_len; i += 4) {
377
0
    size_t num_bytes_resulting;
378
379
0
    if (!base64_decode_quad(out, &num_bytes_resulting, &in[i])) {
380
0
      return 0;
381
0
    }
382
383
0
    bytes_out += num_bytes_resulting;
384
0
    out += num_bytes_resulting;
385
0
    if (num_bytes_resulting != 3 && i != in_len - 4) {
386
0
      return 0;
387
0
    }
388
0
  }
389
390
0
  *out_len = bytes_out;
391
0
  return 1;
392
0
}
393
394
0
int EVP_DecodeBlock(uint8_t *dst, const uint8_t *src, size_t src_len) {
395
  // Trim spaces and tabs from the beginning of the input.
396
0
  while (src_len > 0) {
397
0
    if (src[0] != ' ' && src[0] != '\t') {
398
0
      break;
399
0
    }
400
401
0
    src++;
402
0
    src_len--;
403
0
  }
404
405
  // Trim newlines, spaces and tabs from the end of the line.
406
0
  while (src_len > 0) {
407
0
    switch (src[src_len - 1]) {
408
0
      case ' ':
409
0
      case '\t':
410
0
      case '\r':
411
0
      case '\n':
412
0
        src_len--;
413
0
        continue;
414
0
    }
415
416
0
    break;
417
0
  }
418
419
0
  size_t dst_len;
420
0
  if (!EVP_DecodedLength(&dst_len, src_len) || dst_len > INT_MAX ||
421
0
      !EVP_DecodeBase64(dst, &dst_len, dst_len, src, src_len)) {
422
0
    return -1;
423
0
  }
424
425
  // EVP_DecodeBlock does not take padding into account, so put the
426
  // NULs back in... so the caller can strip them back out.
427
0
  while (dst_len % 3 != 0) {
428
0
    dst[dst_len++] = '\0';
429
0
  }
430
0
  assert(dst_len <= INT_MAX);
431
432
0
  return (int)dst_len;
433
0
}