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