xref: /PHP-7.3/ext/standard/crypt_sha256.c (revision cd8d5610)
1 /* SHA256-based Unix crypt implementation.
2    Released into the Public Domain by Ulrich Drepper <drepper@redhat.com>.  */
3 /* Windows VC++ port by Pierre Joye <pierre@php.net> */
4 
5 #include "php.h"
6 #include "php_main.h"
7 
8 #include <errno.h>
9 #include <limits.h>
10 
11 #ifdef PHP_WIN32
12 # define __alignof__ __alignof
13 # define alloca _alloca
14 #else
15 # ifndef HAVE_ALIGNOF
16 #  include <stddef.h>
17 #  define __alignof__(type) offsetof (struct { char c; type member;}, member)
18 # endif
19 #endif
20 
21 #include <stdio.h>
22 #include <stdlib.h>
23 
24 #ifdef PHP_WIN32
25 # include <string.h>
26 #else
27 # include <sys/param.h>
28 # include <sys/types.h>
29 # if HAVE_STRING_H
30 #  include <string.h>
31 # else
32 #  include <strings.h>
33 # endif
34 #endif
35 
__php_stpncpy(char * dst,const char * src,size_t len)36 char * __php_stpncpy(char *dst, const char *src, size_t len)
37 {
38 	size_t n = strlen(src);
39 	if (n > len) {
40 		n = len;
41 	}
42 	return strncpy(dst, src, len) + n;
43 }
44 
__php_mempcpy(void * dst,const void * src,size_t len)45 void * __php_mempcpy(void * dst, const void * src, size_t len)
46 {
47 	return (((char *)memcpy(dst, src, len)) + len);
48 }
49 
50 #ifndef MIN
51 # define MIN(a, b) (((a) < (b)) ? (a) : (b))
52 #endif
53 #ifndef MAX
54 # define MAX(a, b) (((a) > (b)) ? (a) : (b))
55 #endif
56 
57 /* Structure to save state of computation between the single steps.  */
58 struct sha256_ctx {
59 	uint32_t H[8];
60 
61 	uint32_t total[2];
62 	uint32_t buflen;
63 	char buffer[128]; /* NB: always correctly aligned for uint32_t.  */
64 };
65 
66 #if defined(PHP_WIN32) || (!defined(WORDS_BIGENDIAN))
67 # define SWAP(n) \
68     (((n) << 24) | (((n) & 0xff00) << 8) | (((n) >> 8) & 0xff00) | ((n) >> 24))
69 #else
70 # define SWAP(n) (n)
71 #endif
72 
73 /* This array contains the bytes used to pad the buffer to the next
74    64-byte boundary.  (FIPS 180-2:5.1.1)  */
75 static const unsigned char fillbuf[64] = { 0x80, 0 /* , 0, 0, ...  */ };
76 
77 
78 /* Constants for SHA256 from FIPS 180-2:4.2.2.  */
79 static const uint32_t K[64] = {
80 	0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,
81 	0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
82 	0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
83 	0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
84 	0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
85 	0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
86 	0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
87 	0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
88 	0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
89 	0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
90 	0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
91 	0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
92 	0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,
93 	0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
94 	0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
95 	0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
96 };
97 
98 
99 /* Process LEN bytes of BUFFER, accumulating context into CTX.
100    It is assumed that LEN % 64 == 0.  */
sha256_process_block(const void * buffer,size_t len,struct sha256_ctx * ctx)101 static void sha256_process_block (const void *buffer, size_t len, struct sha256_ctx *ctx) {
102 	const uint32_t *words = buffer;
103 	size_t nwords = len / sizeof (uint32_t);
104 	unsigned int t;
105 
106 	uint32_t a = ctx->H[0];
107 	uint32_t b = ctx->H[1];
108 	uint32_t c = ctx->H[2];
109 	uint32_t d = ctx->H[3];
110 	uint32_t e = ctx->H[4];
111 	uint32_t f = ctx->H[5];
112 	uint32_t g = ctx->H[6];
113 	uint32_t h = ctx->H[7];
114 
115 	/* First increment the byte count.  FIPS 180-2 specifies the possible
116 	 length of the file up to 2^64 bits.  Here we only compute the
117 	 number of bytes.  Do a double word increment.  */
118 	ctx->total[0] += (uint32_t)len;
119 	if (ctx->total[0] < len) {
120 		++ctx->total[1];
121 	}
122 
123 	/* Process all bytes in the buffer with 64 bytes in each round of
124 	 the loop.  */
125 	while (nwords > 0) {
126 		uint32_t W[64];
127 		uint32_t a_save = a;
128 		uint32_t b_save = b;
129 		uint32_t c_save = c;
130 		uint32_t d_save = d;
131 		uint32_t e_save = e;
132 		uint32_t f_save = f;
133 		uint32_t g_save = g;
134 		uint32_t h_save = h;
135 
136 	/* Operators defined in FIPS 180-2:4.1.2.  */
137 #define Ch(x, y, z) ((x & y) ^ (~x & z))
138 #define Maj(x, y, z) ((x & y) ^ (x & z) ^ (y & z))
139 #define S0(x) (CYCLIC (x, 2) ^ CYCLIC (x, 13) ^ CYCLIC (x, 22))
140 #define S1(x) (CYCLIC (x, 6) ^ CYCLIC (x, 11) ^ CYCLIC (x, 25))
141 #define R0(x) (CYCLIC (x, 7) ^ CYCLIC (x, 18) ^ (x >> 3))
142 #define R1(x) (CYCLIC (x, 17) ^ CYCLIC (x, 19) ^ (x >> 10))
143 
144 	/* It is unfortunate that C does not provide an operator for
145 	cyclic rotation.  Hope the C compiler is smart enough.  */
146 #define CYCLIC(w, s) ((w >> s) | (w << (32 - s)))
147 
148 		/* Compute the message schedule according to FIPS 180-2:6.2.2 step 2.  */
149 		for (t = 0; t < 16; ++t) {
150 			W[t] = SWAP (*words);
151 			++words;
152 		}
153 		for (t = 16; t < 64; ++t)
154 			W[t] = R1 (W[t - 2]) + W[t - 7] + R0 (W[t - 15]) + W[t - 16];
155 
156 		/* The actual computation according to FIPS 180-2:6.2.2 step 3.  */
157 		for (t = 0; t < 64; ++t) {
158 			uint32_t T1 = h + S1 (e) + Ch (e, f, g) + K[t] + W[t];
159 			uint32_t T2 = S0 (a) + Maj (a, b, c);
160 			h = g;
161 			g = f;
162 			f = e;
163 			e = d + T1;
164 			d = c;
165 			c = b;
166 			b = a;
167 			a = T1 + T2;
168 		}
169 
170 		/* Add the starting values of the context according to FIPS 180-2:6.2.2
171 		step 4.  */
172 		a += a_save;
173 		b += b_save;
174 		c += c_save;
175 		d += d_save;
176 		e += e_save;
177 		f += f_save;
178 		g += g_save;
179 		h += h_save;
180 
181 		/* Prepare for the next round.  */
182 		nwords -= 16;
183 	}
184 
185 	/* Put checksum in context given as argument.  */
186 	ctx->H[0] = a;
187 	ctx->H[1] = b;
188 	ctx->H[2] = c;
189 	ctx->H[3] = d;
190 	ctx->H[4] = e;
191 	ctx->H[5] = f;
192 	ctx->H[6] = g;
193 	ctx->H[7] = h;
194 }
195 
196 
197 /* Initialize structure containing state of computation.
198    (FIPS 180-2:5.3.2)  */
sha256_init_ctx(struct sha256_ctx * ctx)199 static void sha256_init_ctx(struct sha256_ctx *ctx) {
200 	ctx->H[0] = 0x6a09e667;
201 	ctx->H[1] = 0xbb67ae85;
202 	ctx->H[2] = 0x3c6ef372;
203 	ctx->H[3] = 0xa54ff53a;
204 	ctx->H[4] = 0x510e527f;
205 	ctx->H[5] = 0x9b05688c;
206 	ctx->H[6] = 0x1f83d9ab;
207 	ctx->H[7] = 0x5be0cd19;
208 
209 	ctx->total[0] = ctx->total[1] = 0;
210 	ctx->buflen = 0;
211 }
212 
213 
214 /* Process the remaining bytes in the internal buffer and the usual
215    prolog according to the standard and write the result to RESBUF.
216 
217    IMPORTANT: On some systems it is required that RESBUF is correctly
218    aligned for a 32 bits value.  */
sha256_finish_ctx(struct sha256_ctx * ctx,void * resbuf)219 static void * sha256_finish_ctx(struct sha256_ctx *ctx, void *resbuf) {
220 	/* Take yet unprocessed bytes into account.  */
221 	uint32_t bytes = ctx->buflen;
222 	size_t pad;
223 	unsigned int i;
224 
225 	/* Now count remaining bytes.  */
226 	ctx->total[0] += bytes;
227 	if (ctx->total[0] < bytes) {
228 		++ctx->total[1];
229 	}
230 
231 	pad = bytes >= 56 ? 64 + 56 - bytes : 56 - bytes;
232 	memcpy(&ctx->buffer[bytes], fillbuf, pad);
233 
234 	/* Put the 64-bit file length in *bits* at the end of the buffer.  */
235 	*(uint32_t *) &ctx->buffer[bytes + pad + 4] = SWAP (ctx->total[0] << 3);
236 	*(uint32_t *) &ctx->buffer[bytes + pad] = SWAP ((ctx->total[1] << 3) |
237 						  (ctx->total[0] >> 29));
238 
239 	/* Process last bytes.  */
240 	sha256_process_block(ctx->buffer, bytes + pad + 8, ctx);
241 
242 	/* Put result from CTX in first 32 bytes following RESBUF.  */
243 	for (i = 0; i < 8; ++i) {
244 		((uint32_t *) resbuf)[i] = SWAP(ctx->H[i]);
245 	}
246 
247 	return resbuf;
248 }
249 
250 
sha256_process_bytes(const void * buffer,size_t len,struct sha256_ctx * ctx)251 static void sha256_process_bytes(const void *buffer, size_t len, struct sha256_ctx *ctx) {
252 	/* When we already have some bits in our internal buffer concatenate
253 	 both inputs first.  */
254 	if (ctx->buflen != 0) {
255 		size_t left_over = ctx->buflen;
256 		size_t add = 128 - left_over > len ? len : 128 - left_over;
257 
258 		  memcpy(&ctx->buffer[left_over], buffer, add);
259 		  ctx->buflen += (uint32_t)add;
260 
261 		if (ctx->buflen > 64) {
262 			sha256_process_block(ctx->buffer, ctx->buflen & ~63, ctx);
263 			ctx->buflen &= 63;
264 			/* The regions in the following copy operation cannot overlap.  */
265 			memcpy(ctx->buffer, &ctx->buffer[(left_over + add) & ~63], ctx->buflen);
266 		}
267 
268 		buffer = (const char *) buffer + add;
269 		len -= add;
270 	}
271 
272 	/* Process available complete blocks.  */
273 	if (len >= 64) {
274 /* To check alignment gcc has an appropriate operator.  Other
275 compilers don't.  */
276 #if __GNUC__ >= 2
277 # define UNALIGNED_P(p) (((uintptr_t) p) % __alignof__ (uint32_t) != 0)
278 #else
279 # define UNALIGNED_P(p) (((uintptr_t) p) % sizeof (uint32_t) != 0)
280 #endif
281 		if (UNALIGNED_P (buffer))
282 			while (len > 64) {
283 				sha256_process_block(memcpy(ctx->buffer, buffer, 64), 64, ctx);
284 				buffer = (const char *) buffer + 64;
285 				len -= 64;
286 			} else {
287 				sha256_process_block(buffer, len & ~63, ctx);
288 				buffer = (const char *) buffer + (len & ~63);
289 				len &= 63;
290 			}
291 	}
292 
293 	/* Move remaining bytes into internal buffer.  */
294 	if (len > 0) {
295 		size_t left_over = ctx->buflen;
296 
297 		memcpy(&ctx->buffer[left_over], buffer, len);
298 		left_over += len;
299 		if (left_over >= 64) {
300 			sha256_process_block(ctx->buffer, 64, ctx);
301 			left_over -= 64;
302 			memcpy(ctx->buffer, &ctx->buffer[64], left_over);
303 		}
304 		ctx->buflen = (uint32_t)left_over;
305 	}
306 }
307 
308 
309 /* Define our magic string to mark salt for SHA256 "encryption"
310    replacement.  */
311 static const char sha256_salt_prefix[] = "$5$";
312 
313 /* Prefix for optional rounds specification.  */
314 static const char sha256_rounds_prefix[] = "rounds=";
315 
316 /* Maximum salt string length.  */
317 #define SALT_LEN_MAX 16
318 /* Default number of rounds if not explicitly specified.  */
319 #define ROUNDS_DEFAULT 5000
320 /* Minimum number of rounds.  */
321 #define ROUNDS_MIN 1000
322 /* Maximum number of rounds.  */
323 #define ROUNDS_MAX 999999999
324 
325 /* Table with characters for base64 transformation.  */
326 static const char b64t[64] =
327 "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
328 
php_sha256_crypt_r(const char * key,const char * salt,char * buffer,int buflen)329 char * php_sha256_crypt_r(const char *key, const char *salt, char *buffer, int buflen)
330 {
331 #ifdef PHP_WIN32
332 	ZEND_SET_ALIGNED(32, unsigned char alt_result[32]);
333 	ZEND_SET_ALIGNED(32, unsigned char temp_result[32]);
334 #else
335 	ZEND_SET_ALIGNED(__alignof__ (uint32_t), unsigned char alt_result[32]);
336 	ZEND_SET_ALIGNED(__alignof__ (uint32_t), unsigned char temp_result[32]);
337 #endif
338 
339 	struct sha256_ctx ctx;
340 	struct sha256_ctx alt_ctx;
341 	size_t salt_len;
342 	size_t key_len;
343 	size_t cnt;
344 	char *cp;
345 	char *copied_key = NULL;
346 	char *copied_salt = NULL;
347 	char *p_bytes;
348 	char *s_bytes;
349 	/* Default number of rounds.  */
350 	size_t rounds = ROUNDS_DEFAULT;
351 	zend_bool rounds_custom = 0;
352 
353 	/* Find beginning of salt string.  The prefix should normally always
354 	be present.  Just in case it is not.  */
355 	if (strncmp(sha256_salt_prefix, salt, sizeof(sha256_salt_prefix) - 1) == 0) {
356 		/* Skip salt prefix.  */
357 		salt += sizeof(sha256_salt_prefix) - 1;
358 	}
359 
360 	if (strncmp(salt, sha256_rounds_prefix, sizeof(sha256_rounds_prefix) - 1) == 0) {
361 		const char *num = salt + sizeof(sha256_rounds_prefix) - 1;
362 		char *endp;
363 		zend_ulong srounds = ZEND_STRTOUL(num, &endp, 10);
364 		if (*endp == '$') {
365 			salt = endp + 1;
366 			rounds = MAX(ROUNDS_MIN, MIN(srounds, ROUNDS_MAX));
367 			rounds_custom = 1;
368 		}
369 	}
370 
371 	salt_len = MIN(strcspn(salt, "$"), SALT_LEN_MAX);
372 	key_len = strlen(key);
373 
374 	if ((key - (char *) 0) % __alignof__ (uint32_t) != 0) {
375 		char *tmp = (char *) alloca(key_len + __alignof__(uint32_t));
376 		key = copied_key = memcpy(tmp + __alignof__(uint32_t) - (tmp - (char *) 0) % __alignof__(uint32_t), key, key_len);
377 	}
378 
379 	if ((salt - (char *) 0) % __alignof__(uint32_t) != 0) {
380 		char *tmp = (char *) alloca(salt_len + 1 + __alignof__(uint32_t));
381 		salt = copied_salt =
382 		memcpy(tmp + __alignof__(uint32_t) - (tmp - (char *) 0) % __alignof__ (uint32_t), salt, salt_len);
383 		copied_salt[salt_len] = 0;
384 	}
385 
386 	/* Prepare for the real work.  */
387 	sha256_init_ctx(&ctx);
388 
389 	/* Add the key string.  */
390 	sha256_process_bytes(key, key_len, &ctx);
391 
392 	/* The last part is the salt string.  This must be at most 16
393 	 characters and it ends at the first `$' character (for
394 	 compatibility with existing implementations).  */
395 	sha256_process_bytes(salt, salt_len, &ctx);
396 
397 
398 	/* Compute alternate SHA256 sum with input KEY, SALT, and KEY.  The
399 	 final result will be added to the first context.  */
400 	sha256_init_ctx(&alt_ctx);
401 
402 	/* Add key.  */
403 	sha256_process_bytes(key, key_len, &alt_ctx);
404 
405 	/* Add salt.  */
406 	sha256_process_bytes(salt, salt_len, &alt_ctx);
407 
408 	/* Add key again.  */
409 	sha256_process_bytes(key, key_len, &alt_ctx);
410 
411 	/* Now get result of this (32 bytes) and add it to the other
412 	 context.  */
413 	sha256_finish_ctx(&alt_ctx, alt_result);
414 
415 	/* Add for any character in the key one byte of the alternate sum.  */
416 	for (cnt = key_len; cnt > 32; cnt -= 32) {
417 		sha256_process_bytes(alt_result, 32, &ctx);
418 	}
419 	sha256_process_bytes(alt_result, cnt, &ctx);
420 
421 	/* Take the binary representation of the length of the key and for every
422 	1 add the alternate sum, for every 0 the key.  */
423 	for (cnt = key_len; cnt > 0; cnt >>= 1) {
424 		if ((cnt & 1) != 0) {
425 			sha256_process_bytes(alt_result, 32, &ctx);
426 		} else {
427 			sha256_process_bytes(key, key_len, &ctx);
428 		}
429 	}
430 
431 	/* Create intermediate result.  */
432 	sha256_finish_ctx(&ctx, alt_result);
433 
434 	/* Start computation of P byte sequence.  */
435 	sha256_init_ctx(&alt_ctx);
436 
437 	/* For every character in the password add the entire password.  */
438 	for (cnt = 0; cnt < key_len; ++cnt) {
439 		sha256_process_bytes(key, key_len, &alt_ctx);
440 	}
441 
442 	/* Finish the digest.  */
443 	sha256_finish_ctx(&alt_ctx, temp_result);
444 
445 	/* Create byte sequence P.  */
446 	cp = p_bytes = alloca(key_len);
447 	for (cnt = key_len; cnt >= 32; cnt -= 32) {
448 		cp = __php_mempcpy((void *)cp, (const void *)temp_result, 32);
449 	}
450 	memcpy(cp, temp_result, cnt);
451 
452 	/* Start computation of S byte sequence.  */
453 	sha256_init_ctx(&alt_ctx);
454 
455 	/* For every character in the password add the entire password.  */
456 	for (cnt = 0; cnt < (size_t) (16 + alt_result[0]); ++cnt) {
457 		sha256_process_bytes(salt, salt_len, &alt_ctx);
458 	}
459 
460 	/* Finish the digest.  */
461 	sha256_finish_ctx(&alt_ctx, temp_result);
462 
463 	/* Create byte sequence S.  */
464 	cp = s_bytes = alloca(salt_len);
465 	for (cnt = salt_len; cnt >= 32; cnt -= 32) {
466 		cp = __php_mempcpy(cp, temp_result, 32);
467 	}
468 	memcpy(cp, temp_result, cnt);
469 
470 	/* Repeatedly run the collected hash value through SHA256 to burn
471 	CPU cycles.  */
472 	for (cnt = 0; cnt < rounds; ++cnt) {
473 		/* New context.  */
474 		sha256_init_ctx(&ctx);
475 
476 		/* Add key or last result.  */
477 		if ((cnt & 1) != 0) {
478 			sha256_process_bytes(p_bytes, key_len, &ctx);
479 		} else {
480 			sha256_process_bytes(alt_result, 32, &ctx);
481 		}
482 
483 		/* Add salt for numbers not divisible by 3.  */
484 		if (cnt % 3 != 0) {
485 			sha256_process_bytes(s_bytes, salt_len, &ctx);
486 		}
487 
488 		/* Add key for numbers not divisible by 7.  */
489 		if (cnt % 7 != 0) {
490 			sha256_process_bytes(p_bytes, key_len, &ctx);
491 		}
492 
493 		/* Add key or last result.  */
494 		if ((cnt & 1) != 0) {
495 			sha256_process_bytes(alt_result, 32, &ctx);
496 		} else {
497 			sha256_process_bytes(p_bytes, key_len, &ctx);
498 		}
499 
500 		/* Create intermediate result.  */
501 		sha256_finish_ctx(&ctx, alt_result);
502 	}
503 
504 	/* Now we can construct the result string.  It consists of three
505 	parts.  */
506 	cp = __php_stpncpy(buffer, sha256_salt_prefix, MAX(0, buflen));
507 	buflen -= sizeof(sha256_salt_prefix) - 1;
508 
509 	if (rounds_custom) {
510 #ifdef PHP_WIN32
511 		int n = _snprintf(cp, MAX(0, buflen), "%s" ZEND_ULONG_FMT "$", sha256_rounds_prefix, rounds);
512 #else
513 		int n = snprintf(cp, MAX(0, buflen), "%s%zu$", sha256_rounds_prefix, rounds);
514 #endif
515 		cp += n;
516 		buflen -= n;
517 	}
518 
519 	cp = __php_stpncpy(cp, salt, MIN ((size_t) MAX (0, buflen), salt_len));
520 	buflen -= MIN(MAX (0, buflen), (int)salt_len);
521 
522 	if (buflen > 0) {
523 		*cp++ = '$';
524 		--buflen;
525 	}
526 
527 #define b64_from_24bit(B2, B1, B0, N)					      \
528   do {									      \
529     unsigned int w = ((B2) << 16) | ((B1) << 8) | (B0);			      \
530     int n = (N);							      \
531     while (n-- > 0 && buflen > 0)					      \
532       {									      \
533 	*cp++ = b64t[w & 0x3f];						      \
534 	--buflen;							      \
535 	w >>= 6;							      \
536       }									      \
537   } while (0)
538 
539 	b64_from_24bit(alt_result[0], alt_result[10], alt_result[20], 4);
540 	b64_from_24bit(alt_result[21], alt_result[1], alt_result[11], 4);
541 	b64_from_24bit(alt_result[12], alt_result[22], alt_result[2], 4);
542 	b64_from_24bit(alt_result[3], alt_result[13], alt_result[23], 4);
543 	b64_from_24bit(alt_result[24], alt_result[4], alt_result[14], 4);
544 	b64_from_24bit(alt_result[15], alt_result[25], alt_result[5], 4);
545 	b64_from_24bit(alt_result[6], alt_result[16], alt_result[26], 4);
546 	b64_from_24bit(alt_result[27], alt_result[7], alt_result[17], 4);
547 	b64_from_24bit(alt_result[18], alt_result[28], alt_result[8], 4);
548 	b64_from_24bit(alt_result[9], alt_result[19], alt_result[29], 4);
549 	b64_from_24bit(0, alt_result[31], alt_result[30], 3);
550 	if (buflen <= 0) {
551 		errno = ERANGE;
552 		buffer = NULL;
553 	} else
554 		*cp = '\0';		/* Terminate the string.  */
555 
556 	/* Clear the buffer for the intermediate result so that people
557      attaching to processes or reading core dumps cannot get any
558      information.  We do it in this way to clear correct_words[]
559      inside the SHA256 implementation as well.  */
560 	sha256_init_ctx(&ctx);
561 	sha256_finish_ctx(&ctx, alt_result);
562 	ZEND_SECURE_ZERO(temp_result, sizeof(temp_result));
563 	ZEND_SECURE_ZERO(p_bytes, key_len);
564 	ZEND_SECURE_ZERO(s_bytes, salt_len);
565 	ZEND_SECURE_ZERO(&ctx, sizeof(ctx));
566 	ZEND_SECURE_ZERO(&alt_ctx, sizeof(alt_ctx));
567 
568 	if (copied_key != NULL) {
569 		ZEND_SECURE_ZERO(copied_key, key_len);
570 	}
571 	if (copied_salt != NULL) {
572 		ZEND_SECURE_ZERO(copied_salt, salt_len);
573 	}
574 
575 	return buffer;
576 }
577 
578 
579 /* This entry point is equivalent to the `crypt' function in Unix
580    libcs.  */
php_sha256_crypt(const char * key,const char * salt)581 char * php_sha256_crypt(const char *key, const char *salt)
582 {
583 	/* We don't want to have an arbitrary limit in the size of the
584 	password.  We can compute an upper bound for the size of the
585 	result in advance and so we can prepare the buffer we pass to
586 	`sha256_crypt_r'.  */
587 	ZEND_TLS char *buffer;
588 	ZEND_TLS int buflen = 0;
589 	int needed = (sizeof(sha256_salt_prefix) - 1
590 			+ sizeof(sha256_rounds_prefix) + 9 + 1
591 			+ (int)strlen(salt) + 1 + 43 + 1);
592 
593 	if (buflen < needed) {
594 		char *new_buffer = (char *) realloc(buffer, needed);
595 		if (new_buffer == NULL) {
596 			return NULL;
597 		}
598 
599 		buffer = new_buffer;
600 		buflen = needed;
601 	}
602 
603 	return php_sha256_crypt_r(key, salt, buffer, buflen);
604 }
605 
606 
607 #ifdef TEST
608 static const struct
609 {
610 	const char *input;
611 	const char result[32];
612 } tests[] =
613 	{
614 	/* Test vectors from FIPS 180-2: appendix B.1.  */
615 	{ "abc",
616 	"\xba\x78\x16\xbf\x8f\x01\xcf\xea\x41\x41\x40\xde\x5d\xae\x22\x23"
617 	"\xb0\x03\x61\xa3\x96\x17\x7a\x9c\xb4\x10\xff\x61\xf2\x00\x15\xad" },
618 	/* Test vectors from FIPS 180-2: appendix B.2.  */
619 	{ "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
620 	"\x24\x8d\x6a\x61\xd2\x06\x38\xb8\xe5\xc0\x26\x93\x0c\x3e\x60\x39"
621 	"\xa3\x3c\xe4\x59\x64\xff\x21\x67\xf6\xec\xed\xd4\x19\xdb\x06\xc1" },
622 	/* Test vectors from the NESSIE project.  */
623 	{ "",
624 	"\xe3\xb0\xc4\x42\x98\xfc\x1c\x14\x9a\xfb\xf4\xc8\x99\x6f\xb9\x24"
625 	"\x27\xae\x41\xe4\x64\x9b\x93\x4c\xa4\x95\x99\x1b\x78\x52\xb8\x55" },
626 	{ "a",
627 	"\xca\x97\x81\x12\xca\x1b\xbd\xca\xfa\xc2\x31\xb3\x9a\x23\xdc\x4d"
628 	"\xa7\x86\xef\xf8\x14\x7c\x4e\x72\xb9\x80\x77\x85\xaf\xee\x48\xbb" },
629 	{ "message digest",
630 	"\xf7\x84\x6f\x55\xcf\x23\xe1\x4e\xeb\xea\xb5\xb4\xe1\x55\x0c\xad"
631 	"\x5b\x50\x9e\x33\x48\xfb\xc4\xef\xa3\xa1\x41\x3d\x39\x3c\xb6\x50" },
632 	{ "abcdefghijklmnopqrstuvwxyz",
633 	"\x71\xc4\x80\xdf\x93\xd6\xae\x2f\x1e\xfa\xd1\x44\x7c\x66\xc9\x52"
634 	"\x5e\x31\x62\x18\xcf\x51\xfc\x8d\x9e\xd8\x32\xf2\xda\xf1\x8b\x73" },
635 	{ "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
636 	"\x24\x8d\x6a\x61\xd2\x06\x38\xb8\xe5\xc0\x26\x93\x0c\x3e\x60\x39"
637 	"\xa3\x3c\xe4\x59\x64\xff\x21\x67\xf6\xec\xed\xd4\x19\xdb\x06\xc1" },
638 	{ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
639 	"\xdb\x4b\xfc\xbd\x4d\xa0\xcd\x85\xa6\x0c\x3c\x37\xd3\xfb\xd8\x80"
640 	"\x5c\x77\xf1\x5f\xc6\xb1\xfd\xfe\x61\x4e\xe0\xa7\xc8\xfd\xb4\xc0" },
641 	{ "123456789012345678901234567890123456789012345678901234567890"
642 	"12345678901234567890",
643 	"\xf3\x71\xbc\x4a\x31\x1f\x2b\x00\x9e\xef\x95\x2d\xd8\x3c\xa8\x0e"
644 	"\x2b\x60\x02\x6c\x8e\x93\x55\x92\xd0\xf9\xc3\x08\x45\x3c\x81\x3e" }
645   };
646 #define ntests (sizeof (tests) / sizeof (tests[0]))
647 
648 
649 static const struct
650 {
651 	const char *salt;
652 	const char *input;
653 	const char *expected;
654 } tests2[] =
655 {
656 	{ "$5$saltstring", "Hello world!",
657 	"$5$saltstring$5B8vYYiY.CVt1RlTTf8KbXBH3hsxY/GNooZaBBGWEc5" },
658 	{ "$5$rounds=10000$saltstringsaltstring", "Hello world!",
659 	"$5$rounds=10000$saltstringsaltst$3xv.VbSHBb41AL9AvLeujZkZRBAwqFMz2."
660 	"opqey6IcA" },
661 	{ "$5$rounds=5000$toolongsaltstring", "This is just a test",
662 	"$5$rounds=5000$toolongsaltstrin$Un/5jzAHMgOGZ5.mWJpuVolil07guHPvOW8"
663 	"mGRcvxa5" },
664 	{ "$5$rounds=1400$anotherlongsaltstring",
665 	"a very much longer text to encrypt.  This one even stretches over more"
666 	"than one line.",
667 	"$5$rounds=1400$anotherlongsalts$Rx.j8H.h8HjEDGomFU8bDkXm3XIUnzyxf12"
668 	"oP84Bnq1" },
669 	{ "$5$rounds=77777$short",
670 	"we have a short salt string but not a short password",
671 	"$5$rounds=77777$short$JiO1O3ZpDAxGJeaDIuqCoEFysAe1mZNJRs3pw0KQRd/" },
672 	{ "$5$rounds=123456$asaltof16chars..", "a short string",
673 	"$5$rounds=123456$asaltof16chars..$gP3VQ/6X7UUEW3HkBn2w1/Ptq2jxPyzV/"
674 	"cZKmF/wJvD" },
675 	{ "$5$rounds=10$roundstoolow", "the minimum number is still observed",
676 	"$5$rounds=1000$roundstoolow$yfvwcWrQ8l/K0DAWyuPMDNHpIVlTQebY9l/gL97"
677 	"2bIC" },
678 };
679 #define ntests2 (sizeof (tests2) / sizeof (tests2[0]))
680 
681 
main(void)682 int main(void) {
683 	struct sha256_ctx ctx;
684 	char sum[32];
685 	int result = 0;
686 	int cnt, i;
687 	char buf[1000];
688 	static const char expected[32] =
689 	"\xcd\xc7\x6e\x5c\x99\x14\xfb\x92\x81\xa1\xc7\xe2\x84\xd7\x3e\x67"
690 	"\xf1\x80\x9a\x48\xa4\x97\x20\x0e\x04\x6d\x39\xcc\xc7\x11\x2c\xd0";
691 
692 	for (cnt = 0; cnt < (int) ntests; ++cnt) {
693 		sha256_init_ctx(&ctx);
694 		sha256_process_bytes(tests[cnt].input, strlen(tests[cnt].input), &ctx);
695 		sha256_finish_ctx(&ctx, sum);
696 		if (memcmp(tests[cnt].result, sum, 32) != 0) {
697 			printf("test %d run %d failed\n", cnt, 1);
698 			result = 1;
699 		}
700 
701 		sha256_init_ctx(&ctx);
702 		for (i = 0; tests[cnt].input[i] != '\0'; ++i) {
703 			sha256_process_bytes(&tests[cnt].input[i], 1, &ctx);
704 		}
705 		sha256_finish_ctx(&ctx, sum);
706 		if (memcmp(tests[cnt].result, sum, 32) != 0) {
707 			printf("test %d run %d failed\n", cnt, 2);
708 			result = 1;
709 		}
710 	}
711 
712 	/* Test vector from FIPS 180-2: appendix B.3.  */
713 
714 	memset(buf, 'a', sizeof(buf));
715 	sha256_init_ctx(&ctx);
716 	for (i = 0; i < 1000; ++i) {
717 		sha256_process_bytes (buf, sizeof (buf), &ctx);
718 	}
719 
720 	sha256_finish_ctx(&ctx, sum);
721 
722 	if (memcmp(expected, sum, 32) != 0) {
723 		printf("test %d failed\n", cnt);
724 		result = 1;
725 	}
726 
727 	for (cnt = 0; cnt < ntests2; ++cnt) {
728 		char *cp = php_sha256_crypt(tests2[cnt].input, tests2[cnt].salt);
729 		if (strcmp(cp, tests2[cnt].expected) != 0) {
730 			printf("test %d: expected \"%s\", got \"%s\"\n", cnt, tests2[cnt].expected, cp);
731 			result = 1;
732 		}
733 	}
734 
735 	if (result == 0)
736 	puts("all tests OK");
737 
738 	return result;
739 }
740 #endif
741