Fix passwd seg fault
[openssl.git] / apps / passwd.c
1 /* ====================================================================
2  * Copyright (c) 2000-2015 The OpenSSL Project.  All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  *
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in
13  *    the documentation and/or other materials provided with the
14  *    distribution.
15  *
16  * 3. All advertising materials mentioning features or use of this
17  *    software must display the following acknowledgment:
18  *    "This product includes software developed by the OpenSSL Project
19  *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
20  *
21  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
22  *    endorse or promote products derived from this software without
23  *    prior written permission. For written permission, please contact
24  *    licensing@OpenSSL.org.
25  *
26  * 5. Products derived from this software may not be called "OpenSSL"
27  *    nor may "OpenSSL" appear in their names without prior written
28  *    permission of the OpenSSL Project.
29  *
30  * 6. Redistributions of any form whatsoever must retain the following
31  *    acknowledgment:
32  *    "This product includes software developed by the OpenSSL Project
33  *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
34  *
35  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
36  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
37  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
38  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
39  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
41  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
42  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
43  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
44  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
45  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
46  * OF THE POSSIBILITY OF SUCH DAMAGE.
47  * ====================================================================
48  */
49
50 #if defined OPENSSL_NO_MD5 || defined CHARSET_EBCDIC
51 # define NO_MD5CRYPT_1
52 #endif
53
54 #if !defined(OPENSSL_NO_DES) || !defined(NO_MD5CRYPT_1)
55
56 # include <string.h>
57
58 # include "apps.h"
59
60 # include <openssl/bio.h>
61 # include <openssl/err.h>
62 # include <openssl/evp.h>
63 # include <openssl/rand.h>
64 # ifndef OPENSSL_NO_DES
65 #  include <openssl/des.h>
66 # endif
67 # ifndef NO_MD5CRYPT_1
68 #  include <openssl/md5.h>
69 # endif
70
71 static unsigned const char cov_2char[64] = {
72     /* from crypto/des/fcrypt.c */
73     0x2E, 0x2F, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35,
74     0x36, 0x37, 0x38, 0x39, 0x41, 0x42, 0x43, 0x44,
75     0x45, 0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B, 0x4C,
76     0x4D, 0x4E, 0x4F, 0x50, 0x51, 0x52, 0x53, 0x54,
77     0x55, 0x56, 0x57, 0x58, 0x59, 0x5A, 0x61, 0x62,
78     0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A,
79     0x6B, 0x6C, 0x6D, 0x6E, 0x6F, 0x70, 0x71, 0x72,
80     0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A
81 };
82
83 static int do_passwd(int passed_salt, char **salt_p, char **salt_malloc_p,
84                      char *passwd, BIO *out, int quiet, int table,
85                      int reverse, size_t pw_maxlen, int usecrypt, int use1,
86                      int useapr1);
87
88 typedef enum OPTION_choice {
89     OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
90     OPT_IN,
91     OPT_NOVERIFY, OPT_QUIET, OPT_TABLE, OPT_REVERSE, OPT_APR1,
92     OPT_1, OPT_CRYPT, OPT_SALT, OPT_STDIN
93 } OPTION_CHOICE;
94
95 OPTIONS passwd_options[] = {
96     {"help", OPT_HELP, '-', "Display this summary"},
97     {"in", OPT_IN, '<', "Pead passwords from file"},
98     {"noverify", OPT_NOVERIFY, '-',
99      "Never verify when reading password from terminal"},
100     {"quiet", OPT_QUIET, '-', "No warnings"},
101     {"table", OPT_TABLE, '-', "Format output as table"},
102     {"reverse", OPT_REVERSE, '-', "Switch table columns"},
103     {"salt", OPT_SALT, 's', "Use provided salt"},
104     {"stdin", OPT_STDIN, '-', "Read passwords from stdin"},
105 # ifndef NO_MD5CRYPT_1
106     {"apr1", OPT_APR1, '-', "MD5-based password algorithm, Apache variant"},
107     {"1", OPT_1, '-', "MD5-based password algorithm"},
108 # endif
109 # ifndef OPENSSL_NO_DES
110     {"crypt", OPT_CRYPT, '-', "Standard Unix password algorithm (default)"},
111 # endif
112     {NULL}
113 };
114
115 int passwd_main(int argc, char **argv)
116 {
117     BIO *in = NULL;
118     char *infile = NULL, *salt = NULL, *passwd = NULL, **passwds = NULL;
119     char *salt_malloc = NULL, *passwd_malloc = NULL, *prog;
120     OPTION_CHOICE o;
121     int in_stdin = 0, pw_source_defined = 0;
122 #ifndef OPENSSL_NO_UI
123     int in_noverify = 0;
124 #endif
125     int passed_salt = 0, quiet = 0, table = 0, reverse = 0;
126     int ret = 1, usecrypt = 0, use1 = 0, useapr1 = 0;
127     size_t passwd_malloc_size = 0, pw_maxlen = 256;
128
129     prog = opt_init(argc, argv, passwd_options);
130     while ((o = opt_next()) != OPT_EOF) {
131         switch (o) {
132         case OPT_EOF:
133         case OPT_ERR:
134  opthelp:
135             BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
136             goto end;
137         case OPT_HELP:
138             opt_help(passwd_options);
139             ret = 0;
140             goto end;
141         case OPT_IN:
142             if (pw_source_defined)
143                 goto opthelp;
144             infile = opt_arg();
145             pw_source_defined = 1;
146             break;
147         case OPT_NOVERIFY:
148 #ifndef OPENSSL_NO_UI
149             in_noverify = 1;
150 #endif
151             break;
152         case OPT_QUIET:
153             quiet = 1;
154             break;
155         case OPT_TABLE:
156             table = 1;
157             break;
158         case OPT_REVERSE:
159             reverse = 1;
160             break;
161         case OPT_1:
162             use1 = 1;
163             break;
164         case OPT_APR1:
165             useapr1 = 1;
166             break;
167         case OPT_CRYPT:
168             usecrypt = 1;
169             break;
170         case OPT_SALT:
171             passed_salt = 1;
172             salt = opt_arg();
173             break;
174         case OPT_STDIN:
175             if (pw_source_defined)
176                 goto opthelp;
177             in_stdin = 1;
178             pw_source_defined = 1;
179             break;
180         }
181     }
182     argc = opt_num_rest();
183     argv = opt_rest();
184
185     if (*argv) {
186         if (pw_source_defined)
187             goto opthelp;
188         pw_source_defined = 1;
189         passwds = argv;
190     }
191
192     if (!usecrypt && !use1 && !useapr1) {
193         /* use default */
194         usecrypt = 1;
195     }
196     if (usecrypt + use1 + useapr1 > 1) {
197         /* conflict */
198         goto opthelp;
199     }
200
201 # ifdef OPENSSL_NO_DES
202     if (usecrypt)
203         goto opthelp;
204 # endif
205 # ifdef NO_MD5CRYPT_1
206     if (use1 || useapr1)
207         goto opthelp;
208 # endif
209
210     if (infile != NULL && in_stdin) {
211         BIO_printf(bio_err, "%s: Can't combine -in and -stdin\n", prog);
212         goto end;
213     }
214
215     if (infile != NULL || in_stdin) {
216         /*
217          * If in_stdin is true, we know that infile is NULL, and that
218          * bio_open_default() will give us back an alias for stdin.
219          */
220         in = bio_open_default(infile, 'r', FORMAT_TEXT);
221         if (in == NULL)
222             goto end;
223     }
224
225     if (usecrypt)
226         pw_maxlen = 8;
227     else if (use1 || useapr1)
228         pw_maxlen = 256;        /* arbitrary limit, should be enough for most
229                                  * passwords */
230
231     if (passwds == NULL) {
232         /* no passwords on the command line */
233
234         passwd_malloc_size = pw_maxlen + 2;
235         /* longer than necessary so that we can warn about truncation */
236         passwd = passwd_malloc =
237             app_malloc(passwd_malloc_size, "password buffer");
238     }
239
240     if ((in == NULL) && (passwds == NULL)) {
241         if (1) {
242 #ifndef OPENSSL_NO_UI
243             /* build a null-terminated list */
244             static char *passwds_static[2] = { NULL, NULL };
245
246             passwds = passwds_static;
247             if (in == NULL)
248                 if (EVP_read_pw_string
249                     (passwd_malloc, passwd_malloc_size, "Password: ",
250                      !(passed_salt || in_noverify)) != 0)
251                     goto end;
252             passwds[0] = passwd_malloc;
253         } else {
254 #endif
255             BIO_printf(bio_err, "password required\n");
256             goto end;
257         }
258     }
259
260
261     if (in == NULL) {
262         assert(passwds != NULL);
263         assert(*passwds != NULL);
264
265         do {                    /* loop over list of passwords */
266             passwd = *passwds++;
267             if (!do_passwd(passed_salt, &salt, &salt_malloc, passwd, bio_out,
268                            quiet, table, reverse, pw_maxlen, usecrypt, use1,
269                            useapr1))
270                 goto end;
271         }
272         while (*passwds != NULL);
273     } else
274         /* in != NULL */
275     {
276         int done;
277
278         assert(passwd != NULL);
279         do {
280             int r = BIO_gets(in, passwd, pw_maxlen + 1);
281             if (r > 0) {
282                 char *c = (strchr(passwd, '\n'));
283                 if (c != NULL)
284                     *c = 0;     /* truncate at newline */
285                 else {
286                     /* ignore rest of line */
287                     char trash[BUFSIZ];
288                     do
289                         r = BIO_gets(in, trash, sizeof trash);
290                     while ((r > 0) && (!strchr(trash, '\n')));
291                 }
292
293                 if (!do_passwd
294                     (passed_salt, &salt, &salt_malloc, passwd, bio_out, quiet,
295                      table, reverse, pw_maxlen, usecrypt, use1, useapr1))
296                     goto end;
297             }
298             done = (r <= 0);
299         }
300         while (!done);
301     }
302     ret = 0;
303
304  end:
305     ERR_print_errors(bio_err);
306     OPENSSL_free(salt_malloc);
307     OPENSSL_free(passwd_malloc);
308     BIO_free(in);
309     return (ret);
310 }
311
312 # ifndef NO_MD5CRYPT_1
313 /*
314  * MD5-based password algorithm (should probably be available as a library
315  * function; then the static buffer would not be acceptable). For magic
316  * string "1", this should be compatible to the MD5-based BSD password
317  * algorithm. For 'magic' string "apr1", this is compatible to the MD5-based
318  * Apache password algorithm. (Apparently, the Apache password algorithm is
319  * identical except that the 'magic' string was changed -- the laziest
320  * application of the NIH principle I've ever encountered.)
321  */
322 static char *md5crypt(const char *passwd, const char *magic, const char *salt)
323 {
324     /* "$apr1$..salt..$.......md5hash..........\0" */
325     static char out_buf[6 + 9 + 24 + 2];
326     unsigned char buf[MD5_DIGEST_LENGTH];
327     char *salt_out;
328     int n;
329     unsigned int i;
330     EVP_MD_CTX *md, *md2;
331     size_t passwd_len, salt_len;
332
333     passwd_len = strlen(passwd);
334     out_buf[0] = '$';
335     out_buf[1] = 0;
336     assert(strlen(magic) <= 4); /* "1" or "apr1" */
337     OPENSSL_strlcat(out_buf, magic, sizeof out_buf);
338     OPENSSL_strlcat(out_buf, "$", sizeof out_buf);
339     OPENSSL_strlcat(out_buf, salt, sizeof out_buf);
340     assert(strlen(out_buf) <= 6 + 8); /* "$apr1$..salt.." */
341     salt_out = out_buf + 2 + strlen(magic);
342     salt_len = strlen(salt_out);
343     assert(salt_len <= 8);
344
345     md = EVP_MD_CTX_new();
346     if (md == NULL)
347         return NULL;
348     EVP_DigestInit_ex(md, EVP_md5(), NULL);
349     EVP_DigestUpdate(md, passwd, passwd_len);
350     EVP_DigestUpdate(md, "$", 1);
351     EVP_DigestUpdate(md, magic, strlen(magic));
352     EVP_DigestUpdate(md, "$", 1);
353     EVP_DigestUpdate(md, salt_out, salt_len);
354
355     md2 = EVP_MD_CTX_new();
356     if (md2 == NULL)
357         return NULL;
358     EVP_DigestInit_ex(md2, EVP_md5(), NULL);
359     EVP_DigestUpdate(md2, passwd, passwd_len);
360     EVP_DigestUpdate(md2, salt_out, salt_len);
361     EVP_DigestUpdate(md2, passwd, passwd_len);
362     EVP_DigestFinal_ex(md2, buf, NULL);
363
364     for (i = passwd_len; i > sizeof buf; i -= sizeof buf)
365         EVP_DigestUpdate(md, buf, sizeof buf);
366     EVP_DigestUpdate(md, buf, i);
367
368     n = passwd_len;
369     while (n) {
370         EVP_DigestUpdate(md, (n & 1) ? "\0" : passwd, 1);
371         n >>= 1;
372     }
373     EVP_DigestFinal_ex(md, buf, NULL);
374
375     for (i = 0; i < 1000; i++) {
376         EVP_DigestInit_ex(md2, EVP_md5(), NULL);
377         EVP_DigestUpdate(md2, (i & 1) ? (unsigned const char *)passwd : buf,
378                          (i & 1) ? passwd_len : sizeof buf);
379         if (i % 3)
380             EVP_DigestUpdate(md2, salt_out, salt_len);
381         if (i % 7)
382             EVP_DigestUpdate(md2, passwd, passwd_len);
383         EVP_DigestUpdate(md2, (i & 1) ? buf : (unsigned const char *)passwd,
384                          (i & 1) ? sizeof buf : passwd_len);
385         EVP_DigestFinal_ex(md2, buf, NULL);
386     }
387     EVP_MD_CTX_free(md2);
388     EVP_MD_CTX_free(md);
389
390     {
391         /* transform buf into output string */
392
393         unsigned char buf_perm[sizeof buf];
394         int dest, source;
395         char *output;
396
397         /* silly output permutation */
398         for (dest = 0, source = 0; dest < 14;
399              dest++, source = (source + 6) % 17)
400             buf_perm[dest] = buf[source];
401         buf_perm[14] = buf[5];
402         buf_perm[15] = buf[11];
403 #  ifndef PEDANTIC              /* Unfortunately, this generates a "no
404                                  * effect" warning */
405         assert(16 == sizeof buf_perm);
406 #  endif
407
408         output = salt_out + salt_len;
409         assert(output == out_buf + strlen(out_buf));
410
411         *output++ = '$';
412
413         for (i = 0; i < 15; i += 3) {
414             *output++ = cov_2char[buf_perm[i + 2] & 0x3f];
415             *output++ = cov_2char[((buf_perm[i + 1] & 0xf) << 2) |
416                                   (buf_perm[i + 2] >> 6)];
417             *output++ = cov_2char[((buf_perm[i] & 3) << 4) |
418                                   (buf_perm[i + 1] >> 4)];
419             *output++ = cov_2char[buf_perm[i] >> 2];
420         }
421         assert(i == 15);
422         *output++ = cov_2char[buf_perm[i] & 0x3f];
423         *output++ = cov_2char[buf_perm[i] >> 6];
424         *output = 0;
425         assert(strlen(out_buf) < sizeof(out_buf));
426     }
427
428     return out_buf;
429 }
430 # endif
431
432 static int do_passwd(int passed_salt, char **salt_p, char **salt_malloc_p,
433                      char *passwd, BIO *out, int quiet, int table,
434                      int reverse, size_t pw_maxlen, int usecrypt, int use1,
435                      int useapr1)
436 {
437     char *hash = NULL;
438
439     assert(salt_p != NULL);
440     assert(salt_malloc_p != NULL);
441
442     /* first make sure we have a salt */
443     if (!passed_salt) {
444 # ifndef OPENSSL_NO_DES
445         if (usecrypt) {
446             if (*salt_malloc_p == NULL) {
447                 *salt_p = *salt_malloc_p = app_malloc(3, "salt buffer");
448             }
449             if (RAND_bytes((unsigned char *)*salt_p, 2) <= 0)
450                 goto end;
451             (*salt_p)[0] = cov_2char[(*salt_p)[0] & 0x3f]; /* 6 bits */
452             (*salt_p)[1] = cov_2char[(*salt_p)[1] & 0x3f]; /* 6 bits */
453             (*salt_p)[2] = 0;
454 #  ifdef CHARSET_EBCDIC
455             ascii2ebcdic(*salt_p, *salt_p, 2); /* des_crypt will convert back
456                                                 * to ASCII */
457 #  endif
458         }
459 # endif                         /* !OPENSSL_NO_DES */
460
461 # ifndef NO_MD5CRYPT_1
462         if (use1 || useapr1) {
463             int i;
464
465             if (*salt_malloc_p == NULL) {
466                 *salt_p = *salt_malloc_p = app_malloc(9, "salt buffer");
467             }
468             if (RAND_bytes((unsigned char *)*salt_p, 8) <= 0)
469                 goto end;
470
471             for (i = 0; i < 8; i++)
472                 (*salt_p)[i] = cov_2char[(*salt_p)[i] & 0x3f]; /* 6 bits */
473             (*salt_p)[8] = 0;
474         }
475 # endif                         /* !NO_MD5CRYPT_1 */
476     }
477
478     assert(*salt_p != NULL);
479
480     /* truncate password if necessary */
481     if ((strlen(passwd) > pw_maxlen)) {
482         if (!quiet)
483             /*
484              * XXX: really we should know how to print a size_t, not cast it
485              */
486             BIO_printf(bio_err,
487                        "Warning: truncating password to %u characters\n",
488                        (unsigned)pw_maxlen);
489         passwd[pw_maxlen] = 0;
490     }
491     assert(strlen(passwd) <= pw_maxlen);
492
493     /* now compute password hash */
494 # ifndef OPENSSL_NO_DES
495     if (usecrypt)
496         hash = DES_crypt(passwd, *salt_p);
497 # endif
498 # ifndef NO_MD5CRYPT_1
499     if (use1 || useapr1)
500         hash = md5crypt(passwd, (use1 ? "1" : "apr1"), *salt_p);
501 # endif
502     assert(hash != NULL);
503
504     if (table && !reverse)
505         BIO_printf(out, "%s\t%s\n", passwd, hash);
506     else if (table && reverse)
507         BIO_printf(out, "%s\t%s\n", hash, passwd);
508     else
509         BIO_printf(out, "%s\n", hash);
510     return 0;
511
512  end:
513     return 1;
514 }
515 #else
516
517 int passwd_main(int argc, char **argv)
518 {
519     BIO_printf(bio_err, "Program not available.\n");
520     return (1);
521 }
522 #endif