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