]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - lib/libcrypt/crypt-sha256.c
MFV r329799, r329800:
[FreeBSD/FreeBSD.git] / lib / libcrypt / crypt-sha256.c
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2011 The FreeBSD Project. All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25  * SUCH DAMAGE.
26  */
27
28 /* Based on:
29  * SHA256-based Unix crypt implementation. Released into the Public Domain by
30  * Ulrich Drepper <drepper@redhat.com>. */
31
32 #include <sys/cdefs.h>
33 __FBSDID("$FreeBSD$");
34
35 #include <sys/endian.h>
36 #include <sys/param.h>
37
38 #include <errno.h>
39 #include <limits.h>
40 #include <sha256.h>
41 #include <stdbool.h>
42 #include <stdint.h>
43 #include <stdio.h>
44 #include <stdlib.h>
45 #include <string.h>
46
47 #include "crypt.h"
48
49 /* Define our magic string to mark salt for SHA256 "encryption" replacement. */
50 static const char sha256_salt_prefix[] = "$5$";
51
52 /* Prefix for optional rounds specification. */
53 static const char sha256_rounds_prefix[] = "rounds=";
54
55 /* Maximum salt string length. */
56 #define SALT_LEN_MAX 16
57 /* Default number of rounds if not explicitly specified. */
58 #define ROUNDS_DEFAULT 5000
59 /* Minimum number of rounds. */
60 #define ROUNDS_MIN 1000
61 /* Maximum number of rounds. */
62 #define ROUNDS_MAX 999999999
63
64 int
65 crypt_sha256(const char *key, const char *salt, char *buffer)
66 {
67         u_long srounds;
68         uint8_t alt_result[32], temp_result[32];
69         SHA256_CTX ctx, alt_ctx;
70         size_t salt_len, key_len, cnt, rounds;
71         char *cp, *copied_key, *copied_salt, *p_bytes, *s_bytes, *endp;
72         const char *num;
73         bool rounds_custom;
74
75         copied_key = NULL;
76         copied_salt = NULL;
77
78         /* Default number of rounds. */
79         rounds = ROUNDS_DEFAULT;
80         rounds_custom = false;
81
82         /* Find beginning of salt string. The prefix should normally always
83          * be present. Just in case it is not. */
84         if (strncmp(sha256_salt_prefix, salt, sizeof(sha256_salt_prefix) - 1) == 0)
85                 /* Skip salt prefix. */
86                 salt += sizeof(sha256_salt_prefix) - 1;
87
88         if (strncmp(salt, sha256_rounds_prefix, sizeof(sha256_rounds_prefix) - 1)
89             == 0) {
90                 num = salt + sizeof(sha256_rounds_prefix) - 1;
91                 srounds = strtoul(num, &endp, 10);
92
93                 if (*endp == '$') {
94                         salt = endp + 1;
95                         rounds = MAX(ROUNDS_MIN, MIN(srounds, ROUNDS_MAX));
96                         rounds_custom = true;
97                 }
98         }
99
100         salt_len = MIN(strcspn(salt, "$"), SALT_LEN_MAX);
101         key_len = strlen(key);
102
103         /* Prepare for the real work. */
104         SHA256_Init(&ctx);
105
106         /* Add the key string. */
107         SHA256_Update(&ctx, key, key_len);
108
109         /* The last part is the salt string. This must be at most 8
110          * characters and it ends at the first `$' character (for
111          * compatibility with existing implementations). */
112         SHA256_Update(&ctx, salt, salt_len);
113
114         /* Compute alternate SHA256 sum with input KEY, SALT, and KEY. The
115          * final result will be added to the first context. */
116         SHA256_Init(&alt_ctx);
117
118         /* Add key. */
119         SHA256_Update(&alt_ctx, key, key_len);
120
121         /* Add salt. */
122         SHA256_Update(&alt_ctx, salt, salt_len);
123
124         /* Add key again. */
125         SHA256_Update(&alt_ctx, key, key_len);
126
127         /* Now get result of this (32 bytes) and add it to the other context. */
128         SHA256_Final(alt_result, &alt_ctx);
129
130         /* Add for any character in the key one byte of the alternate sum. */
131         for (cnt = key_len; cnt > 32; cnt -= 32)
132                 SHA256_Update(&ctx, alt_result, 32);
133         SHA256_Update(&ctx, alt_result, cnt);
134
135         /* Take the binary representation of the length of the key and for
136          * every 1 add the alternate sum, for every 0 the key. */
137         for (cnt = key_len; cnt > 0; cnt >>= 1)
138                 if ((cnt & 1) != 0)
139                         SHA256_Update(&ctx, alt_result, 32);
140                 else
141                         SHA256_Update(&ctx, key, key_len);
142
143         /* Create intermediate result. */
144         SHA256_Final(alt_result, &ctx);
145
146         /* Start computation of P byte sequence. */
147         SHA256_Init(&alt_ctx);
148
149         /* For every character in the password add the entire password. */
150         for (cnt = 0; cnt < key_len; ++cnt)
151                 SHA256_Update(&alt_ctx, key, key_len);
152
153         /* Finish the digest. */
154         SHA256_Final(temp_result, &alt_ctx);
155
156         /* Create byte sequence P. */
157         cp = p_bytes = alloca(key_len);
158         for (cnt = key_len; cnt >= 32; cnt -= 32) {
159                 memcpy(cp, temp_result, 32);
160                 cp += 32;
161         }
162         memcpy(cp, temp_result, cnt);
163
164         /* Start computation of S byte sequence. */
165         SHA256_Init(&alt_ctx);
166
167         /* For every character in the password add the entire password. */
168         for (cnt = 0; cnt < 16 + alt_result[0]; ++cnt)
169                 SHA256_Update(&alt_ctx, salt, salt_len);
170
171         /* Finish the digest. */
172         SHA256_Final(temp_result, &alt_ctx);
173
174         /* Create byte sequence S. */
175         cp = s_bytes = alloca(salt_len);
176         for (cnt = salt_len; cnt >= 32; cnt -= 32) {
177                 memcpy(cp, temp_result, 32);
178                 cp += 32;
179         }
180         memcpy(cp, temp_result, cnt);
181
182         /* Repeatedly run the collected hash value through SHA256 to burn CPU
183          * cycles. */
184         for (cnt = 0; cnt < rounds; ++cnt) {
185                 /* New context. */
186                 SHA256_Init(&ctx);
187
188                 /* Add key or last result. */
189                 if ((cnt & 1) != 0)
190                         SHA256_Update(&ctx, p_bytes, key_len);
191                 else
192                         SHA256_Update(&ctx, alt_result, 32);
193
194                 /* Add salt for numbers not divisible by 3. */
195                 if (cnt % 3 != 0)
196                         SHA256_Update(&ctx, s_bytes, salt_len);
197
198                 /* Add key for numbers not divisible by 7. */
199                 if (cnt % 7 != 0)
200                         SHA256_Update(&ctx, p_bytes, key_len);
201
202                 /* Add key or last result. */
203                 if ((cnt & 1) != 0)
204                         SHA256_Update(&ctx, alt_result, 32);
205                 else
206                         SHA256_Update(&ctx, p_bytes, key_len);
207
208                 /* Create intermediate result. */
209                 SHA256_Final(alt_result, &ctx);
210         }
211
212         /* Now we can construct the result string. It consists of three
213          * parts. */
214         cp = stpcpy(buffer, sha256_salt_prefix);
215
216         if (rounds_custom)
217                 cp += sprintf(cp, "%s%zu$", sha256_rounds_prefix, rounds);
218
219         cp = stpncpy(cp, salt, salt_len);
220
221         *cp++ = '$';
222
223         b64_from_24bit(alt_result[0], alt_result[10], alt_result[20], 4, &cp);
224         b64_from_24bit(alt_result[21], alt_result[1], alt_result[11], 4, &cp);
225         b64_from_24bit(alt_result[12], alt_result[22], alt_result[2], 4, &cp);
226         b64_from_24bit(alt_result[3], alt_result[13], alt_result[23], 4, &cp);
227         b64_from_24bit(alt_result[24], alt_result[4], alt_result[14], 4, &cp);
228         b64_from_24bit(alt_result[15], alt_result[25], alt_result[5], 4, &cp);
229         b64_from_24bit(alt_result[6], alt_result[16], alt_result[26], 4, &cp);
230         b64_from_24bit(alt_result[27], alt_result[7], alt_result[17], 4, &cp);
231         b64_from_24bit(alt_result[18], alt_result[28], alt_result[8], 4, &cp);
232         b64_from_24bit(alt_result[9], alt_result[19], alt_result[29], 4, &cp);
233         b64_from_24bit(0, alt_result[31], alt_result[30], 3, &cp);
234         *cp = '\0';     /* Terminate the string. */
235
236         /* Clear the buffer for the intermediate result so that people
237          * attaching to processes or reading core dumps cannot get any
238          * information. We do it in this way to clear correct_words[] inside
239          * the SHA256 implementation as well. */
240         SHA256_Init(&ctx);
241         SHA256_Final(alt_result, &ctx);
242         memset(temp_result, '\0', sizeof(temp_result));
243         memset(p_bytes, '\0', key_len);
244         memset(s_bytes, '\0', salt_len);
245         memset(&ctx, '\0', sizeof(ctx));
246         memset(&alt_ctx, '\0', sizeof(alt_ctx));
247         if (copied_key != NULL)
248                 memset(copied_key, '\0', key_len);
249         if (copied_salt != NULL)
250                 memset(copied_salt, '\0', salt_len);
251
252         return (0);
253 }
254
255 #ifdef TEST
256
257 static const struct {
258         const char *input;
259         const char result[32];
260 } tests[] =
261 {
262         /* Test vectors from FIPS 180-2: appendix B.1. */
263         {
264                 "abc",
265                 "\xba\x78\x16\xbf\x8f\x01\xcf\xea\x41\x41\x40\xde\x5d\xae\x22\x23"
266                 "\xb0\x03\x61\xa3\x96\x17\x7a\x9c\xb4\x10\xff\x61\xf2\x00\x15\xad"
267         },
268         /* Test vectors from FIPS 180-2: appendix B.2. */
269         {
270                 "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
271                 "\x24\x8d\x6a\x61\xd2\x06\x38\xb8\xe5\xc0\x26\x93\x0c\x3e\x60\x39"
272                 "\xa3\x3c\xe4\x59\x64\xff\x21\x67\xf6\xec\xed\xd4\x19\xdb\x06\xc1"
273         },
274         /* Test vectors from the NESSIE project. */
275         {
276                 "",
277                 "\xe3\xb0\xc4\x42\x98\xfc\x1c\x14\x9a\xfb\xf4\xc8\x99\x6f\xb9\x24"
278                 "\x27\xae\x41\xe4\x64\x9b\x93\x4c\xa4\x95\x99\x1b\x78\x52\xb8\x55"
279         },
280         {
281                 "a",
282                 "\xca\x97\x81\x12\xca\x1b\xbd\xca\xfa\xc2\x31\xb3\x9a\x23\xdc\x4d"
283                 "\xa7\x86\xef\xf8\x14\x7c\x4e\x72\xb9\x80\x77\x85\xaf\xee\x48\xbb"
284         },
285         {
286                 "message digest",
287                 "\xf7\x84\x6f\x55\xcf\x23\xe1\x4e\xeb\xea\xb5\xb4\xe1\x55\x0c\xad"
288                 "\x5b\x50\x9e\x33\x48\xfb\xc4\xef\xa3\xa1\x41\x3d\x39\x3c\xb6\x50"
289         },
290         {
291                 "abcdefghijklmnopqrstuvwxyz",
292                 "\x71\xc4\x80\xdf\x93\xd6\xae\x2f\x1e\xfa\xd1\x44\x7c\x66\xc9\x52"
293                 "\x5e\x31\x62\x18\xcf\x51\xfc\x8d\x9e\xd8\x32\xf2\xda\xf1\x8b\x73"
294         },
295         {
296                 "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
297                 "\x24\x8d\x6a\x61\xd2\x06\x38\xb8\xe5\xc0\x26\x93\x0c\x3e\x60\x39"
298                 "\xa3\x3c\xe4\x59\x64\xff\x21\x67\xf6\xec\xed\xd4\x19\xdb\x06\xc1"
299         },
300         {
301                 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
302                 "\xdb\x4b\xfc\xbd\x4d\xa0\xcd\x85\xa6\x0c\x3c\x37\xd3\xfb\xd8\x80"
303                 "\x5c\x77\xf1\x5f\xc6\xb1\xfd\xfe\x61\x4e\xe0\xa7\xc8\xfd\xb4\xc0"
304         },
305         {
306                 "123456789012345678901234567890123456789012345678901234567890"
307                 "12345678901234567890",
308                 "\xf3\x71\xbc\x4a\x31\x1f\x2b\x00\x9e\xef\x95\x2d\xd8\x3c\xa8\x0e"
309                 "\x2b\x60\x02\x6c\x8e\x93\x55\x92\xd0\xf9\xc3\x08\x45\x3c\x81\x3e"
310         }
311 };
312
313 #define ntests (sizeof (tests) / sizeof (tests[0]))
314
315 static const struct {
316         const char *salt;
317         const char *input;
318         const char *expected;
319 } tests2[] =
320 {
321         {
322                 "$5$saltstring", "Hello world!",
323                 "$5$saltstring$5B8vYYiY.CVt1RlTTf8KbXBH3hsxY/GNooZaBBGWEc5"
324         },
325         {
326                 "$5$rounds=10000$saltstringsaltstring", "Hello world!",
327                 "$5$rounds=10000$saltstringsaltst$3xv.VbSHBb41AL9AvLeujZkZRBAwqFMz2."
328                 "opqey6IcA"
329         },
330         {
331                 "$5$rounds=5000$toolongsaltstring", "This is just a test",
332                 "$5$rounds=5000$toolongsaltstrin$Un/5jzAHMgOGZ5.mWJpuVolil07guHPvOW8"
333                 "mGRcvxa5"
334         },
335         {
336                 "$5$rounds=1400$anotherlongsaltstring",
337                 "a very much longer text to encrypt.  This one even stretches over more"
338                 "than one line.",
339                 "$5$rounds=1400$anotherlongsalts$Rx.j8H.h8HjEDGomFU8bDkXm3XIUnzyxf12"
340                 "oP84Bnq1"
341         },
342         {
343                 "$5$rounds=77777$short",
344                 "we have a short salt string but not a short password",
345                 "$5$rounds=77777$short$JiO1O3ZpDAxGJeaDIuqCoEFysAe1mZNJRs3pw0KQRd/"
346         },
347         {
348                 "$5$rounds=123456$asaltof16chars..", "a short string",
349                 "$5$rounds=123456$asaltof16chars..$gP3VQ/6X7UUEW3HkBn2w1/Ptq2jxPyzV/"
350                 "cZKmF/wJvD"
351         },
352         {
353                 "$5$rounds=10$roundstoolow", "the minimum number is still observed",
354                 "$5$rounds=1000$roundstoolow$yfvwcWrQ8l/K0DAWyuPMDNHpIVlTQebY9l/gL97"
355                 "2bIC"
356         },
357 };
358
359 #define ntests2 (sizeof (tests2) / sizeof (tests2[0]))
360
361 int
362 main(void)
363 {
364         SHA256_CTX ctx;
365         uint8_t sum[32];
366         int result = 0;
367         int i, cnt;
368
369         for (cnt = 0; cnt < (int)ntests; ++cnt) {
370                 SHA256_Init(&ctx);
371                 SHA256_Update(&ctx, tests[cnt].input, strlen(tests[cnt].input));
372                 SHA256_Final(sum, &ctx);
373                 if (memcmp(tests[cnt].result, sum, 32) != 0) {
374                         for (i = 0; i < 32; i++)
375                                 printf("%02X", tests[cnt].result[i]);
376                         printf("\n");
377                         for (i = 0; i < 32; i++)
378                                 printf("%02X", sum[i]);
379                         printf("\n");
380                         printf("test %d run %d failed\n", cnt, 1);
381                         result = 1;
382                 }
383
384                 SHA256_Init(&ctx);
385                 for (i = 0; tests[cnt].input[i] != '\0'; ++i)
386                         SHA256_Update(&ctx, &tests[cnt].input[i], 1);
387                 SHA256_Final(sum, &ctx);
388                 if (memcmp(tests[cnt].result, sum, 32) != 0) {
389                         for (i = 0; i < 32; i++)
390                                 printf("%02X", tests[cnt].result[i]);
391                         printf("\n");
392                         for (i = 0; i < 32; i++)
393                                 printf("%02X", sum[i]);
394                         printf("\n");
395                         printf("test %d run %d failed\n", cnt, 2);
396                         result = 1;
397                 }
398         }
399
400         /* Test vector from FIPS 180-2: appendix B.3. */
401         char buf[1000];
402
403         memset(buf, 'a', sizeof(buf));
404         SHA256_Init(&ctx);
405         for (i = 0; i < 1000; ++i)
406                 SHA256_Update(&ctx, buf, sizeof(buf));
407         SHA256_Final(sum, &ctx);
408         static const char expected[32] =
409         "\xcd\xc7\x6e\x5c\x99\x14\xfb\x92\x81\xa1\xc7\xe2\x84\xd7\x3e\x67"
410         "\xf1\x80\x9a\x48\xa4\x97\x20\x0e\x04\x6d\x39\xcc\xc7\x11\x2c\xd0";
411
412         if (memcmp(expected, sum, 32) != 0) {
413                 printf("test %d failed\n", cnt);
414                 result = 1;
415         }
416
417         for (cnt = 0; cnt < ntests2; ++cnt) {
418                 char *cp = crypt_sha256(tests2[cnt].input, tests2[cnt].salt);
419
420                 if (strcmp(cp, tests2[cnt].expected) != 0) {
421                         printf("test %d: expected \"%s\", got \"%s\"\n",
422                                cnt, tests2[cnt].expected, cp);
423                         result = 1;
424                 }
425         }
426
427         if (result == 0)
428                 puts("all tests OK");
429
430         return result;
431 }
432
433 #endif /* TEST */