1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2 
3 /* Stolen from glibc and converted to our style. In glibc it comes with the following copyright blurb: */
4 
5 /* Functions to compute SHA256 message digest of files or memory blocks.
6    according to the definition of SHA256 in FIPS 180-2.
7    Copyright (C) 2007-2019 Free Software Foundation, Inc.
8    This file is part of the GNU C Library.
9 
10    The GNU C Library is free software; you can redistribute it and/or
11    modify it under the terms of the GNU Lesser General Public
12    License as published by the Free Software Foundation; either
13    version 2.1 of the License, or (at your option) any later version.
14 
15    The GNU C Library is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18    Lesser General Public License for more details.
19 
20    You should have received a copy of the GNU Lesser General Public
21    License along with the GNU C Library; if not, see
22    <http://www.gnu.org/licenses/>.  */
23 
24 /* Written by Ulrich Drepper <drepper@redhat.com>, 2007.  */
25 
26 #ifndef SD_BOOT
27 #include <string.h>
28 #endif
29 
30 #include "macro-fundamental.h"
31 #include "sha256.h"
32 
33 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
34 # define SWAP(n)                                                        \
35         (((n) << 24) | (((n) & 0xff00) << 8) | (((n) >> 8) & 0xff00) | ((n) >> 24))
36 # define SWAP64(n)                              \
37         (((n) << 56)                            \
38          | (((n) & 0xff00) << 40)               \
39          | (((n) & 0xff0000) << 24)             \
40          | (((n) & 0xff000000) << 8)            \
41          | (((n) >> 8) & 0xff000000)            \
42          | (((n) >> 24) & 0xff0000)             \
43          | (((n) >> 40) & 0xff00)               \
44          | ((n) >> 56))
45 #else
46 # define SWAP(n) (n)
47 # define SWAP64(n) (n)
48 #endif
49 
50 /* This array contains the bytes used to pad the buffer to the next
51    64-byte boundary.  (FIPS 180-2:5.1.1)  */
52 static const uint8_t fillbuf[64] = {
53         0x80, 0 /* , 0, 0, ...  */
54 };
55 
56 /* Constants for SHA256 from FIPS 180-2:4.2.2.  */
57 static const uint32_t K[64] = {
58         0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,
59         0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
60         0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
61         0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
62         0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
63         0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
64         0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
65         0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
66         0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
67         0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
68         0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
69         0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
70         0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,
71         0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
72         0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
73         0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
74 };
75 
76 static void sha256_process_block(const void *, size_t, struct sha256_ctx *);
77 
78 /* Initialize structure containing state of computation.
79    (FIPS 180-2:5.3.2)  */
sha256_init_ctx(struct sha256_ctx * ctx)80 void sha256_init_ctx(struct sha256_ctx *ctx) {
81         assert(ctx);
82 
83         ctx->H[0] = 0x6a09e667;
84         ctx->H[1] = 0xbb67ae85;
85         ctx->H[2] = 0x3c6ef372;
86         ctx->H[3] = 0xa54ff53a;
87         ctx->H[4] = 0x510e527f;
88         ctx->H[5] = 0x9b05688c;
89         ctx->H[6] = 0x1f83d9ab;
90         ctx->H[7] = 0x5be0cd19;
91 
92         ctx->total64 = 0;
93         ctx->buflen = 0;
94 }
95 
96 /* Process the remaining bytes in the internal buffer and the usual
97    prolog according to the standard and write the result to RESBUF.
98 
99    IMPORTANT: On some systems it is required that RESBUF is correctly
100    aligned for a 32 bits value.  */
sha256_finish_ctx(struct sha256_ctx * ctx,void * resbuf)101 void *sha256_finish_ctx(struct sha256_ctx *ctx, void *resbuf) {
102         /* Take yet unprocessed bytes into account.  */
103         uint32_t bytes = ctx->buflen;
104         size_t pad;
105 
106         assert(ctx);
107         assert(resbuf);
108 
109         /* Now count remaining bytes.  */
110         ctx->total64 += bytes;
111 
112         pad = bytes >= 56 ? 64 + 56 - bytes : 56 - bytes;
113         memcpy(&ctx->buffer[bytes], fillbuf, pad);
114 
115         /* Put the 64-bit file length in *bits* at the end of the buffer.  */
116         ctx->buffer32[(bytes + pad + 4) / 4] = SWAP(ctx->total[TOTAL64_low] << 3);
117         ctx->buffer32[(bytes + pad) / 4] = SWAP((ctx->total[TOTAL64_high] << 3)
118                                                 | (ctx->total[TOTAL64_low] >> 29));
119 
120         /* Process last bytes.  */
121         sha256_process_block(ctx->buffer, bytes + pad + 8, ctx);
122 
123         /* Put result from CTX in first 32 bytes following RESBUF.  */
124         for (size_t i = 0; i < 8; ++i)
125                 ((uint32_t *) resbuf)[i] = SWAP(ctx->H[i]);
126 
127         return resbuf;
128 }
129 
sha256_process_bytes(const void * buffer,size_t len,struct sha256_ctx * ctx)130 void sha256_process_bytes(const void *buffer, size_t len, struct sha256_ctx *ctx) {
131         assert(buffer);
132         assert(ctx);
133 
134         /* When we already have some bits in our internal buffer concatenate
135            both inputs first.  */
136 
137         if (ctx->buflen != 0) {
138                 size_t left_over = ctx->buflen;
139                 size_t add = 128 - left_over > len ? len : 128 - left_over;
140 
141                 memcpy(&ctx->buffer[left_over], buffer, add);
142                 ctx->buflen += add;
143 
144                 if (ctx->buflen > 64) {
145                         sha256_process_block(ctx->buffer, ctx->buflen & ~63, ctx);
146 
147                         ctx->buflen &= 63;
148                         /* The regions in the following copy operation cannot overlap.  */
149                         memcpy(ctx->buffer, &ctx->buffer[(left_over + add) & ~63],
150                                 ctx->buflen);
151                 }
152 
153                 buffer = (const char *) buffer + add;
154                 len -= add;
155         }
156 
157         /* Process available complete blocks.  */
158         if (len >= 64) {
159 
160 /* The condition below is from glibc's string/string-inline.c.
161  * See definition of _STRING_INLINE_unaligned. */
162 #if !defined(__mc68020__) && !defined(__s390__) && !defined(__i386__)
163 
164 /* To check alignment gcc has an appropriate operator. Other compilers don't.  */
165 # if __GNUC__ >= 2
166 #  define UNALIGNED_P(p) (((size_t) p) % __alignof__(uint32_t) != 0)
167 # else
168 #  define UNALIGNED_P(p) (((size_t) p) % sizeof(uint32_t) != 0)
169 # endif
170                 if (UNALIGNED_P(buffer))
171                         while (len > 64) {
172                                 memcpy(ctx->buffer, buffer, 64);
173                                 sha256_process_block(ctx->buffer, 64, ctx);
174                                 buffer = (const char *) buffer + 64;
175                                 len -= 64;
176                         }
177                 else
178 #endif
179                 {
180                         sha256_process_block(buffer, len & ~63, ctx);
181                         buffer = (const char *) buffer + (len & ~63);
182                         len &= 63;
183                 }
184         }
185 
186         /* Move remaining bytes into internal buffer.  */
187         if (len > 0) {
188                 size_t left_over = ctx->buflen;
189 
190                 memcpy(&ctx->buffer[left_over], buffer, len);
191                 left_over += len;
192                 if (left_over >= 64) {
193                         sha256_process_block(ctx->buffer, 64, ctx);
194                         left_over -= 64;
195                         memcpy(ctx->buffer, &ctx->buffer[64], left_over);
196                 }
197                 ctx->buflen = left_over;
198         }
199 }
200 
201 
202 /* Process LEN bytes of BUFFER, accumulating context into CTX.
203    It is assumed that LEN % 64 == 0.  */
sha256_process_block(const void * buffer,size_t len,struct sha256_ctx * ctx)204 static void sha256_process_block(const void *buffer, size_t len, struct sha256_ctx *ctx) {
205         const uint32_t *words = buffer;
206         size_t nwords = len / sizeof(uint32_t);
207 
208         assert(buffer);
209         assert(ctx);
210 
211         uint32_t a = ctx->H[0];
212         uint32_t b = ctx->H[1];
213         uint32_t c = ctx->H[2];
214         uint32_t d = ctx->H[3];
215         uint32_t e = ctx->H[4];
216         uint32_t f = ctx->H[5];
217         uint32_t g = ctx->H[6];
218         uint32_t h = ctx->H[7];
219 
220         /* First increment the byte count.  FIPS 180-2 specifies the possible
221            length of the file up to 2^64 bits.  Here we only compute the
222            number of bytes.  */
223         ctx->total64 += len;
224 
225         /* Process all bytes in the buffer with 64 bytes in each round of
226            the loop.  */
227         while (nwords > 0) {
228                 uint32_t W[64];
229                 uint32_t a_save = a;
230                 uint32_t b_save = b;
231                 uint32_t c_save = c;
232                 uint32_t d_save = d;
233                 uint32_t e_save = e;
234                 uint32_t f_save = f;
235                 uint32_t g_save = g;
236                 uint32_t h_save = h;
237 
238                 /* Operators defined in FIPS 180-2:4.1.2.  */
239 #define Ch(x, y, z) ((x & y) ^ (~x & z))
240 #define Maj(x, y, z) ((x & y) ^ (x & z) ^ (y & z))
241 #define S0(x) (CYCLIC (x, 2) ^ CYCLIC (x, 13) ^ CYCLIC (x, 22))
242 #define S1(x) (CYCLIC (x, 6) ^ CYCLIC (x, 11) ^ CYCLIC (x, 25))
243 #define R0(x) (CYCLIC (x, 7) ^ CYCLIC (x, 18) ^ (x >> 3))
244 #define R1(x) (CYCLIC (x, 17) ^ CYCLIC (x, 19) ^ (x >> 10))
245 
246                 /* It is unfortunate that C does not provide an operator for
247                    cyclic rotation.  Hope the C compiler is smart enough.  */
248 #define CYCLIC(w, s) ((w >> s) | (w << (32 - s)))
249 
250                 /* Compute the message schedule according to FIPS 180-2:6.2.2 step 2.  */
251                 for (size_t t = 0; t < 16; ++t) {
252                         W[t] = SWAP (*words);
253                         ++words;
254                 }
255                 for (size_t t = 16; t < 64; ++t)
256                         W[t] = R1 (W[t - 2]) + W[t - 7] + R0 (W[t - 15]) + W[t - 16];
257 
258                 /* The actual computation according to FIPS 180-2:6.2.2 step 3.  */
259                 for (size_t t = 0; t < 64; ++t) {
260                         uint32_t T1 = h + S1 (e) + Ch (e, f, g) + K[t] + W[t];
261                         uint32_t T2 = S0 (a) + Maj (a, b, c);
262                         h = g;
263                         g = f;
264                         f = e;
265                         e = d + T1;
266                         d = c;
267                         c = b;
268                         b = a;
269                         a = T1 + T2;
270                 }
271 
272                 /* Add the starting values of the context according to FIPS 180-2:6.2.2
273                    step 4.  */
274                 a += a_save;
275                 b += b_save;
276                 c += c_save;
277                 d += d_save;
278                 e += e_save;
279                 f += f_save;
280                 g += g_save;
281                 h += h_save;
282 
283                 /* Prepare for the next round.  */
284                 nwords -= 16;
285         }
286 
287         /* Put checksum in context given as argument.  */
288         ctx->H[0] = a;
289         ctx->H[1] = b;
290         ctx->H[2] = c;
291         ctx->H[3] = d;
292         ctx->H[4] = e;
293         ctx->H[5] = f;
294         ctx->H[6] = g;
295         ctx->H[7] = h;
296 }
297