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