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