Load rand state after loading providers
[openssl.git] / apps / passwd.c
1 /*
2  * Copyright 2000-2021 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9
10 #include <string.h>
11
12 #include "apps.h"
13 #include "progs.h"
14
15 #include <openssl/bio.h>
16 #include <openssl/err.h>
17 #include <openssl/evp.h>
18 #include <openssl/rand.h>
19 #if !defined(OPENSSL_NO_DES) && !defined(OPENSSL_NO_DEPRECATED_3_0)
20 # include <openssl/des.h>
21 #endif
22 #include <openssl/md5.h>
23 #include <openssl/sha.h>
24
25 static const unsigned char cov_2char[64] = {
26     /* from crypto/des/fcrypt.c */
27     0x2E, 0x2F, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35,
28     0x36, 0x37, 0x38, 0x39, 0x41, 0x42, 0x43, 0x44,
29     0x45, 0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B, 0x4C,
30     0x4D, 0x4E, 0x4F, 0x50, 0x51, 0x52, 0x53, 0x54,
31     0x55, 0x56, 0x57, 0x58, 0x59, 0x5A, 0x61, 0x62,
32     0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A,
33     0x6B, 0x6C, 0x6D, 0x6E, 0x6F, 0x70, 0x71, 0x72,
34     0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A
35 };
36
37 static const char ascii_dollar[] = { 0x24, 0x00 };
38
39 typedef enum {
40     passwd_unset = 0,
41     passwd_md5,
42     passwd_apr1,
43     passwd_sha256,
44     passwd_sha512,
45     passwd_aixmd5
46 } passwd_modes;
47
48 static int do_passwd(int passed_salt, char **salt_p, char **salt_malloc_p,
49                      char *passwd, BIO *out, int quiet, int table,
50                      int reverse, size_t pw_maxlen, passwd_modes mode);
51
52 typedef enum OPTION_choice {
53     OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
54     OPT_IN,
55     OPT_NOVERIFY, OPT_QUIET, OPT_TABLE, OPT_REVERSE, OPT_APR1,
56     OPT_1, OPT_5, OPT_6, OPT_AIXMD5, OPT_SALT, OPT_STDIN,
57     OPT_R_ENUM, OPT_PROV_ENUM
58 } OPTION_CHOICE;
59
60 const OPTIONS passwd_options[] = {
61     {OPT_HELP_STR, 1, '-', "Usage: %s [options] [password]\n"},
62
63     OPT_SECTION("General"),
64     {"help", OPT_HELP, '-', "Display this summary"},
65
66     OPT_SECTION("Input"),
67     {"in", OPT_IN, '<', "Read passwords from file"},
68     {"noverify", OPT_NOVERIFY, '-',
69      "Never verify when reading password from terminal"},
70     {"stdin", OPT_STDIN, '-', "Read passwords from stdin"},
71
72     OPT_SECTION("Output"),
73     {"quiet", OPT_QUIET, '-', "No warnings"},
74     {"table", OPT_TABLE, '-', "Format output as table"},
75     {"reverse", OPT_REVERSE, '-', "Switch table columns"},
76
77     OPT_SECTION("Cryptographic"),
78     {"salt", OPT_SALT, 's', "Use provided salt"},
79     {"6", OPT_6, '-', "SHA512-based password algorithm"},
80     {"5", OPT_5, '-', "SHA256-based password algorithm"},
81     {"apr1", OPT_APR1, '-', "MD5-based password algorithm, Apache variant"},
82     {"1", OPT_1, '-', "MD5-based password algorithm"},
83     {"aixmd5", OPT_AIXMD5, '-', "AIX MD5-based password algorithm"},
84
85     OPT_R_OPTIONS,
86     OPT_PROV_OPTIONS,
87
88     OPT_PARAMETERS(),
89     {"password", 0, 0, "Password text to digest (optional)"},
90     {NULL}
91 };
92
93 int passwd_main(int argc, char **argv)
94 {
95     BIO *in = NULL;
96     char *infile = NULL, *salt = NULL, *passwd = NULL, **passwds = NULL;
97     char *salt_malloc = NULL, *passwd_malloc = NULL, *prog;
98     OPTION_CHOICE o;
99     int in_stdin = 0, pw_source_defined = 0;
100 #ifndef OPENSSL_NO_UI_CONSOLE
101     int in_noverify = 0;
102 #endif
103     int passed_salt = 0, quiet = 0, table = 0, reverse = 0;
104     int ret = 1;
105     passwd_modes mode = passwd_unset;
106     size_t passwd_malloc_size = 0;
107     size_t pw_maxlen = 256; /* arbitrary limit, should be enough for most
108                              * passwords */
109
110     prog = opt_init(argc, argv, passwd_options);
111     while ((o = opt_next()) != OPT_EOF) {
112         switch (o) {
113         case OPT_EOF:
114         case OPT_ERR:
115  opthelp:
116             BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
117             goto end;
118         case OPT_HELP:
119             opt_help(passwd_options);
120             ret = 0;
121             goto end;
122         case OPT_IN:
123             if (pw_source_defined)
124                 goto opthelp;
125             infile = opt_arg();
126             pw_source_defined = 1;
127             break;
128         case OPT_NOVERIFY:
129 #ifndef OPENSSL_NO_UI_CONSOLE
130             in_noverify = 1;
131 #endif
132             break;
133         case OPT_QUIET:
134             quiet = 1;
135             break;
136         case OPT_TABLE:
137             table = 1;
138             break;
139         case OPT_REVERSE:
140             reverse = 1;
141             break;
142         case OPT_1:
143             if (mode != passwd_unset)
144                 goto opthelp;
145             mode = passwd_md5;
146             break;
147         case OPT_5:
148             if (mode != passwd_unset)
149                 goto opthelp;
150             mode = passwd_sha256;
151             break;
152         case OPT_6:
153             if (mode != passwd_unset)
154                 goto opthelp;
155             mode = passwd_sha512;
156             break;
157         case OPT_APR1:
158             if (mode != passwd_unset)
159                 goto opthelp;
160             mode = passwd_apr1;
161             break;
162         case OPT_AIXMD5:
163             if (mode != passwd_unset)
164                 goto opthelp;
165             mode = passwd_aixmd5;
166             break;
167         case OPT_SALT:
168             passed_salt = 1;
169             salt = opt_arg();
170             break;
171         case OPT_STDIN:
172             if (pw_source_defined)
173                 goto opthelp;
174             in_stdin = 1;
175             pw_source_defined = 1;
176             break;
177         case OPT_R_CASES:
178             if (!opt_rand(o))
179                 goto end;
180             break;
181         case OPT_PROV_CASES:
182             if (!opt_provider(o))
183                 goto end;
184             break;
185         }
186     }
187
188     /* All remaining arguments are the password text */
189     argc = opt_num_rest();
190     argv = opt_rest();
191     if (*argv != NULL) {
192         if (pw_source_defined)
193             goto opthelp;
194         pw_source_defined = 1;
195         passwds = argv;
196     }
197
198     app_RAND_load();
199     if (mode == passwd_unset) {
200         /* use default */
201         mode = passwd_md5;
202     }
203
204     if (infile != NULL && in_stdin) {
205         BIO_printf(bio_err, "%s: Can't combine -in and -stdin\n", prog);
206         goto end;
207     }
208
209     if (infile != NULL || in_stdin) {
210         /*
211          * If in_stdin is true, we know that infile is NULL, and that
212          * bio_open_default() will give us back an alias for stdin.
213          */
214         in = bio_open_default(infile, 'r', FORMAT_TEXT);
215         if (in == NULL)
216             goto end;
217     }
218
219     if (passwds == NULL) {
220         /* no passwords on the command line */
221
222         passwd_malloc_size = pw_maxlen + 2;
223         /* longer than necessary so that we can warn about truncation */
224         passwd = passwd_malloc =
225             app_malloc(passwd_malloc_size, "password buffer");
226     }
227
228     if ((in == NULL) && (passwds == NULL)) {
229         /*
230          * we use the following method to make sure what
231          * in the 'else' section is always compiled, to
232          * avoid rot of not-frequently-used code.
233          */
234         if (1) {
235 #ifndef OPENSSL_NO_UI_CONSOLE
236             /* build a null-terminated list */
237             static char *passwds_static[2] = { NULL, NULL };
238
239             passwds = passwds_static;
240             if (in == NULL) {
241                 if (EVP_read_pw_string
242                     (passwd_malloc, passwd_malloc_size, "Password: ",
243                      !(passed_salt || in_noverify)) != 0)
244                     goto end;
245             }
246             passwds[0] = passwd_malloc;
247         } else {
248 #endif
249             BIO_printf(bio_err, "password required\n");
250             goto end;
251         }
252     }
253
254     if (in == NULL) {
255         assert(passwds != NULL);
256         assert(*passwds != NULL);
257
258         do {                    /* loop over list of passwords */
259             passwd = *passwds++;
260             if (!do_passwd(passed_salt, &salt, &salt_malloc, passwd, bio_out,
261                            quiet, table, reverse, pw_maxlen, mode))
262                 goto end;
263         } while (*passwds != NULL);
264     } else {
265         /* in != NULL */
266         int done;
267
268         assert(passwd != NULL);
269         do {
270             int r = BIO_gets(in, passwd, pw_maxlen + 1);
271             if (r > 0) {
272                 char *c = (strchr(passwd, '\n'));
273                 if (c != NULL) {
274                     *c = 0;     /* truncate at newline */
275                 } else {
276                     /* ignore rest of line */
277                     char trash[BUFSIZ];
278                     do
279                         r = BIO_gets(in, trash, sizeof(trash));
280                     while ((r > 0) && (!strchr(trash, '\n')));
281                 }
282
283                 if (!do_passwd
284                     (passed_salt, &salt, &salt_malloc, passwd, bio_out, quiet,
285                      table, reverse, pw_maxlen, mode))
286                     goto end;
287             }
288             done = (r <= 0);
289         } while (!done);
290     }
291     ret = 0;
292
293  end:
294 #if 0
295     ERR_print_errors(bio_err);
296 #endif
297     OPENSSL_free(salt_malloc);
298     OPENSSL_free(passwd_malloc);
299     BIO_free(in);
300     return ret;
301 }
302
303 /*
304  * MD5-based password algorithm (should probably be available as a library
305  * function; then the static buffer would not be acceptable). For magic
306  * string "1", this should be compatible to the MD5-based BSD password
307  * algorithm. For 'magic' string "apr1", this is compatible to the MD5-based
308  * Apache password algorithm. (Apparently, the Apache password algorithm is
309  * identical except that the 'magic' string was changed -- the laziest
310  * application of the NIH principle I've ever encountered.)
311  */
312 static char *md5crypt(const char *passwd, const char *magic, const char *salt)
313 {
314     /* "$apr1$..salt..$.......md5hash..........\0" */
315     static char out_buf[6 + 9 + 24 + 2];
316     unsigned char buf[MD5_DIGEST_LENGTH];
317     char ascii_magic[5];         /* "apr1" plus '\0' */
318     char ascii_salt[9];          /* Max 8 chars plus '\0' */
319     char *ascii_passwd = NULL;
320     char *salt_out;
321     int n;
322     unsigned int i;
323     EVP_MD_CTX *md = NULL, *md2 = NULL;
324     size_t passwd_len, salt_len, magic_len;
325
326     passwd_len = strlen(passwd);
327
328     out_buf[0] = 0;
329     magic_len = strlen(magic);
330     OPENSSL_strlcpy(ascii_magic, magic, sizeof(ascii_magic));
331 #ifdef CHARSET_EBCDIC
332     if ((magic[0] & 0x80) != 0)    /* High bit is 1 in EBCDIC alnums */
333         ebcdic2ascii(ascii_magic, ascii_magic, magic_len);
334 #endif
335
336     /* The salt gets truncated to 8 chars */
337     OPENSSL_strlcpy(ascii_salt, salt, sizeof(ascii_salt));
338     salt_len = strlen(ascii_salt);
339 #ifdef CHARSET_EBCDIC
340     ebcdic2ascii(ascii_salt, ascii_salt, salt_len);
341 #endif
342
343 #ifdef CHARSET_EBCDIC
344     ascii_passwd = OPENSSL_strdup(passwd);
345     if (ascii_passwd == NULL)
346         return NULL;
347     ebcdic2ascii(ascii_passwd, ascii_passwd, passwd_len);
348     passwd = ascii_passwd;
349 #endif
350
351     if (magic_len > 0) {
352         OPENSSL_strlcat(out_buf, ascii_dollar, sizeof(out_buf));
353
354         if (magic_len > 4)    /* assert it's  "1" or "apr1" */
355             goto err;
356
357         OPENSSL_strlcat(out_buf, ascii_magic, sizeof(out_buf));
358         OPENSSL_strlcat(out_buf, ascii_dollar, sizeof(out_buf));
359     }
360
361     OPENSSL_strlcat(out_buf, ascii_salt, sizeof(out_buf));
362
363     if (strlen(out_buf) > 6 + 8) /* assert "$apr1$..salt.." */
364         goto err;
365
366     salt_out = out_buf;
367     if (magic_len > 0)
368         salt_out += 2 + magic_len;
369
370     if (salt_len > 8)
371         goto err;
372
373     md = EVP_MD_CTX_new();
374     if (md == NULL
375         || !EVP_DigestInit_ex(md, EVP_md5(), NULL)
376         || !EVP_DigestUpdate(md, passwd, passwd_len))
377         goto err;
378
379     if (magic_len > 0)
380         if (!EVP_DigestUpdate(md, ascii_dollar, 1)
381             || !EVP_DigestUpdate(md, ascii_magic, magic_len)
382             || !EVP_DigestUpdate(md, ascii_dollar, 1))
383           goto err;
384
385     if (!EVP_DigestUpdate(md, ascii_salt, salt_len))
386         goto err;
387
388     md2 = EVP_MD_CTX_new();
389     if (md2 == NULL
390         || !EVP_DigestInit_ex(md2, EVP_md5(), NULL)
391         || !EVP_DigestUpdate(md2, passwd, passwd_len)
392         || !EVP_DigestUpdate(md2, ascii_salt, salt_len)
393         || !EVP_DigestUpdate(md2, passwd, passwd_len)
394         || !EVP_DigestFinal_ex(md2, buf, NULL))
395         goto err;
396
397     for (i = passwd_len; i > sizeof(buf); i -= sizeof(buf)) {
398         if (!EVP_DigestUpdate(md, buf, sizeof(buf)))
399             goto err;
400     }
401     if (!EVP_DigestUpdate(md, buf, i))
402         goto err;
403
404     n = passwd_len;
405     while (n) {
406         if (!EVP_DigestUpdate(md, (n & 1) ? "\0" : passwd, 1))
407             goto err;
408         n >>= 1;
409     }
410     if (!EVP_DigestFinal_ex(md, buf, NULL))
411         return NULL;
412
413     for (i = 0; i < 1000; i++) {
414         if (!EVP_DigestInit_ex(md2, EVP_md5(), NULL))
415             goto err;
416         if (!EVP_DigestUpdate(md2,
417                               (i & 1) ? (const unsigned char *)passwd : buf,
418                               (i & 1) ? passwd_len : sizeof(buf)))
419             goto err;
420         if (i % 3) {
421             if (!EVP_DigestUpdate(md2, ascii_salt, salt_len))
422                 goto err;
423         }
424         if (i % 7) {
425             if (!EVP_DigestUpdate(md2, passwd, passwd_len))
426                 goto err;
427         }
428         if (!EVP_DigestUpdate(md2,
429                               (i & 1) ? buf : (const unsigned char *)passwd,
430                               (i & 1) ? sizeof(buf) : passwd_len))
431                 goto err;
432         if (!EVP_DigestFinal_ex(md2, buf, NULL))
433                 goto err;
434     }
435     EVP_MD_CTX_free(md2);
436     EVP_MD_CTX_free(md);
437     md2 = NULL;
438     md = NULL;
439
440     {
441         /* transform buf into output string */
442         unsigned char buf_perm[sizeof(buf)];
443         int dest, source;
444         char *output;
445
446         /* silly output permutation */
447         for (dest = 0, source = 0; dest < 14;
448              dest++, source = (source + 6) % 17)
449             buf_perm[dest] = buf[source];
450         buf_perm[14] = buf[5];
451         buf_perm[15] = buf[11];
452 # ifndef PEDANTIC              /* Unfortunately, this generates a "no
453                                  * effect" warning */
454         assert(16 == sizeof(buf_perm));
455 # endif
456
457         output = salt_out + salt_len;
458         assert(output == out_buf + strlen(out_buf));
459
460         *output++ = ascii_dollar[0];
461
462         for (i = 0; i < 15; i += 3) {
463             *output++ = cov_2char[buf_perm[i + 2] & 0x3f];
464             *output++ = cov_2char[((buf_perm[i + 1] & 0xf) << 2) |
465                                   (buf_perm[i + 2] >> 6)];
466             *output++ = cov_2char[((buf_perm[i] & 3) << 4) |
467                                   (buf_perm[i + 1] >> 4)];
468             *output++ = cov_2char[buf_perm[i] >> 2];
469         }
470         assert(i == 15);
471         *output++ = cov_2char[buf_perm[i] & 0x3f];
472         *output++ = cov_2char[buf_perm[i] >> 6];
473         *output = 0;
474         assert(strlen(out_buf) < sizeof(out_buf));
475 #ifdef CHARSET_EBCDIC
476         ascii2ebcdic(out_buf, out_buf, strlen(out_buf));
477 #endif
478     }
479
480     return out_buf;
481
482  err:
483     OPENSSL_free(ascii_passwd);
484     EVP_MD_CTX_free(md2);
485     EVP_MD_CTX_free(md);
486     return NULL;
487 }
488
489 /*
490  * SHA based password algorithm, describe by Ulrich Drepper here:
491  * https://www.akkadia.org/drepper/SHA-crypt.txt
492  * (note that it's in the public domain)
493  */
494 static char *shacrypt(const char *passwd, const char *magic, const char *salt)
495 {
496     /* Prefix for optional rounds specification.  */
497     static const char rounds_prefix[] = "rounds=";
498     /* Maximum salt string length.  */
499 # define SALT_LEN_MAX 16
500     /* Default number of rounds if not explicitly specified.  */
501 # define ROUNDS_DEFAULT 5000
502     /* Minimum number of rounds.  */
503 # define ROUNDS_MIN 1000
504     /* Maximum number of rounds.  */
505 # define ROUNDS_MAX 999999999
506
507     /* "$6$rounds=<N>$......salt......$...shahash(up to 86 chars)...\0" */
508     static char out_buf[3 + 17 + 17 + 86 + 1];
509     unsigned char buf[SHA512_DIGEST_LENGTH];
510     unsigned char temp_buf[SHA512_DIGEST_LENGTH];
511     size_t buf_size = 0;
512     char ascii_magic[2];
513     char ascii_salt[17];          /* Max 16 chars plus '\0' */
514     char *ascii_passwd = NULL;
515     size_t n;
516     EVP_MD_CTX *md = NULL, *md2 = NULL;
517     const EVP_MD *sha = NULL;
518     size_t passwd_len, salt_len, magic_len;
519     unsigned int rounds = 5000;        /* Default */
520     char rounds_custom = 0;
521     char *p_bytes = NULL;
522     char *s_bytes = NULL;
523     char *cp = NULL;
524
525     passwd_len = strlen(passwd);
526     magic_len = strlen(magic);
527
528     /* assert it's "5" or "6" */
529     if (magic_len != 1)
530         return NULL;
531
532     switch (magic[0]) {
533     case '5':
534         sha = EVP_sha256();
535         buf_size = 32;
536         break;
537     case '6':
538         sha = EVP_sha512();
539         buf_size = 64;
540         break;
541     default:
542         return NULL;
543     }
544
545     if (strncmp(salt, rounds_prefix, sizeof(rounds_prefix) - 1) == 0) {
546         const char *num = salt + sizeof(rounds_prefix) - 1;
547         char *endp;
548         unsigned long int srounds = strtoul (num, &endp, 10);
549         if (*endp == '$') {
550             salt = endp + 1;
551             if (srounds > ROUNDS_MAX)
552                 rounds = ROUNDS_MAX;
553             else if (srounds < ROUNDS_MIN)
554                 rounds = ROUNDS_MIN;
555             else
556                 rounds = (unsigned int)srounds;
557             rounds_custom = 1;
558         } else {
559             return NULL;
560         }
561     }
562
563     OPENSSL_strlcpy(ascii_magic, magic, sizeof(ascii_magic));
564 #ifdef CHARSET_EBCDIC
565     if ((magic[0] & 0x80) != 0)    /* High bit is 1 in EBCDIC alnums */
566         ebcdic2ascii(ascii_magic, ascii_magic, magic_len);
567 #endif
568
569     /* The salt gets truncated to 16 chars */
570     OPENSSL_strlcpy(ascii_salt, salt, sizeof(ascii_salt));
571     salt_len = strlen(ascii_salt);
572 #ifdef CHARSET_EBCDIC
573     ebcdic2ascii(ascii_salt, ascii_salt, salt_len);
574 #endif
575
576 #ifdef CHARSET_EBCDIC
577     ascii_passwd = OPENSSL_strdup(passwd);
578     if (ascii_passwd == NULL)
579         return NULL;
580     ebcdic2ascii(ascii_passwd, ascii_passwd, passwd_len);
581     passwd = ascii_passwd;
582 #endif
583
584     out_buf[0] = 0;
585     OPENSSL_strlcat(out_buf, ascii_dollar, sizeof(out_buf));
586     OPENSSL_strlcat(out_buf, ascii_magic, sizeof(out_buf));
587     OPENSSL_strlcat(out_buf, ascii_dollar, sizeof(out_buf));
588     if (rounds_custom) {
589         char tmp_buf[80]; /* "rounds=999999999" */
590         sprintf(tmp_buf, "rounds=%u", rounds);
591 #ifdef CHARSET_EBCDIC
592         /* In case we're really on a ASCII based platform and just pretend */
593         if (tmp_buf[0] != 0x72)  /* ASCII 'r' */
594             ebcdic2ascii(tmp_buf, tmp_buf, strlen(tmp_buf));
595 #endif
596         OPENSSL_strlcat(out_buf, tmp_buf, sizeof(out_buf));
597         OPENSSL_strlcat(out_buf, ascii_dollar, sizeof(out_buf));
598     }
599     OPENSSL_strlcat(out_buf, ascii_salt, sizeof(out_buf));
600
601     /* assert "$5$rounds=999999999$......salt......" */
602     if (strlen(out_buf) > 3 + 17 * rounds_custom + salt_len )
603         goto err;
604
605     md = EVP_MD_CTX_new();
606     if (md == NULL
607         || !EVP_DigestInit_ex(md, sha, NULL)
608         || !EVP_DigestUpdate(md, passwd, passwd_len)
609         || !EVP_DigestUpdate(md, ascii_salt, salt_len))
610         goto err;
611
612     md2 = EVP_MD_CTX_new();
613     if (md2 == NULL
614         || !EVP_DigestInit_ex(md2, sha, NULL)
615         || !EVP_DigestUpdate(md2, passwd, passwd_len)
616         || !EVP_DigestUpdate(md2, ascii_salt, salt_len)
617         || !EVP_DigestUpdate(md2, passwd, passwd_len)
618         || !EVP_DigestFinal_ex(md2, buf, NULL))
619         goto err;
620
621     for (n = passwd_len; n > buf_size; n -= buf_size) {
622         if (!EVP_DigestUpdate(md, buf, buf_size))
623             goto err;
624     }
625     if (!EVP_DigestUpdate(md, buf, n))
626         goto err;
627
628     n = passwd_len;
629     while (n) {
630         if (!EVP_DigestUpdate(md,
631                               (n & 1) ? buf : (const unsigned char *)passwd,
632                               (n & 1) ? buf_size : passwd_len))
633             goto err;
634         n >>= 1;
635     }
636     if (!EVP_DigestFinal_ex(md, buf, NULL))
637         return NULL;
638
639     /* P sequence */
640     if (!EVP_DigestInit_ex(md2, sha, NULL))
641         goto err;
642
643     for (n = passwd_len; n > 0; n--)
644         if (!EVP_DigestUpdate(md2, passwd, passwd_len))
645             goto err;
646
647     if (!EVP_DigestFinal_ex(md2, temp_buf, NULL))
648         return NULL;
649
650     if ((p_bytes = OPENSSL_zalloc(passwd_len)) == NULL)
651         goto err;
652     for (cp = p_bytes, n = passwd_len; n > buf_size; n -= buf_size, cp += buf_size)
653         memcpy(cp, temp_buf, buf_size);
654     memcpy(cp, temp_buf, n);
655
656     /* S sequence */
657     if (!EVP_DigestInit_ex(md2, sha, NULL))
658         goto err;
659
660     for (n = 16 + buf[0]; n > 0; n--)
661         if (!EVP_DigestUpdate(md2, ascii_salt, salt_len))
662             goto err;
663
664     if (!EVP_DigestFinal_ex(md2, temp_buf, NULL))
665         return NULL;
666
667     if ((s_bytes = OPENSSL_zalloc(salt_len)) == NULL)
668         goto err;
669     for (cp = s_bytes, n = salt_len; n > buf_size; n -= buf_size, cp += buf_size)
670         memcpy(cp, temp_buf, buf_size);
671     memcpy(cp, temp_buf, n);
672
673     for (n = 0; n < rounds; n++) {
674         if (!EVP_DigestInit_ex(md2, sha, NULL))
675             goto err;
676         if (!EVP_DigestUpdate(md2,
677                               (n & 1) ? (const unsigned char *)p_bytes : buf,
678                               (n & 1) ? passwd_len : buf_size))
679             goto err;
680         if (n % 3) {
681             if (!EVP_DigestUpdate(md2, s_bytes, salt_len))
682                 goto err;
683         }
684         if (n % 7) {
685             if (!EVP_DigestUpdate(md2, p_bytes, passwd_len))
686                 goto err;
687         }
688         if (!EVP_DigestUpdate(md2,
689                               (n & 1) ? buf : (const unsigned char *)p_bytes,
690                               (n & 1) ? buf_size : passwd_len))
691                 goto err;
692         if (!EVP_DigestFinal_ex(md2, buf, NULL))
693                 goto err;
694     }
695     EVP_MD_CTX_free(md2);
696     EVP_MD_CTX_free(md);
697     md2 = NULL;
698     md = NULL;
699     OPENSSL_free(p_bytes);
700     OPENSSL_free(s_bytes);
701     p_bytes = NULL;
702     s_bytes = NULL;
703
704     cp = out_buf + strlen(out_buf);
705     *cp++ = ascii_dollar[0];
706
707 # define b64_from_24bit(B2, B1, B0, N)                                   \
708     do {                                                                \
709         unsigned int w = ((B2) << 16) | ((B1) << 8) | (B0);             \
710         int i = (N);                                                    \
711         while (i-- > 0)                                                 \
712             {                                                           \
713                 *cp++ = cov_2char[w & 0x3f];                            \
714                 w >>= 6;                                                \
715             }                                                           \
716     } while (0)
717
718     switch (magic[0]) {
719     case '5':
720         b64_from_24bit (buf[0], buf[10], buf[20], 4);
721         b64_from_24bit (buf[21], buf[1], buf[11], 4);
722         b64_from_24bit (buf[12], buf[22], buf[2], 4);
723         b64_from_24bit (buf[3], buf[13], buf[23], 4);
724         b64_from_24bit (buf[24], buf[4], buf[14], 4);
725         b64_from_24bit (buf[15], buf[25], buf[5], 4);
726         b64_from_24bit (buf[6], buf[16], buf[26], 4);
727         b64_from_24bit (buf[27], buf[7], buf[17], 4);
728         b64_from_24bit (buf[18], buf[28], buf[8], 4);
729         b64_from_24bit (buf[9], buf[19], buf[29], 4);
730         b64_from_24bit (0, buf[31], buf[30], 3);
731         break;
732     case '6':
733         b64_from_24bit (buf[0], buf[21], buf[42], 4);
734         b64_from_24bit (buf[22], buf[43], buf[1], 4);
735         b64_from_24bit (buf[44], buf[2], buf[23], 4);
736         b64_from_24bit (buf[3], buf[24], buf[45], 4);
737         b64_from_24bit (buf[25], buf[46], buf[4], 4);
738         b64_from_24bit (buf[47], buf[5], buf[26], 4);
739         b64_from_24bit (buf[6], buf[27], buf[48], 4);
740         b64_from_24bit (buf[28], buf[49], buf[7], 4);
741         b64_from_24bit (buf[50], buf[8], buf[29], 4);
742         b64_from_24bit (buf[9], buf[30], buf[51], 4);
743         b64_from_24bit (buf[31], buf[52], buf[10], 4);
744         b64_from_24bit (buf[53], buf[11], buf[32], 4);
745         b64_from_24bit (buf[12], buf[33], buf[54], 4);
746         b64_from_24bit (buf[34], buf[55], buf[13], 4);
747         b64_from_24bit (buf[56], buf[14], buf[35], 4);
748         b64_from_24bit (buf[15], buf[36], buf[57], 4);
749         b64_from_24bit (buf[37], buf[58], buf[16], 4);
750         b64_from_24bit (buf[59], buf[17], buf[38], 4);
751         b64_from_24bit (buf[18], buf[39], buf[60], 4);
752         b64_from_24bit (buf[40], buf[61], buf[19], 4);
753         b64_from_24bit (buf[62], buf[20], buf[41], 4);
754         b64_from_24bit (0, 0, buf[63], 2);
755         break;
756     default:
757         goto err;
758     }
759     *cp = '\0';
760 #ifdef CHARSET_EBCDIC
761     ascii2ebcdic(out_buf, out_buf, strlen(out_buf));
762 #endif
763
764     return out_buf;
765
766  err:
767     EVP_MD_CTX_free(md2);
768     EVP_MD_CTX_free(md);
769     OPENSSL_free(p_bytes);
770     OPENSSL_free(s_bytes);
771     OPENSSL_free(ascii_passwd);
772     return NULL;
773 }
774
775 static int do_passwd(int passed_salt, char **salt_p, char **salt_malloc_p,
776                      char *passwd, BIO *out, int quiet, int table,
777                      int reverse, size_t pw_maxlen, passwd_modes mode)
778 {
779     char *hash = NULL;
780
781     assert(salt_p != NULL);
782     assert(salt_malloc_p != NULL);
783
784     /* first make sure we have a salt */
785     if (!passed_salt) {
786         size_t saltlen = 0;
787         size_t i;
788
789         if (mode == passwd_md5 || mode == passwd_apr1 || mode == passwd_aixmd5)
790             saltlen = 8;
791
792         if (mode == passwd_sha256 || mode == passwd_sha512)
793             saltlen = 16;
794
795         assert(saltlen != 0);
796
797         if (*salt_malloc_p == NULL)
798             *salt_p = *salt_malloc_p = app_malloc(saltlen + 1, "salt buffer");
799         if (RAND_bytes((unsigned char *)*salt_p, saltlen) <= 0)
800             goto end;
801
802         for (i = 0; i < saltlen; i++)
803             (*salt_p)[i] = cov_2char[(*salt_p)[i] & 0x3f]; /* 6 bits */
804         (*salt_p)[i] = 0;
805 # ifdef CHARSET_EBCDIC
806         /* The password encryption function will convert back to ASCII */
807         ascii2ebcdic(*salt_p, *salt_p, saltlen);
808 # endif
809     }
810
811     assert(*salt_p != NULL);
812
813     /* truncate password if necessary */
814     if ((strlen(passwd) > pw_maxlen)) {
815         if (!quiet)
816             /*
817              * XXX: really we should know how to print a size_t, not cast it
818              */
819             BIO_printf(bio_err,
820                        "Warning: truncating password to %u characters\n",
821                        (unsigned)pw_maxlen);
822         passwd[pw_maxlen] = 0;
823     }
824     assert(strlen(passwd) <= pw_maxlen);
825
826     /* now compute password hash */
827     if (mode == passwd_md5 || mode == passwd_apr1)
828         hash = md5crypt(passwd, (mode == passwd_md5 ? "1" : "apr1"), *salt_p);
829     if (mode == passwd_aixmd5)
830         hash = md5crypt(passwd, "", *salt_p);
831     if (mode == passwd_sha256 || mode == passwd_sha512)
832         hash = shacrypt(passwd, (mode == passwd_sha256 ? "5" : "6"), *salt_p);
833     assert(hash != NULL);
834
835     if (table && !reverse)
836         BIO_printf(out, "%s\t%s\n", passwd, hash);
837     else if (table && reverse)
838         BIO_printf(out, "%s\t%s\n", hash, passwd);
839     else
840         BIO_printf(out, "%s\n", hash);
841     return 1;
842
843  end:
844     return 0;
845 }