315fe8fc8f6e8e8de8bb977350d77865194bf092
[openssl.git] / crypto / modes / wrap128.c
1 /* crypto/modes/wrap128.c */
2 /* Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL
3  * project.
4  * Mode with padding contributed by Petr Spacek (pspacek@redhat.com).
5  */
6 /* ====================================================================
7  * Copyright (c) 2013 The OpenSSL Project.  All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  *
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer. 
15  *
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in
18  *    the documentation and/or other materials provided with the
19  *    distribution.
20  *
21  * 3. All advertising materials mentioning features or use of this
22  *    software must display the following acknowledgment:
23  *    "This product includes software developed by the OpenSSL Project
24  *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
25  *
26  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
27  *    endorse or promote products derived from this software without
28  *    prior written permission. For written permission, please contact
29  *    licensing@OpenSSL.org.
30  *
31  * 5. Products derived from this software may not be called "OpenSSL"
32  *    nor may "OpenSSL" appear in their names without prior written
33  *    permission of the OpenSSL Project.
34  *
35  * 6. Redistributions of any form whatsoever must retain the following
36  *    acknowledgment:
37  *    "This product includes software developed by the OpenSSL Project
38  *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
39  *
40  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
41  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
43  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
44  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
45  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
46  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
47  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
49  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
50  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
51  * OF THE POSSIBILITY OF SUCH DAMAGE.
52  * ====================================================================
53  */
54
55 /**  Beware!
56  *
57  *  Following wrapping modes were designed for AES but this implementation
58  *  allows you to use them for any 128 bit block cipher.
59  */
60
61 #include "cryptlib.h"
62 #include <openssl/modes.h>
63
64 /** RFC 3394 section 2.2.3.1 Default Initial Value */
65 static const unsigned char default_iv[] = {
66   0xA6, 0xA6, 0xA6, 0xA6, 0xA6, 0xA6, 0xA6, 0xA6,
67 };
68
69 /** RFC 5649 section 3 Alternative Initial Value 32-bit constant */
70 static const unsigned char default_aiv[] = {
71   0xA6, 0x59, 0x59, 0xA6
72 };
73
74 /** Input size limit: lower than maximum of standards but far larger than
75  *  anything that will be used in practice.
76  */
77 #define CRYPTO128_WRAP_MAX (1UL << 31)
78
79 /** Wrapping according to RFC 3394 section 2.2.1.
80  *
81  *  @param[in]  key    Key value. 
82  *  @param[in]  iv     IV value. Length = 8 bytes. NULL = use default_iv.
83  *  @param[in]  in     Plain text as n 64-bit blocks, n >= 2.
84  *  @param[in]  inlen  Length of in.
85  *  @param[out] out    Cipher text. Minimal buffer length = (inlen + 8) bytes.
86  *                     Input and output buffers can overlap if block function
87  *                     supports that.
88  *  @param[in]  block  Block processing function.
89  *  @return            0 if inlen does not consist of n 64-bit blocks, n >= 2.
90  *                     or if inlen > CRYPTO128_WRAP_MAX.
91  *                     Output length if wrapping succeeded.
92  */
93 size_t CRYPTO_128_wrap(void *key, const unsigned char *iv,
94                 unsigned char *out,
95                 const unsigned char *in, size_t inlen, block128_f block)
96         {
97         unsigned char *A, B[16], *R;
98         size_t i, j, t;
99         if ((inlen & 0x7) || (inlen < 16) || (inlen > CRYPTO128_WRAP_MAX))
100                 return 0;
101         A = B;
102         t = 1;
103         memmove(out + 8, in, inlen);
104         if (!iv)
105                 iv = default_iv;
106
107         memcpy(A, iv, 8);
108
109         for (j = 0; j < 6; j++)
110                 {
111                 R = out + 8;
112                 for (i = 0; i < inlen; i += 8, t++, R += 8)
113                         {
114                         memcpy(B + 8, R, 8);
115                         block(B, B, key);
116                         A[7] ^= (unsigned char)(t & 0xff);
117                         if (t > 0xff)   
118                                 {
119                                 A[6] ^= (unsigned char)((t >> 8) & 0xff);
120                                 A[5] ^= (unsigned char)((t >> 16) & 0xff);
121                                 A[4] ^= (unsigned char)((t >> 24) & 0xff);
122                                 }
123                         memcpy(R, B + 8, 8);
124                         }
125                 }
126         memcpy(out, A, 8);
127         return inlen + 8;
128         }
129
130
131 /** Unwrapping according to RFC 3394 section 2.2.2 steps 1-2.
132  *  IV check (step 3) is responsibility of the caller.
133  *
134  *  @param[in]  key    Key value. 
135  *  @param[out] iv     Unchecked IV value. Minimal buffer length = 8 bytes.
136  *  @param[out] out    Plain text without IV.
137  *                     Minimal buffer length = (inlen - 8) bytes.
138  *                     Input and output buffers can overlap if block function
139  *                     supports that.
140  *  @param[in]  in     Ciphertext text as n 64-bit blocks
141  *  @param[in]  inlen  Length of in.
142  *  @param[in]  block  Block processing function.
143  *  @return            0 if inlen is out of range [24, CRYPTO128_WRAP_MAX]
144  *                     or if inlen is not multiply of 8.
145  *                     Output length otherwise.
146  */
147 static size_t crypto_128_unwrap_raw(void *key, unsigned char *iv,
148                 unsigned char *out, const unsigned char *in,
149                 size_t inlen, block128_f block)
150         {
151         unsigned char *A, B[16], *R;
152         size_t i, j, t;
153         inlen -= 8;
154         if ((inlen & 0x7) || (inlen < 16) || (inlen > CRYPTO128_WRAP_MAX))
155                 return 0;
156         A = B;
157         t =  6 * (inlen >> 3);
158         memcpy(A, in, 8);
159         memmove(out, in + 8, inlen);
160         for (j = 0; j < 6; j++)
161                 {
162                 R = out + inlen - 8;
163                 for (i = 0; i < inlen; i += 8, t--, R -= 8)
164                         {
165                         A[7] ^= (unsigned char)(t & 0xff);
166                         if (t > 0xff)   
167                                 {
168                                 A[6] ^= (unsigned char)((t >> 8) & 0xff);
169                                 A[5] ^= (unsigned char)((t >> 16) & 0xff);
170                                 A[4] ^= (unsigned char)((t >> 24) & 0xff);
171                                 }
172                         memcpy(B + 8, R, 8);
173                         block(B, B, key);
174                         memcpy(R, B + 8, 8);
175                         }
176                 }
177         memcpy(iv, A, 8);
178         return inlen;
179         }
180
181 /** Unwrapping according to RFC 3394 section 2.2.2 including IV check.
182  *  First block of plain text have to match supplied IV otherwise an error is
183  *  returned.
184  *
185  *  @param[in]  key    Key value. 
186  *  @param[out] iv     Unchecked IV value. Minimal buffer length = 8 bytes.
187  *  @param[out] out    Plain text without IV.
188  *                     Minimal buffer length = (inlen - 8) bytes.
189  *                     Input and output buffers can overlap if block function
190  *                     supports that.
191  *  @param[in]  in     Ciphertext text as n 64-bit blocks
192  *  @param[in]  inlen  Length of in.
193  *  @param[in]  block  Block processing function.
194  *  @return            0 if inlen is out of range [24, CRYPTO128_WRAP_MAX]
195  *                     or if inlen is not multiply of 8
196  *                     or if IV doesn't match expected value.
197  *                     Output length otherwise.
198  */
199 size_t CRYPTO_128_unwrap(void *key, const unsigned char *iv,
200                 unsigned char *out, const unsigned char *in, size_t inlen,
201                 block128_f block)
202         {
203         size_t ret;
204         unsigned char got_iv[8];
205
206         ret = crypto_128_unwrap_raw(key, got_iv, out, in, inlen, block);
207         if (ret != inlen)
208                 return ret;
209
210         if (!iv)
211                 iv = default_iv;
212         if (CRYPTO_memcmp(out, iv, 8))
213                 {
214                 OPENSSL_cleanse(out, inlen);
215                 return 0;
216                 }
217         return inlen;
218         }
219
220 /** Wrapping according to RFC 5649 section 4.1.
221  *
222  *  @param[in]  key    Key value. 
223  *  @param[in]  icv    (Non-standard) IV, 4 bytes. NULL = use default_aiv.
224  *  @param[out] out    Cipher text. Minimal buffer length = (inlen + 15) bytes.
225  *                     Input and output buffers can overlap if block function
226  *                     supports that.
227  *  @param[in]  in     Plain text as n 64-bit blocks, n >= 2.
228  *  @param[in]  inlen  Length of in.
229  *  @param[in]  block  Block processing function.
230  *  @return            0 if inlen is out of range [1, CRYPTO128_WRAP_MAX].
231  *                     Output length if wrapping succeeded.
232  */
233 size_t CRYPTO_128_wrap_pad(void *key, const unsigned char *icv,
234                 unsigned char *out,
235                 const unsigned char *in, size_t inlen, block128_f block)
236         {
237         /* n: number of 64-bit blocks in the padded key data */
238         const size_t blocks_padded = (inlen + 8) / 8;
239         const size_t padded_len = blocks_padded * 8;
240         const size_t padding_len = padded_len - inlen;
241         /* RFC 5649 section 3: Alternative Initial Value */
242         unsigned char aiv[8];
243         int ret;
244
245         /* Section 1: use 32-bit fixed field for plaintext octet length */
246         if (inlen == 0 || inlen >= CRYPTO128_WRAP_MAX)
247                 return 0;
248
249         /* Section 3: Alternative Initial Value */
250         if (!icv)
251                 memcpy(aiv, default_aiv, 4);
252         else
253                 memcpy(aiv, icv, 4); /* Standard doesn't mention this. */
254
255         aiv[4] = (inlen >> 24) & 0xFF;
256         aiv[5] = (inlen >> 16) & 0xFF;
257         aiv[6] = (inlen >> 8) & 0xFF;
258         aiv[7] = inlen & 0xFF;
259
260         if (padded_len == 8)
261                 {
262                 /* Section 4.1 - special case in step 2:
263                  * If the padded plaintext contains exactly eight octets, then
264                  * prepend the AIV and encrypt the resulting 128-bit block
265                  * using AES in ECB mode. */
266                 memmove(out + 8, in, inlen);
267                 memcpy(out, aiv, 8);
268                 memset(out + 8 + inlen, 0, padding_len);
269                 block(out, out, key);
270                 ret = 16; /* AIV + padded input */
271                 }
272                 else
273                 {
274                 memmove(out, in, inlen);
275                 memset(out + inlen, 0, padding_len); /* Section 4.1 step 1 */
276                 ret = CRYPTO_128_wrap(key, aiv, out, out, padded_len, block);
277                 }
278
279         return ret;
280         }
281
282 /** Unwrapping according to RFC 5649 section 4.2.
283  *
284  *  @param[in]  key    Key value. 
285  *  @param[in]  icv    (Non-standard) IV, 4 bytes. NULL = use default_aiv.
286  *  @param[out] out    Plain text. Minimal buffer length = inlen bytes.
287  *                     Input and output buffers can overlap if block function
288  *                     supports that.
289  *  @param[in]  in     Ciphertext text as n 64-bit blocks
290  *  @param[in]  inlen  Length of in.
291  *  @param[in]  block  Block processing function.
292  *  @return            0 if inlen is out of range [16, CRYPTO128_WRAP_MAX],
293  *                     or if inlen is not multiply of 8
294  *                     or if IV and message length indicator doesn't match.
295  *                     Output length if unwrapping succeeded and IV matches.
296  */
297 size_t CRYPTO_128_unwrap_pad(void *key, const unsigned char *icv,
298                 unsigned char *out,
299                 const unsigned char *in, size_t inlen, block128_f block)
300         {
301         /* n: number of 64-bit blocks in the padded key data */
302         size_t n = inlen / 8 - 1;
303         size_t padded_len;
304         size_t padding_len;
305         size_t ptext_len;
306         /* RFC 5649 section 3: Alternative Initial Value */
307         unsigned char aiv[8];
308         static unsigned char zeros[8] = {0x0};
309         size_t ret;
310
311         /* Section 4.2: Cipher text length has to be (n+1) 64-bit blocks. */
312         if ((inlen & 0x7) != 0 || inlen < 16 || inlen >= CRYPTO128_WRAP_MAX)
313                 return 0;
314
315         memmove(out, in, inlen);
316         if (inlen == 16)
317                 {
318                 /* Section 4.2 - special case in step 1:
319                  * When n=1, the ciphertext contains exactly two 64-bit
320                  * blocks and they are decrypted as a single AES
321                  * block using AES in ECB mode:
322                  * AIV | P[1] = DEC(K, C[0] | C[1])
323                  */
324                 block(out, out, key);
325                 memcpy(aiv, out, 8);
326                 /* Remove AIV */
327                 memmove(out, out + 8, 8);
328                 padded_len = 8;
329                 }
330                 else
331                 {
332                 padded_len = inlen - 8;
333                 ret = crypto_128_unwrap_raw(key, aiv, out, out, inlen, block);
334                 if (padded_len != ret)
335                         {
336                         OPENSSL_cleanse(out, inlen);
337                         return 0;
338                         }
339                 }
340
341         /* Section 3: AIV checks: Check that MSB(32,A) = A65959A6.
342          * Optionally a user-supplied value can be used
343          * (even if standard doesn't mention this). */
344         if ((!icv && CRYPTO_memcmp(aiv, default_aiv, 4))
345                 || (icv && CRYPTO_memcmp(aiv, icv, 4)))
346                 {
347                 OPENSSL_cleanse(out, inlen);
348                 return 0;
349                 }
350
351         /* Check that 8*(n-1) < LSB(32,AIV) <= 8*n.
352          * If so, let ptext_len = LSB(32,AIV). */
353
354         ptext_len = (aiv[4] << 24) | (aiv[5] << 16) | (aiv[6] << 8) | aiv[7];
355         if (8*(n-1) >= ptext_len || ptext_len > 8*n)
356                 {
357                 OPENSSL_cleanse(out, inlen);
358                 return 0;
359                 }
360
361         /* Check that the rightmost padding_len octets of the output data
362          * are zero. */
363         padding_len = padded_len - ptext_len;
364         if (CRYPTO_memcmp(out + ptext_len, zeros, padding_len) != 0)
365                 {
366                 OPENSSL_cleanse(out, inlen);
367                 return 0;
368                 }
369
370         /* Section 4.2 step 3: Remove padding */
371         return ptext_len;
372         }