1/* ====================================================================
2 * Copyright (c) 2008 The OpenSSL Project.  All rights reserved.
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 *
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer.
10 *
11 * 2. Redistributions in binary form must reproduce the above copyright
12 *    notice, this list of conditions and the following disclaimer in
13 *    the documentation and/or other materials provided with the
14 *    distribution.
15 *
16 * 3. All advertising materials mentioning features or use of this
17 *    software must display the following acknowledgment:
18 *    "This product includes software developed by the OpenSSL Project
19 *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
20 *
21 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
22 *    endorse or promote products derived from this software without
23 *    prior written permission. For written permission, please contact
24 *    openssl-core@openssl.org.
25 *
26 * 5. Products derived from this software may not be called "OpenSSL"
27 *    nor may "OpenSSL" appear in their names without prior written
28 *    permission of the OpenSSL Project.
29 *
30 * 6. Redistributions of any form whatsoever must retain the following
31 *    acknowledgment:
32 *    "This product includes software developed by the OpenSSL Project
33 *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
34 *
35 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
36 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
37 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
38 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
39 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
41 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
42 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
43 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
44 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
45 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
46 * OF THE POSSIBILITY OF SUCH DAMAGE.
47 * ==================================================================== */
48#include <openssl/modes.h>
49
50#include <assert.h>
51#include <string.h>
52
53#include "internal.h"
54
55
56/* NOTE: the IV/counter CTR mode is big-endian.  The code itself
57 * is endian-neutral. */
58
59/* increment counter (128-bit int) by 1 */
60static void ctr128_inc(uint8_t *counter) {
61  uint32_t n = 16;
62  uint8_t c;
63
64  do {
65    --n;
66    c = counter[n];
67    ++c;
68    counter[n] = c;
69    if (c) {
70      return;
71    }
72  } while (n);
73}
74
75/* The input encrypted as though 128bit counter mode is being used.  The extra
76 * state information to record how much of the 128bit block we have used is
77 * contained in *num, and the encrypted counter is kept in ecount_buf.  Both
78 * *num and ecount_buf must be initialised with zeros before the first call to
79 * CRYPTO_ctr128_encrypt().
80 *
81 * This algorithm assumes that the counter is in the x lower bits of the IV
82 * (ivec), and that the application has full control over overflow and the rest
83 * of the IV.  This implementation takes NO responsibility for checking that
84 * the counter doesn't overflow into the rest of the IV when incremented. */
85void CRYPTO_ctr128_encrypt(const uint8_t *in, uint8_t *out, size_t len,
86                           const void *key, uint8_t ivec[16],
87                           uint8_t ecount_buf[16], unsigned int *num,
88                           block128_f block) {
89  unsigned int n;
90
91  assert(key && ecount_buf && num);
92  assert(len == 0 || (in && out));
93  assert(*num < 16);
94  assert((16 % sizeof(size_t)) == 0);
95
96  n = *num;
97
98  while (n && len) {
99    *(out++) = *(in++) ^ ecount_buf[n];
100    --len;
101    n = (n + 1) % 16;
102  }
103
104#if STRICT_ALIGNMENT
105  if (((size_t)in | (size_t)out | (size_t)ivec) % sizeof(size_t) != 0) {
106    size_t l = 0;
107    while (l < len) {
108      if (n == 0) {
109        (*block)(ivec, ecount_buf, key);
110        ctr128_inc(ivec);
111      }
112      out[l] = in[l] ^ ecount_buf[n];
113      ++l;
114      n = (n + 1) % 16;
115    }
116
117    *num = n;
118    return;
119  }
120#endif
121
122  while (len >= 16) {
123    (*block)(ivec, ecount_buf, key);
124    ctr128_inc(ivec);
125    for (; n < 16; n += sizeof(size_t)) {
126      *(size_t *)(out + n) = *(size_t *)(in + n) ^ *(size_t *)(ecount_buf + n);
127    }
128    len -= 16;
129    out += 16;
130    in += 16;
131    n = 0;
132  }
133  if (len) {
134    (*block)(ivec, ecount_buf, key);
135    ctr128_inc(ivec);
136    while (len--) {
137      out[n] = in[n] ^ ecount_buf[n];
138      ++n;
139    }
140  }
141  *num = n;
142}
143
144/* increment upper 96 bits of 128-bit counter by 1 */
145static void ctr96_inc(uint8_t *counter) {
146  uint32_t n = 12;
147  uint8_t c;
148
149  do {
150    --n;
151    c = counter[n];
152    ++c;
153    counter[n] = c;
154    if (c) {
155      return;
156    }
157  } while (n);
158}
159
160void CRYPTO_ctr128_encrypt_ctr32(const uint8_t *in, uint8_t *out,
161                                 size_t len, const void *key,
162                                 uint8_t ivec[16],
163                                 uint8_t ecount_buf[16],
164                                 unsigned int *num, ctr128_f func) {
165  unsigned int n, ctr32;
166
167  assert(key && ecount_buf && num);
168  assert(len == 0 || (in && out));
169  assert(*num < 16);
170
171  n = *num;
172
173  while (n && len) {
174    *(out++) = *(in++) ^ ecount_buf[n];
175    --len;
176    n = (n + 1) % 16;
177  }
178
179  ctr32 = GETU32(ivec + 12);
180  while (len >= 16) {
181    size_t blocks = len / 16;
182    /* 1<<28 is just a not-so-small yet not-so-large number...
183     * Below condition is practically never met, but it has to
184     * be checked for code correctness. */
185    if (sizeof(size_t) > sizeof(unsigned int) && blocks > (1U << 28)) {
186      blocks = (1U << 28);
187    }
188    /* As (*func) operates on 32-bit counter, caller
189     * has to handle overflow. 'if' below detects the
190     * overflow, which is then handled by limiting the
191     * amount of blocks to the exact overflow point... */
192    ctr32 += (uint32_t)blocks;
193    if (ctr32 < blocks) {
194      blocks -= ctr32;
195      ctr32 = 0;
196    }
197    (*func)(in, out, blocks, key, ivec);
198    /* (*func) does not update ivec, caller does: */
199    PUTU32(ivec + 12, ctr32);
200    /* ... overflow was detected, propogate carry. */
201    if (ctr32 == 0) {
202      ctr96_inc(ivec);
203    }
204    blocks *= 16;
205    len -= blocks;
206    out += blocks;
207    in += blocks;
208  }
209  if (len) {
210    memset(ecount_buf, 0, 16);
211    (*func)(ecount_buf, ecount_buf, 1, key, ivec);
212    ++ctr32;
213    PUTU32(ivec + 12, ctr32);
214    if (ctr32 == 0) {
215      ctr96_inc(ivec);
216    }
217    while (len--) {
218      out[n] = in[n] ^ ecount_buf[n];
219      ++n;
220    }
221  }
222
223  *num = n;
224}
225