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