1 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
2 * All rights reserved.
3 *
4 * This package is an SSL implementation written
5 * by Eric Young (eay@cryptsoft.com).
6 * The implementation was written so as to conform with Netscapes SSL.
7 *
8 * This library is free for commercial and non-commercial use as long as
9 * the following conditions are aheared to. The following conditions
10 * apply to all code found in this distribution, be it the RC4, RSA,
11 * lhash, DES, etc., code; not just the SSL code. The SSL documentation
12 * included with this distribution is covered by the same copyright terms
13 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
14 *
15 * Copyright remains Eric Young's, and as such any Copyright notices in
16 * the code are not to be removed.
17 * If this package is used in a product, Eric Young should be given attribution
18 * as the author of the parts of the library used.
19 * This can be in the form of a textual message at program startup or
20 * in documentation (online or textual) provided with the package.
21 *
22 * Redistribution and use in source and binary forms, with or without
23 * modification, are permitted provided that the following conditions
24 * are met:
25 * 1. Redistributions of source code must retain the copyright
26 * notice, this list of conditions and the following disclaimer.
27 * 2. Redistributions in binary form must reproduce the above copyright
28 * notice, this list of conditions and the following disclaimer in the
29 * documentation and/or other materials provided with the distribution.
30 * 3. All advertising materials mentioning features or use of this software
31 * must display the following acknowledgement:
32 * "This product includes cryptographic software written by
33 * Eric Young (eay@cryptsoft.com)"
34 * The word 'cryptographic' can be left out if the rouines from the library
35 * being used are not cryptographic related :-).
36 * 4. If you include any Windows specific code (or a derivative thereof) from
37 * the apps directory (application code) you must include an acknowledgement:
38 * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
39 *
40 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
41 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
43 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
44 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
45 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
46 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
48 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
49 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
50 * SUCH DAMAGE.
51 *
52 * The licence and distribution terms for any publically available version or
53 * derivative of this code cannot be changed. i.e. this code cannot simply be
54 * copied and put under another distribution licence
55 * [including the GNU Public Licence.] */
56
57 #include <openssl/base64.h>
58
59 #include <assert.h>
60 #include <limits.h>
61 #include <string.h>
62
63 #include "../internal.h"
64
65
66 // constant_time_lt_args_8 behaves like |constant_time_lt_8| but takes |uint8_t|
67 // arguments for a slightly simpler implementation.
constant_time_lt_args_8(uint8_t a,uint8_t b)68 static inline uint8_t constant_time_lt_args_8(uint8_t a, uint8_t b) {
69 crypto_word_t aw = a;
70 crypto_word_t bw = b;
71 // |crypto_word_t| is larger than |uint8_t|, so |aw| and |bw| have the same
72 // MSB. |aw| < |bw| iff MSB(|aw| - |bw|) is 1.
73 return constant_time_msb_w(aw - bw);
74 }
75
76 // constant_time_in_range_8 returns |CONSTTIME_TRUE_8| if |min| <= |a| <= |max|
77 // and |CONSTTIME_FALSE_8| otherwise.
constant_time_in_range_8(uint8_t a,uint8_t min,uint8_t max)78 static inline uint8_t constant_time_in_range_8(uint8_t a, uint8_t min,
79 uint8_t max) {
80 a -= min;
81 return constant_time_lt_args_8(a, max - min + 1);
82 }
83
84 // Encoding.
85
conv_bin2ascii(uint8_t a)86 static uint8_t conv_bin2ascii(uint8_t a) {
87 // Since PEM is sometimes used to carry private keys, we encode base64 data
88 // itself in constant-time.
89 a &= 0x3f;
90 uint8_t ret = constant_time_select_8(constant_time_eq_8(a, 62), '+', '/');
91 ret =
92 constant_time_select_8(constant_time_lt_args_8(a, 62), a - 52 + '0', ret);
93 ret =
94 constant_time_select_8(constant_time_lt_args_8(a, 52), a - 26 + 'a', ret);
95 ret = constant_time_select_8(constant_time_lt_args_8(a, 26), a + 'A', ret);
96 return ret;
97 }
98
99 static_assert(sizeof(((EVP_ENCODE_CTX *)(NULL))->data) % 3 == 0,
100 "data length must be a multiple of base64 chunk size");
101
EVP_EncodedLength(size_t * out_len,size_t len)102 int EVP_EncodedLength(size_t *out_len, size_t len) {
103 if (len + 2 < len) {
104 return 0;
105 }
106 len += 2;
107 len /= 3;
108
109 if (((len << 2) >> 2) != len) {
110 return 0;
111 }
112 len <<= 2;
113
114 if (len + 1 < len) {
115 return 0;
116 }
117 len++;
118
119 *out_len = len;
120 return 1;
121 }
122
EVP_ENCODE_CTX_new(void)123 EVP_ENCODE_CTX *EVP_ENCODE_CTX_new(void) {
124 EVP_ENCODE_CTX *ret = OPENSSL_malloc(sizeof(EVP_ENCODE_CTX));
125 if (ret == NULL) {
126 return NULL;
127 }
128 OPENSSL_memset(ret, 0, sizeof(EVP_ENCODE_CTX));
129 return ret;
130 }
131
EVP_ENCODE_CTX_free(EVP_ENCODE_CTX * ctx)132 void EVP_ENCODE_CTX_free(EVP_ENCODE_CTX *ctx) {
133 OPENSSL_free(ctx);
134 }
135
EVP_EncodeInit(EVP_ENCODE_CTX * ctx)136 void EVP_EncodeInit(EVP_ENCODE_CTX *ctx) {
137 OPENSSL_memset(ctx, 0, sizeof(EVP_ENCODE_CTX));
138 }
139
EVP_EncodeUpdate(EVP_ENCODE_CTX * ctx,uint8_t * out,int * out_len,const uint8_t * in,size_t in_len)140 void EVP_EncodeUpdate(EVP_ENCODE_CTX *ctx, uint8_t *out, int *out_len,
141 const uint8_t *in, size_t in_len) {
142 size_t total = 0;
143
144 *out_len = 0;
145 if (in_len == 0) {
146 return;
147 }
148
149 assert(ctx->data_used < sizeof(ctx->data));
150
151 if (sizeof(ctx->data) - ctx->data_used > in_len) {
152 OPENSSL_memcpy(&ctx->data[ctx->data_used], in, in_len);
153 ctx->data_used += (unsigned)in_len;
154 return;
155 }
156
157 if (ctx->data_used != 0) {
158 const size_t todo = sizeof(ctx->data) - ctx->data_used;
159 OPENSSL_memcpy(&ctx->data[ctx->data_used], in, todo);
160 in += todo;
161 in_len -= todo;
162
163 size_t encoded = EVP_EncodeBlock(out, ctx->data, sizeof(ctx->data));
164 ctx->data_used = 0;
165
166 out += encoded;
167 *(out++) = '\n';
168 *out = '\0';
169
170 total = encoded + 1;
171 }
172
173 while (in_len >= sizeof(ctx->data)) {
174 size_t encoded = EVP_EncodeBlock(out, in, sizeof(ctx->data));
175 in += sizeof(ctx->data);
176 in_len -= sizeof(ctx->data);
177
178 out += encoded;
179 *(out++) = '\n';
180 *out = '\0';
181
182 if (total + encoded + 1 < total) {
183 *out_len = 0;
184 return;
185 }
186
187 total += encoded + 1;
188 }
189
190 if (in_len != 0) {
191 OPENSSL_memcpy(ctx->data, in, in_len);
192 }
193
194 ctx->data_used = (unsigned)in_len;
195
196 if (total > INT_MAX) {
197 // We cannot signal an error, but we can at least avoid making *out_len
198 // negative.
199 total = 0;
200 }
201 *out_len = (int)total;
202 }
203
EVP_EncodeFinal(EVP_ENCODE_CTX * ctx,uint8_t * out,int * out_len)204 void EVP_EncodeFinal(EVP_ENCODE_CTX *ctx, uint8_t *out, int *out_len) {
205 if (ctx->data_used == 0) {
206 *out_len = 0;
207 return;
208 }
209
210 size_t encoded = EVP_EncodeBlock(out, ctx->data, ctx->data_used);
211 out[encoded++] = '\n';
212 out[encoded] = '\0';
213 ctx->data_used = 0;
214
215 // ctx->data_used is bounded by sizeof(ctx->data), so this does not
216 // overflow.
217 assert(encoded <= INT_MAX);
218 *out_len = (int)encoded;
219 }
220
EVP_EncodeBlock(uint8_t * dst,const uint8_t * src,size_t src_len)221 size_t EVP_EncodeBlock(uint8_t *dst, const uint8_t *src, size_t src_len) {
222 uint32_t l;
223 size_t remaining = src_len, ret = 0;
224
225 while (remaining) {
226 if (remaining >= 3) {
227 l = (((uint32_t)src[0]) << 16L) | (((uint32_t)src[1]) << 8L) | src[2];
228 *(dst++) = conv_bin2ascii(l >> 18L);
229 *(dst++) = conv_bin2ascii(l >> 12L);
230 *(dst++) = conv_bin2ascii(l >> 6L);
231 *(dst++) = conv_bin2ascii(l);
232 remaining -= 3;
233 } else {
234 l = ((uint32_t)src[0]) << 16L;
235 if (remaining == 2) {
236 l |= ((uint32_t)src[1] << 8L);
237 }
238
239 *(dst++) = conv_bin2ascii(l >> 18L);
240 *(dst++) = conv_bin2ascii(l >> 12L);
241 *(dst++) = (remaining == 1) ? '=' : conv_bin2ascii(l >> 6L);
242 *(dst++) = '=';
243 remaining = 0;
244 }
245 ret += 4;
246 src += 3;
247 }
248
249 *dst = '\0';
250 return ret;
251 }
252
253
254 // Decoding.
255
EVP_DecodedLength(size_t * out_len,size_t len)256 int EVP_DecodedLength(size_t *out_len, size_t len) {
257 if (len % 4 != 0) {
258 return 0;
259 }
260
261 *out_len = (len / 4) * 3;
262 return 1;
263 }
264
EVP_DecodeInit(EVP_ENCODE_CTX * ctx)265 void EVP_DecodeInit(EVP_ENCODE_CTX *ctx) {
266 OPENSSL_memset(ctx, 0, sizeof(EVP_ENCODE_CTX));
267 }
268
base64_ascii_to_bin(uint8_t a)269 static uint8_t base64_ascii_to_bin(uint8_t a) {
270 // Since PEM is sometimes used to carry private keys, we decode base64 data
271 // itself in constant-time.
272 const uint8_t is_upper = constant_time_in_range_8(a, 'A', 'Z');
273 const uint8_t is_lower = constant_time_in_range_8(a, 'a', 'z');
274 const uint8_t is_digit = constant_time_in_range_8(a, '0', '9');
275 const uint8_t is_plus = constant_time_eq_8(a, '+');
276 const uint8_t is_slash = constant_time_eq_8(a, '/');
277 const uint8_t is_equals = constant_time_eq_8(a, '=');
278
279 uint8_t ret = 0;
280 ret |= is_upper & (a - 'A'); // [0,26)
281 ret |= is_lower & (a - 'a' + 26); // [26,52)
282 ret |= is_digit & (a - '0' + 52); // [52,62)
283 ret |= is_plus & 62;
284 ret |= is_slash & 63;
285 // Invalid inputs, 'A', and '=' have all been mapped to zero. Map invalid
286 // inputs to 0xff. Note '=' is padding and handled separately by the caller.
287 const uint8_t is_valid =
288 is_upper | is_lower | is_digit | is_plus | is_slash | is_equals;
289 ret |= ~is_valid;
290 return ret;
291 }
292
293 // base64_decode_quad decodes a single “quad” (i.e. four characters) of base64
294 // data and writes up to three bytes to |out|. It sets |*out_num_bytes| to the
295 // number of bytes written, which will be less than three if the quad ended
296 // with padding. It returns one on success or zero on error.
base64_decode_quad(uint8_t * out,size_t * out_num_bytes,const uint8_t * in)297 static int base64_decode_quad(uint8_t *out, size_t *out_num_bytes,
298 const uint8_t *in) {
299 const uint8_t a = base64_ascii_to_bin(in[0]);
300 const uint8_t b = base64_ascii_to_bin(in[1]);
301 const uint8_t c = base64_ascii_to_bin(in[2]);
302 const uint8_t d = base64_ascii_to_bin(in[3]);
303 if (a == 0xff || b == 0xff || c == 0xff || d == 0xff) {
304 return 0;
305 }
306
307 const uint32_t v = ((uint32_t)a) << 18 | ((uint32_t)b) << 12 |
308 ((uint32_t)c) << 6 | (uint32_t)d;
309
310 const unsigned padding_pattern = (in[0] == '=') << 3 |
311 (in[1] == '=') << 2 |
312 (in[2] == '=') << 1 |
313 (in[3] == '=');
314
315 switch (padding_pattern) {
316 case 0:
317 // The common case of no padding.
318 *out_num_bytes = 3;
319 out[0] = v >> 16;
320 out[1] = v >> 8;
321 out[2] = v;
322 break;
323
324 case 1: // xxx=
325 *out_num_bytes = 2;
326 out[0] = v >> 16;
327 out[1] = v >> 8;
328 break;
329
330 case 3: // xx==
331 *out_num_bytes = 1;
332 out[0] = v >> 16;
333 break;
334
335 default:
336 return 0;
337 }
338
339 return 1;
340 }
341
EVP_DecodeUpdate(EVP_ENCODE_CTX * ctx,uint8_t * out,int * out_len,const uint8_t * in,size_t in_len)342 int EVP_DecodeUpdate(EVP_ENCODE_CTX *ctx, uint8_t *out, int *out_len,
343 const uint8_t *in, size_t in_len) {
344 *out_len = 0;
345
346 if (ctx->error_encountered) {
347 return -1;
348 }
349
350 size_t bytes_out = 0, i;
351 for (i = 0; i < in_len; i++) {
352 const char c = in[i];
353 switch (c) {
354 case ' ':
355 case '\t':
356 case '\r':
357 case '\n':
358 continue;
359 }
360
361 if (ctx->eof_seen) {
362 ctx->error_encountered = 1;
363 return -1;
364 }
365
366 ctx->data[ctx->data_used++] = c;
367 if (ctx->data_used == 4) {
368 size_t num_bytes_resulting;
369 if (!base64_decode_quad(out, &num_bytes_resulting, ctx->data)) {
370 ctx->error_encountered = 1;
371 return -1;
372 }
373
374 ctx->data_used = 0;
375 bytes_out += num_bytes_resulting;
376 out += num_bytes_resulting;
377
378 if (num_bytes_resulting < 3) {
379 ctx->eof_seen = 1;
380 }
381 }
382 }
383
384 if (bytes_out > INT_MAX) {
385 ctx->error_encountered = 1;
386 *out_len = 0;
387 return -1;
388 }
389 *out_len = (int)bytes_out;
390
391 if (ctx->eof_seen) {
392 return 0;
393 }
394
395 return 1;
396 }
397
EVP_DecodeFinal(EVP_ENCODE_CTX * ctx,uint8_t * out,int * out_len)398 int EVP_DecodeFinal(EVP_ENCODE_CTX *ctx, uint8_t *out, int *out_len) {
399 *out_len = 0;
400 if (ctx->error_encountered || ctx->data_used != 0) {
401 return -1;
402 }
403
404 return 1;
405 }
406
EVP_DecodeBase64(uint8_t * out,size_t * out_len,size_t max_out,const uint8_t * in,size_t in_len)407 int EVP_DecodeBase64(uint8_t *out, size_t *out_len, size_t max_out,
408 const uint8_t *in, size_t in_len) {
409 *out_len = 0;
410
411 if (in_len % 4 != 0) {
412 return 0;
413 }
414
415 size_t max_len;
416 if (!EVP_DecodedLength(&max_len, in_len) ||
417 max_out < max_len) {
418 return 0;
419 }
420
421 size_t i, bytes_out = 0;
422 for (i = 0; i < in_len; i += 4) {
423 size_t num_bytes_resulting;
424
425 if (!base64_decode_quad(out, &num_bytes_resulting, &in[i])) {
426 return 0;
427 }
428
429 bytes_out += num_bytes_resulting;
430 out += num_bytes_resulting;
431 if (num_bytes_resulting != 3 && i != in_len - 4) {
432 return 0;
433 }
434 }
435
436 *out_len = bytes_out;
437 return 1;
438 }
439
EVP_DecodeBlock(uint8_t * dst,const uint8_t * src,size_t src_len)440 int EVP_DecodeBlock(uint8_t *dst, const uint8_t *src, size_t src_len) {
441 // Trim spaces and tabs from the beginning of the input.
442 while (src_len > 0) {
443 if (src[0] != ' ' && src[0] != '\t') {
444 break;
445 }
446
447 src++;
448 src_len--;
449 }
450
451 // Trim newlines, spaces and tabs from the end of the line.
452 while (src_len > 0) {
453 switch (src[src_len-1]) {
454 case ' ':
455 case '\t':
456 case '\r':
457 case '\n':
458 src_len--;
459 continue;
460 }
461
462 break;
463 }
464
465 size_t dst_len;
466 if (!EVP_DecodedLength(&dst_len, src_len) ||
467 dst_len > INT_MAX ||
468 !EVP_DecodeBase64(dst, &dst_len, dst_len, src, src_len)) {
469 return -1;
470 }
471
472 // EVP_DecodeBlock does not take padding into account, so put the
473 // NULs back in... so the caller can strip them back out.
474 while (dst_len % 3 != 0) {
475 dst[dst_len++] = '\0';
476 }
477 assert(dst_len <= INT_MAX);
478
479 return (int)dst_len;
480 }
481