bd2bbc0b099a9882f9748b84b2874208f5a76877
[openssl.git] / crypto / evp / encode.c
1 /*
2  * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the OpenSSL license (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 <limits.h>
12 #include "internal/cryptlib.h"
13 #include <openssl/evp.h>
14 #include "evp_locl.h"
15
16 static unsigned char conv_ascii2bin(unsigned char a);
17 #ifndef CHARSET_EBCDIC
18 # define conv_bin2ascii(a)       (data_bin2ascii[(a)&0x3f])
19 #else
20 /*
21  * We assume that PEM encoded files are EBCDIC files (i.e., printable text
22  * files). Convert them here while decoding. When encoding, output is EBCDIC
23  * (text) format again. (No need for conversion in the conv_bin2ascii macro,
24  * as the underlying textstring data_bin2ascii[] is already EBCDIC)
25  */
26 # define conv_bin2ascii(a)       (data_bin2ascii[(a)&0x3f])
27 #endif
28
29 /*-
30  * 64 char lines
31  * pad input with 0
32  * left over chars are set to =
33  * 1 byte  => xx==
34  * 2 bytes => xxx=
35  * 3 bytes => xxxx
36  */
37 #define BIN_PER_LINE    (64/4*3)
38 #define CHUNKS_PER_LINE (64/4)
39 #define CHAR_PER_LINE   (64+1)
40
41 static const unsigned char data_bin2ascii[65] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ\
42 abcdefghijklmnopqrstuvwxyz0123456789+/";
43
44 /*-
45  * 0xF0 is a EOLN
46  * 0xF1 is ignore but next needs to be 0xF0 (for \r\n processing).
47  * 0xF2 is EOF
48  * 0xE0 is ignore at start of line.
49  * 0xFF is error
50  */
51
52 #define B64_EOLN                0xF0
53 #define B64_CR                  0xF1
54 #define B64_EOF                 0xF2
55 #define B64_WS                  0xE0
56 #define B64_ERROR               0xFF
57 #define B64_NOT_BASE64(a)       (((a)|0x13) == 0xF3)
58 #define B64_BASE64(a)           !B64_NOT_BASE64(a)
59
60 static const unsigned char data_ascii2bin[128] = {
61     0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
62     0xFF, 0xE0, 0xF0, 0xFF, 0xFF, 0xF1, 0xFF, 0xFF,
63     0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
64     0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
65     0xE0, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
66     0xFF, 0xFF, 0xFF, 0x3E, 0xFF, 0xF2, 0xFF, 0x3F,
67     0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x3B,
68     0x3C, 0x3D, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF,
69     0xFF, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06,
70     0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E,
71     0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16,
72     0x17, 0x18, 0x19, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
73     0xFF, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20,
74     0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28,
75     0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, 0x30,
76     0x31, 0x32, 0x33, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
77 };
78
79 #ifndef CHARSET_EBCDIC
80 static unsigned char conv_ascii2bin(unsigned char a)
81 {
82     if (a & 0x80)
83         return B64_ERROR;
84     return data_ascii2bin[a];
85 }
86 #else
87 static unsigned char conv_ascii2bin(unsigned char a)
88 {
89     a = os_toascii[a];
90     if (a & 0x80)
91         return B64_ERROR;
92     return data_ascii2bin[a];
93 }
94 #endif
95
96 EVP_ENCODE_CTX *EVP_ENCODE_CTX_new(void)
97 {
98     return OPENSSL_zalloc(sizeof(EVP_ENCODE_CTX));
99 }
100
101 void EVP_ENCODE_CTX_free(EVP_ENCODE_CTX *ctx)
102 {
103     OPENSSL_free(ctx);
104 }
105 int EVP_ENCODE_CTX_num(EVP_ENCODE_CTX *ctx)
106 {
107     return ctx->num;
108 }
109
110 void EVP_EncodeInit(EVP_ENCODE_CTX *ctx)
111 {
112     ctx->length = 48;
113     ctx->num = 0;
114     ctx->line_num = 0;
115 }
116
117 void EVP_EncodeUpdate(EVP_ENCODE_CTX *ctx, unsigned char *out, int *outl,
118                       const unsigned char *in, int inl)
119 {
120     int i, j;
121     size_t total = 0;
122
123     *outl = 0;
124     if (inl <= 0)
125         return;
126     OPENSSL_assert(ctx->length <= (int)sizeof(ctx->enc_data));
127     if (ctx->length - ctx->num > inl) {
128         memcpy(&(ctx->enc_data[ctx->num]), in, inl);
129         ctx->num += inl;
130         return;
131     }
132     if (ctx->num != 0) {
133         i = ctx->length - ctx->num;
134         memcpy(&(ctx->enc_data[ctx->num]), in, i);
135         in += i;
136         inl -= i;
137         j = EVP_EncodeBlock(out, ctx->enc_data, ctx->length);
138         ctx->num = 0;
139         out += j;
140         *(out++) = '\n';
141         *out = '\0';
142         total = j + 1;
143     }
144     while (inl >= ctx->length && total <= INT_MAX) {
145         j = EVP_EncodeBlock(out, in, ctx->length);
146         in += ctx->length;
147         inl -= ctx->length;
148         out += j;
149         *(out++) = '\n';
150         *out = '\0';
151         total += j + 1;
152     }
153     if (total > INT_MAX) {
154         /* Too much output data! */
155         *outl = 0;
156         return;
157     }
158     if (inl != 0)
159         memcpy(&(ctx->enc_data[0]), in, inl);
160     ctx->num = inl;
161     *outl = total;
162 }
163
164 void EVP_EncodeFinal(EVP_ENCODE_CTX *ctx, unsigned char *out, int *outl)
165 {
166     unsigned int ret = 0;
167
168     if (ctx->num != 0) {
169         ret = EVP_EncodeBlock(out, ctx->enc_data, ctx->num);
170         out[ret++] = '\n';
171         out[ret] = '\0';
172         ctx->num = 0;
173     }
174     *outl = ret;
175 }
176
177 int EVP_EncodeBlock(unsigned char *t, const unsigned char *f, int dlen)
178 {
179     int i, ret = 0;
180     unsigned long l;
181
182     for (i = dlen; i > 0; i -= 3) {
183         if (i >= 3) {
184             l = (((unsigned long)f[0]) << 16L) |
185                 (((unsigned long)f[1]) << 8L) | f[2];
186             *(t++) = conv_bin2ascii(l >> 18L);
187             *(t++) = conv_bin2ascii(l >> 12L);
188             *(t++) = conv_bin2ascii(l >> 6L);
189             *(t++) = conv_bin2ascii(l);
190         } else {
191             l = ((unsigned long)f[0]) << 16L;
192             if (i == 2)
193                 l |= ((unsigned long)f[1] << 8L);
194
195             *(t++) = conv_bin2ascii(l >> 18L);
196             *(t++) = conv_bin2ascii(l >> 12L);
197             *(t++) = (i == 1) ? '=' : conv_bin2ascii(l >> 6L);
198             *(t++) = '=';
199         }
200         ret += 4;
201         f += 3;
202     }
203
204     *t = '\0';
205     return (ret);
206 }
207
208 void EVP_DecodeInit(EVP_ENCODE_CTX *ctx)
209 {
210     /* Only ctx->num is used during decoding. */
211     ctx->num = 0;
212     ctx->length = 0;
213     ctx->line_num = 0;
214     ctx->expect_nl = 0;
215 }
216
217 /*-
218  * -1 for error
219  *  0 for last line
220  *  1 for full line
221  *
222  * Note: even though EVP_DecodeUpdate attempts to detect and report end of
223  * content, the context doesn't currently remember it and will accept more data
224  * in the next call. Therefore, the caller is responsible for checking and
225  * rejecting a 0 return value in the middle of content.
226  *
227  * Note: even though EVP_DecodeUpdate has historically tried to detect end of
228  * content based on line length, this has never worked properly. Therefore,
229  * we now return 0 when one of the following is true:
230  *   - Padding or B64_EOF was detected and the last block is complete.
231  *   - Input has zero-length.
232  * -1 is returned if:
233  *   - Invalid characters are detected.
234  *   - There is extra trailing padding, or data after padding.
235  *   - B64_EOF is detected after an incomplete base64 block.
236  */
237 int EVP_DecodeUpdate(EVP_ENCODE_CTX *ctx, unsigned char *out, int *outl,
238                      const unsigned char *in, int inl)
239 {
240     int seof = 0, eof = 0, rv = -1, ret = 0, i, v, tmp, n, decoded_len;
241     unsigned char *d;
242
243     n = ctx->num;
244     d = ctx->enc_data;
245
246     if (n > 0 && d[n - 1] == '=') {
247         eof++;
248         if (n > 1 && d[n - 2] == '=')
249             eof++;
250     }
251
252      /* Legacy behaviour: an empty input chunk signals end of input. */
253     if (inl == 0) {
254         rv = 0;
255         goto end;
256     }
257
258     for (i = 0; i < inl; i++) {
259         tmp = *(in++);
260         v = conv_ascii2bin(tmp);
261         if (v == B64_ERROR) {
262             rv = -1;
263             goto end;
264         }
265
266         if (tmp == '=') {
267             eof++;
268         } else if (eof > 0 && B64_BASE64(v)) {
269             /* More data after padding. */
270             rv = -1;
271             goto end;
272         }
273
274         if (eof > 2) {
275             rv = -1;
276             goto end;
277         }
278
279         if (v == B64_EOF) {
280             seof = 1;
281             goto tail;
282         }
283
284         /* Only save valid base64 characters. */
285         if (B64_BASE64(v)) {
286             if (n >= 64) {
287                 /*
288                  * We increment n once per loop, and empty the buffer as soon as
289                  * we reach 64 characters, so this can only happen if someone's
290                  * manually messed with the ctx. Refuse to write any more data.
291                  */
292                 rv = -1;
293                 goto end;
294             }
295             OPENSSL_assert(n < (int)sizeof(ctx->enc_data));
296             d[n++] = tmp;
297         }
298
299         if (n == 64) {
300             decoded_len = EVP_DecodeBlock(out, d, n);
301             n = 0;
302             if (decoded_len < 0 || eof > decoded_len) {
303                 rv = -1;
304                 goto end;
305             }
306             ret += decoded_len - eof;
307             out += decoded_len - eof;
308         }
309     }
310
311     /*
312      * Legacy behaviour: if the current line is a full base64-block (i.e., has
313      * 0 mod 4 base64 characters), it is processed immediately. We keep this
314      * behaviour as applications may not be calling EVP_DecodeFinal properly.
315      */
316 tail:
317     if (n > 0) {
318         if ((n & 3) == 0) {
319             decoded_len = EVP_DecodeBlock(out, d, n);
320             n = 0;
321             if (decoded_len < 0 || eof > decoded_len) {
322                 rv = -1;
323                 goto end;
324             }
325             ret += (decoded_len - eof);
326         } else if (seof) {
327             /* EOF in the middle of a base64 block. */
328             rv = -1;
329             goto end;
330         }
331     }
332
333     rv = seof || (n == 0 && eof) ? 0 : 1;
334 end:
335     /* Legacy behaviour. This should probably rather be zeroed on error. */
336     *outl = ret;
337     ctx->num = n;
338     return (rv);
339 }
340
341 int EVP_DecodeBlock(unsigned char *t, const unsigned char *f, int n)
342 {
343     int i, ret = 0, a, b, c, d;
344     unsigned long l;
345
346     /* trim white space from the start of the line. */
347     while ((conv_ascii2bin(*f) == B64_WS) && (n > 0)) {
348         f++;
349         n--;
350     }
351
352     /*
353      * strip off stuff at the end of the line ascii2bin values B64_WS,
354      * B64_EOLN, B64_EOLN and B64_EOF
355      */
356     while ((n > 3) && (B64_NOT_BASE64(conv_ascii2bin(f[n - 1]))))
357         n--;
358
359     if (n % 4 != 0)
360         return (-1);
361
362     for (i = 0; i < n; i += 4) {
363         a = conv_ascii2bin(*(f++));
364         b = conv_ascii2bin(*(f++));
365         c = conv_ascii2bin(*(f++));
366         d = conv_ascii2bin(*(f++));
367         if ((a & 0x80) || (b & 0x80) || (c & 0x80) || (d & 0x80))
368             return (-1);
369         l = ((((unsigned long)a) << 18L) |
370              (((unsigned long)b) << 12L) |
371              (((unsigned long)c) << 6L) | (((unsigned long)d)));
372         *(t++) = (unsigned char)(l >> 16L) & 0xff;
373         *(t++) = (unsigned char)(l >> 8L) & 0xff;
374         *(t++) = (unsigned char)(l) & 0xff;
375         ret += 3;
376     }
377     return (ret);
378 }
379
380 int EVP_DecodeFinal(EVP_ENCODE_CTX *ctx, unsigned char *out, int *outl)
381 {
382     int i;
383
384     *outl = 0;
385     if (ctx->num != 0) {
386         i = EVP_DecodeBlock(out, ctx->enc_data, ctx->num);
387         if (i < 0)
388             return (-1);
389         ctx->num = 0;
390         *outl = i;
391         return (1);
392     } else
393         return (1);
394 }