70{
71 static const char rounds_prefix[] = "rounds=";
72 static const char *magic_bytes[2] = {"5ドル$", "6ドル$"};
73
74 /* Used to create the password hash string */
76
78 PX_MD *digestA = NULL;
79 PX_MD *digestB = NULL;
81
82 const char *dec_salt_binary; /* pointer into the real salt string */
83 StringInfo decoded_salt = NULL;
/* decoded salt string */
85
86 /* temporary buffer for digests */
88 char rounds_custom = 0;
89 char *p_bytes = NULL;
90 char *s_bytes = NULL;
91 char *cp = NULL;
92 const char *fp = NULL; /* intermediate pointer within salt string */
93 const char *ep = NULL; /* holds pointer to the end of the salt string */
94 size_t buf_size = 0; /* buffer size for sha256crypt/sha512crypt */
95 unsigned int block; /* number of bytes processed */
98 salt_len = 0;
99
100 /* Sanity checks */
101 if (!passwd)
102 return NULL;
103
104 if (pw == NULL)
105 elog(
ERROR,
"null value for password rejected");
106
107 if (salt == NULL)
108 elog(
ERROR,
"null value for salt rejected");
109
110 /*
111 * Make sure result buffers are large enough.
112 */
114 elog(
ERROR,
"insufficient result buffer size to encrypt password");
115
116 /* Init result buffer */
119
120 /* Init contents of buffers properly */
121 memset(&sha_buf, '0円', sizeof(sha_buf));
122 memset(&sha_buf_tmp, '0円', sizeof(sha_buf_tmp));
123
124 /*
125 * Decode the salt string. We need to know how many rounds and which
126 * digest we have to use to hash the password.
127 */
129 dec_salt_binary = salt;
130
131 /*
132 * Analyze and prepare the salt string
133 *
134 * The magic string should be specified in the first three bytes of the
135 * salt string. Do some sanity checks first.
136 */
137 if (strlen(dec_salt_binary) < 3)
139 errcode(ERRCODE_INVALID_PARAMETER_VALUE),
141
142 /*
143 * Check format of magic bytes. These should define either 5=sha256crypt
144 * or 6=sha512crypt in the second byte, enclosed by ascii dollar signs.
145 */
146 if ((dec_salt_binary[0] != '$') || (dec_salt_binary[2] != '$'))
148 errcode(ERRCODE_INVALID_PARAMETER_VALUE),
149 errmsg(
"invalid format of salt"),
150 errhint(
"magic byte format for shacrypt is either \"5ドル$\" or \"6ドル$\""));
151
152 /*
153 * Check magic byte for supported shacrypt digest.
154 *
155 * We're just interested in the very first 3 bytes of the salt string,
156 * since this defines the digest length to use.
157 */
158 if (strncmp(dec_salt_binary, magic_bytes[0], strlen(magic_bytes[0])) == 0)
159 {
161 dec_salt_binary += strlen(magic_bytes[0]);
162 }
163 else if (strncmp(dec_salt_binary, magic_bytes[1], strlen(magic_bytes[1])) == 0)
164 {
166 dec_salt_binary += strlen(magic_bytes[1]);
167 }
168
169 /*
170 * dec_salt_binary pointer is positioned after the magic bytes now
171 *
172 * We extract any options in the following code branch. The only optional
173 * setting we need to take care of is the "rounds" option. Note that the
174 * salt generator already checked for invalid settings before, but we need
175 * to do it here again to protect against injection of wrong values when
176 * called without the generator.
177 *
178 * If there is any garbage added after the magic byte and the options/salt
179 * string, we don't treat this special: This is just absorbed as part of
180 * the salt with up to PX_SHACRYPT_SALT_LEN_MAX.
181 *
182 * Unknown magic byte is handled further below.
183 */
184 if (strncmp(dec_salt_binary,
185 rounds_prefix, sizeof(rounds_prefix) - 1) == 0)
186 {
187 const char *num = dec_salt_binary + sizeof(rounds_prefix) - 1;
188 char *endp;
189 int srounds =
strtoint(num, &endp, 10);
190
191 if (*endp != '$')
194 errmsg(
"could not parse salt options"));
195
196 dec_salt_binary = endp + 1;
197
198 /*
199 * We violate supported lower or upper bound of rounds, but in this
200 * case we change this value to the supported lower or upper value. We
201 * don't do this silently and print a NOTICE in such a case.
202 *
203 * Note that a salt string generated with gen_salt() would never
204 * generated such a salt string, since it would error out.
205 *
206 * But Drepper's upstream reference implementation supports this when
207 * passing the salt string directly, so we maintain compatibility.
208 */
210 {
212 errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
213 errmsg(
"rounds=%d exceeds maximum supported value (%d), using %d instead",
217 }
219 {
221 errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
222 errmsg(
"rounds=%d is below supported value (%d), using %d instead",
226 }
227
228 rounds = (
uint32) srounds;
229 rounds_custom = 1;
230 }
231
232 /*
233 * Choose the correct digest length and add the magic bytes to the result
234 * buffer. Also handle possible invalid magic byte we've extracted above.
235 */
237 {
239 {
240 /* Two PX_MD objects required */
244
248
249 /* digest buffer length is 32 for sha256 */
250 buf_size = 32;
251
253 break;
254 }
255
257 {
258 /* Two PX_MD objects required */
262
266
268
270 break;
271 }
272
274 elog(
ERROR,
"unknown crypt identifier \"%c\"", salt[1]);
275 }
276
277 if (rounds_custom > 0)
279
280 /*
281 * We need the real decoded salt string from salt input, this is every
282 * character before the last '$' in the preamble. Append every compatible
283 * character up to PX_SHACRYPT_SALT_MAX_LEN to the result buffer. Note
284 * that depending on the input, there might be no '$' marker after the
285 * salt, when there is no password hash attached at the end.
286 *
287 * We try hard to recognize mistakes, but since we might get an input
288 * string which might also have the password hash after the salt string
289 * section we give up as soon we reach the end of the input or if there
290 * are any bytes consumed for the salt string until we reach the first '$'
291 * marker thereafter.
292 */
293 for (ep = dec_salt_binary;
295 ep++)
296 {
297 /*
298 * Filter out any string which shouldn't be here.
299 *
300 * First check for accidentally embedded magic strings here. We don't
301 * support '$' in salt strings anyways and seeing a magic byte trying
302 * to identify shacrypt hashes might indicate that something went
303 * wrong when generating this salt string. Note that we later check
304 * for non-supported literals anyways, but any '$' here confuses us at
305 * this point.
306 */
307 fp = strstr(dec_salt_binary, magic_bytes[0]);
308 if (fp != NULL)
309 elog(
ERROR,
"bogus magic byte found in salt string");
310
311 fp = strstr(dec_salt_binary, magic_bytes[1]);
312 if (fp != NULL)
313 elog(
ERROR,
"bogus magic byte found in salt string");
314
315 /*
316 * This looks very strict, but we assume the caller did something
317 * wrong when we see a "rounds=" option here.
318 */
319 fp = strstr(dec_salt_binary, rounds_prefix);
320 if (fp != NULL)
321 elog(
ERROR,
"invalid rounds option specified in salt string");
322
323 if (*ep != '$')
324 {
327 else
329 errcode(ERRCODE_INVALID_PARAMETER_VALUE),
330 errmsg(
"invalid character in salt string: \"%.*s\"",
332 }
333 else
334 {
335 /*
336 * We encountered a '$' marker. Check if we already absorbed some
337 * bytes from input. If true, we are optimistic and terminate at
338 * this stage. If not, we try further.
339 *
340 * If we already consumed enough bytes for the salt string,
341 * everything that is after this marker is considered to be part
342 * of an optionally specified password hash and ignored.
343 */
344 if (decoded_salt->
len > 0)
345 break;
346 }
347 }
348
349 salt_len = decoded_salt->
len;
351 elog(
DEBUG1,
"using salt \"%s\", salt len = %d, rounds = %u",
352 decoded_salt->
data, decoded_salt->
len, rounds);
353
354 /*
355 * Sanity check: at this point the salt string buffer must not exceed
356 * expected size.
357 */
358 if (out_buf->
len > (3 + 17 * rounds_custom + salt_len))
359 elog(
ERROR,
"unexpected length of salt string");
360
361 /*-
362 * 1. Start digest A
363 * 2. Add the password string to digest A
364 * 3. Add the salt to digest A
365 */
367 px_md_update(digestA, (
const unsigned char *) decoded_salt->
data, salt_len);
368
369 /*-
370 * 4. Create digest B
371 * 5. Add password to digest B
372 * 6. Add the salt string to digest B
373 * 7. Add the password again to digest B
374 * 8. Finalize digest B
375 */
377 px_md_update(digestB, (
const unsigned char *) dec_salt_binary, salt_len);
380
381 /*
382 * 9. For each block (excluding the NULL byte), add digest B to digest A.
383 */
384 for (block =
len; block > buf_size; block -= buf_size)
386
387 /*-
388 * 10. For the remaining N bytes of the password string, add the first N
389 * bytes of digest B to A.
390 */
392
393 /*-
394 * 11. For each bit of the binary representation of the length of the
395 * password string up to and including the highest 1-digit, starting from
396 * to lowest bit position (numeric value 1)
397 *
398 * a) for a 1-digit add digest B (sha_buf) to digest A
399 * b) for a 0-digit add the password string
400 */
402 while (block)
403 {
405 (block & 1) ? sha_buf : (const unsigned char *) pw,
406 (block & 1) ? buf_size :
len);
407
408 /* right shift to next byte */
409 block >>= 1;
410 }
411
412 /* 12. Finalize digest A */
414
415 /* 13. Start digest DP */
417
418 /*-
419 * 14 Add every byte of the password string (excluding trailing NULL)
420 * to the digest DP
421 */
422 for (block =
len; block > 0; block--)
424
425 /* 15. Finalize digest DP */
427
428 /*-
429 * 16. produce byte sequence P with same length as password.
430 * a) for each block of 32 or 64 bytes of length of the password
431 * string the entire digest DP is used
432 * b) for the remaining N (up to 31 or 63) bytes use the
433 * first N bytes of digest DP
434 */
436 {
438 }
439
440 /* N step of 16, copy over the bytes from password */
441 for (cp = p_bytes, block =
len; block > buf_size; block -= buf_size, cp += buf_size)
442 memcpy(cp, sha_buf_tmp, buf_size);
443 memcpy(cp, sha_buf_tmp, block);
444
445 /*
446 * 17. Start digest DS
447 */
449
450 /*-
451 * 18. Repeat the following 16+A[0] times, where A[0] represents the first
452 * byte in digest A interpreted as an 8-bit unsigned value
453 * add the salt to digest DS
454 */
455 for (block = 16 + sha_buf[0]; block > 0; block--)
456 px_md_update(digestB, (
const unsigned char *) dec_salt_binary, salt_len);
457
458 /*
459 * 19. Finalize digest DS
460 */
462
463 /*-
464 * 20. Produce byte sequence S of the same length as the salt string where
465 *
466 * a) for each block of 32 or 64 bytes of length of the salt string the
467 * entire digest DS is used
468 *
469 * b) for the remaining N (up to 31 or 63) bytes use the first N
470 * bytes of digest DS
471 */
472 if ((s_bytes =
palloc0(salt_len)) == NULL)
474
475 for (cp = s_bytes, block = salt_len; block > buf_size; block -= buf_size, cp += buf_size)
476 memcpy(cp, sha_buf_tmp, buf_size);
477 memcpy(cp, sha_buf_tmp, block);
478
479 /* Make sure we don't leave something important behind */
480 px_memset(&sha_buf_tmp, 0,
sizeof sha_buf);
481
482 /*-
483 * 21. Repeat a loop according to the number specified in the rounds=<N>
484 * specification in the salt (or the default value if none is
485 * present). Each round is numbered, starting with 0 and up to N-1.
486 *
487 * The loop uses a digest as input. In the first round it is the
488 * digest produced in step 12. In the latter steps it is the digest
489 * produced in step 21.h of the previous round. The following text
490 * uses the notation "digest A/B" to describe this behavior.
491 */
492 for (block = 0; block < rounds; block++)
493 {
494 /*
495 * Make it possible to abort in case large values for "rounds" are
496 * specified.
497 */
499
500 /* a) start digest B */
502
503 /*-
504 * b) for odd round numbers add the byte sequence P to digest B
505 * c) for even round numbers add digest A/B
506 */
508 (block & 1) ? (const unsigned char *) p_bytes : sha_buf,
509 (block & 1) ?
len : buf_size);
510
511 /* d) for all round numbers not divisible by 3 add the byte sequence S */
512 if ((block % 3) != 0)
513 px_md_update(digestB, (
const unsigned char *) s_bytes, salt_len);
514
515 /* e) for all round numbers not divisible by 7 add the byte sequence P */
516 if ((block % 7) != 0)
518
519 /*-
520 * f) for odd round numbers add digest A/C
521 * g) for even round numbers add the byte sequence P
522 */
524 (block & 1) ? sha_buf : (const unsigned char *) p_bytes,
525 (block & 1) ? buf_size :
len);
526
527 /* h) finish digest C. */
529 }
530
533
534 digestA = NULL;
535 digestB = NULL;
536
539
540 s_bytes = NULL;
541 p_bytes = NULL;
542
543 /* prepare final result buffer */
545
546#define b64_from_24bit(B2, B1, B0, N) \
547 do { \
548 unsigned int w = ((B2) << 16) | ((B1) << 8) | (B0); \
549 int i = (N); \
550 while (i-- > 0) \
551 { \
552 appendStringInfoCharMacro(out_buf, _crypt_itoa64[w & 0x3f]); \
553 w >>= 6; \
554 } \
555 } while (0)
556
558 {
560 {
572
573 break;
574 }
575
577 {
600
601 break;
602 }
603
605 /* we shouldn't land here ... */
606 elog(
ERROR,
"unsupported digest length");
607 }
608
609 /*
610 * Copy over result to specified buffer.
611 *
612 * The passwd character buffer should have at least PX_SHACRYPT_BUF_LEN
613 * allocated, since we checked above if dstlen is smaller than
614 * PX_SHACRYPT_BUF_LEN (which also includes the NULL byte).
615 *
616 * In that case we would have failed above already.
617 */
618 memcpy(passwd, out_buf->
data, out_buf->
len);
619
620 /* make sure nothing important is left behind */
624
625 /* ...and we're done */
626 return passwd;
627
629 if (digestA != NULL)
631
632 if (digestB != NULL)
634
637
639 errcode(ERRCODE_INTERNAL_ERROR),
640 errmsg(
"cannot create encrypted password"));
641 return NULL; /* keep compiler quiet */
642}
#define b64_from_24bit(B2, B1, B0, N)
int errhint(const char *fmt,...)
int errcode(int sqlerrcode)
int errmsg(const char *fmt,...)
#define ereport(elevel,...)
void err(int eval, const char *fmt,...)
int pg_mblen(const char *mbstr)
void pfree(void *pointer)
void * palloc0(Size size)
#define CHECK_FOR_INTERRUPTS()
int px_find_digest(const char *name, PX_MD **res)
#define PX_SHACRYPT_ROUNDS_MAX
#define PX_SHACRYPT_BUF_LEN
#define PX_SHACRYPT_ROUNDS_MIN
#define PX_SHACRYPT_DIGEST_MAX_LEN
#define PX_SHACRYPT_SALT_MAX_LEN
#define PX_SHACRYPT_ROUNDS_DEFAULT
void px_memset(void *ptr, int c, size_t len)
#define px_md_finish(md, buf)
#define px_md_update(md, data, dlen)
int strtoint(const char *pg_restrict str, char **pg_restrict endptr, int base)
void destroyStringInfo(StringInfo str)
void appendStringInfo(StringInfo str, const char *fmt,...)
StringInfo makeStringInfoExt(int initsize)
void appendStringInfoString(StringInfo str, const char *s)
#define appendStringInfoCharMacro(str, ch)