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