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