Use safer sizeof variant in malloc
[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 <assert.h>
57 # include <string.h>
58
59 # include "apps.h"
60
61 # include <openssl/bio.h>
62 # include <openssl/err.h>
63 # include <openssl/evp.h>
64 # include <openssl/rand.h>
65 # ifndef OPENSSL_NO_DES
66 #  include <openssl/des.h>
67 # endif
68 # ifndef NO_MD5CRYPT_1
69 #  include <openssl/md5.h>
70 # endif
71
72 static unsigned const char cov_2char[64] = {
73     /* from crypto/des/fcrypt.c */
74     0x2E, 0x2F, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35,
75     0x36, 0x37, 0x38, 0x39, 0x41, 0x42, 0x43, 0x44,
76     0x45, 0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B, 0x4C,
77     0x4D, 0x4E, 0x4F, 0x50, 0x51, 0x52, 0x53, 0x54,
78     0x55, 0x56, 0x57, 0x58, 0x59, 0x5A, 0x61, 0x62,
79     0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A,
80     0x6B, 0x6C, 0x6D, 0x6E, 0x6F, 0x70, 0x71, 0x72,
81     0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A
82 };
83
84 static int do_passwd(int passed_salt, char **salt_p, char **salt_malloc_p,
85                      char *passwd, BIO *out, int quiet, int table,
86                      int reverse, size_t pw_maxlen, int usecrypt, int use1,
87                      int useapr1);
88
89 typedef enum OPTION_choice {
90     OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
91     OPT_IN,
92     OPT_NOVERIFY, OPT_QUIET, OPT_TABLE, OPT_REVERSE, OPT_APR1,
93     OPT_1, OPT_CRYPT, OPT_SALT, OPT_STDIN
94 } OPTION_CHOICE;
95
96 OPTIONS passwd_options[] = {
97     {"help", OPT_HELP, '-', "Display this summary"},
98     {"in", OPT_IN, '<', "Pead passwords from file"},
99     {"noverify", OPT_NOVERIFY, '-',
100      "Never verify when reading password from terminal"},
101     {"quiet", OPT_QUIET, '-', "No warnings"},
102     {"table", OPT_TABLE, '-', "Format output as table"},
103     {"reverse", OPT_REVERSE, '-', "Switch table columns"},
104 # ifndef NO_MD5CRYPT_1
105     {"apr1", OPT_APR1, '-', "MD5-based password algorithm, Apache variant"},
106     {"1", OPT_1, '-', "MD5-based password algorithm"},
107 # endif
108 # ifndef OPENSSL_NO_DES
109     {"crypt", OPT_CRYPT, '-', "Standard Unix password algorithm (default)"},
110 # endif
111     {"salt", OPT_SALT, 's', "Use provided salt"},
112     {"stdin", OPT_STDIN, '-', "Read passwords from stdin"},
113     {NULL}
114 };
115
116 int passwd_main(int argc, char **argv)
117 {
118     BIO *in = NULL;
119     char *infile = NULL, *salt = NULL, *passwd = NULL, **passwds = NULL;
120     char *salt_malloc = NULL, *passwd_malloc = NULL, *prog;
121     OPTION_CHOICE o;
122     int in_stdin = 0, in_noverify = 0, pw_source_defined = 0;
123     int passed_salt = 0, quiet = 0, table = 0, reverse = 0;
124     int ret = 1, usecrypt = 0, use1 = 0, useapr1 = 0;
125     size_t passwd_malloc_size = 0, pw_maxlen = 256;
126
127     prog = opt_init(argc, argv, passwd_options);
128     while ((o = opt_next()) != OPT_EOF) {
129         switch (o) {
130         case OPT_EOF:
131         case OPT_ERR:
132  opthelp:
133             BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
134             goto end;
135         case OPT_HELP:
136             opt_help(passwd_options);
137             ret = 0;
138             goto end;
139         case OPT_IN:
140             if (pw_source_defined)
141                 goto opthelp;
142             infile = opt_arg();
143             pw_source_defined = 1;
144             break;
145         case OPT_NOVERIFY:
146             in_noverify = 1;
147             break;
148         case OPT_QUIET:
149             quiet = 1;
150             break;
151         case OPT_TABLE:
152             table = 1;
153             break;
154         case OPT_REVERSE:
155             reverse = 1;
156             break;
157         case OPT_1:
158             use1 = 1;
159             break;
160         case OPT_APR1:
161             useapr1 = 1;
162             break;
163         case OPT_CRYPT:
164             usecrypt = 1;
165             break;
166         case OPT_SALT:
167             passed_salt = 1;
168             salt = opt_arg();
169             break;
170         case OPT_STDIN:
171             if (pw_source_defined)
172                 goto opthelp;
173             in_stdin = 1;
174             break;
175         }
176     }
177     argc = opt_num_rest();
178     argv = opt_rest();
179
180     if (*argv) {
181         if (pw_source_defined)
182             goto opthelp;
183         pw_source_defined = 1;
184         passwds = argv;
185     }
186
187     if (!usecrypt && !use1 && !useapr1) {
188         /* use default */
189         usecrypt = 1;
190     }
191     if (usecrypt + use1 + useapr1 > 1) {
192         /* conflict */
193         goto opthelp;
194     }
195
196 # ifdef OPENSSL_NO_DES
197     if (usecrypt)
198         goto opthelp;
199 # endif
200 # ifdef NO_MD5CRYPT_1
201     if (use1 || useapr1)
202         goto opthelp;
203 # endif
204
205     if (infile && in_stdin) {
206         BIO_printf(bio_err, "%s: Can't combine -in and -stdin\n", prog);
207         goto end;
208     }
209
210     in = bio_open_default(infile, "r");
211     if (in == NULL)
212         goto end;
213
214     if (usecrypt)
215         pw_maxlen = 8;
216     else if (use1 || useapr1)
217         pw_maxlen = 256;        /* arbitrary limit, should be enough for most
218                                  * passwords */
219
220     if (passwds == NULL) {
221         /* no passwords on the command line */
222
223         passwd_malloc_size = pw_maxlen + 2;
224         /* longer than necessary so that we can warn about truncation */
225         passwd = passwd_malloc =
226             app_malloc(passwd_malloc_size, "password buffer");
227     }
228
229     if ((in == NULL) && (passwds == NULL)) {
230         /* build a null-terminated list */
231         static char *passwds_static[2] = { NULL, NULL };
232
233         passwds = passwds_static;
234         if (in == NULL)
235             if (EVP_read_pw_string
236                 (passwd_malloc, passwd_malloc_size, "Password: ",
237                  !(passed_salt || in_noverify)) != 0)
238                 goto end;
239         passwds[0] = passwd_malloc;
240     }
241
242     if (in == NULL) {
243         assert(passwds != NULL);
244         assert(*passwds != NULL);
245
246         do {                    /* loop over list of passwords */
247             passwd = *passwds++;
248             if (!do_passwd(passed_salt, &salt, &salt_malloc, passwd, bio_out,
249                            quiet, table, reverse, pw_maxlen, usecrypt, use1,
250                            useapr1))
251                 goto end;
252         }
253         while (*passwds != NULL);
254     } else
255         /* in != NULL */
256     {
257         int done;
258
259         assert(passwd != NULL);
260         do {
261             int r = BIO_gets(in, passwd, pw_maxlen + 1);
262             if (r > 0) {
263                 char *c = (strchr(passwd, '\n'));
264                 if (c != NULL)
265                     *c = 0;     /* truncate at newline */
266                 else {
267                     /* ignore rest of line */
268                     char trash[BUFSIZ];
269                     do
270                         r = BIO_gets(in, trash, sizeof trash);
271                     while ((r > 0) && (!strchr(trash, '\n')));
272                 }
273
274                 if (!do_passwd
275                     (passed_salt, &salt, &salt_malloc, passwd, bio_out, quiet,
276                      table, reverse, pw_maxlen, usecrypt, use1, useapr1))
277                     goto end;
278             }
279             done = (r <= 0);
280         }
281         while (!done);
282     }
283     ret = 0;
284
285  end:
286     ERR_print_errors(bio_err);
287     OPENSSL_free(salt_malloc);
288     OPENSSL_free(passwd_malloc);
289     BIO_free(in);
290     return (ret);
291 }
292
293 # ifndef NO_MD5CRYPT_1
294 /*
295  * MD5-based password algorithm (should probably be available as a library
296  * function; then the static buffer would not be acceptable). For magic
297  * string "1", this should be compatible to the MD5-based BSD password
298  * algorithm. For 'magic' string "apr1", this is compatible to the MD5-based
299  * Apache password algorithm. (Apparently, the Apache password algorithm is
300  * identical except that the 'magic' string was changed -- the laziest
301  * application of the NIH principle I've ever encountered.)
302  */
303 static char *md5crypt(const char *passwd, const char *magic, const char *salt)
304 {
305     /* "$apr1$..salt..$.......md5hash..........\0" */
306     static char out_buf[6 + 9 + 24 + 2];
307     unsigned char buf[MD5_DIGEST_LENGTH];
308     char *salt_out;
309     int n;
310     unsigned int i;
311     EVP_MD_CTX md, md2;
312     size_t passwd_len, salt_len;
313
314     passwd_len = strlen(passwd);
315     out_buf[0] = '$';
316     out_buf[1] = 0;
317     assert(strlen(magic) <= 4); /* "1" or "apr1" */
318     strncat(out_buf, magic, 4);
319     strncat(out_buf, "$", 1);
320     strncat(out_buf, salt, 8);
321     assert(strlen(out_buf) <= 6 + 8); /* "$apr1$..salt.." */
322     salt_out = out_buf + 2 + strlen(magic);
323     salt_len = strlen(salt_out);
324     assert(salt_len <= 8);
325
326     EVP_MD_CTX_init(&md);
327     EVP_DigestInit_ex(&md, EVP_md5(), NULL);
328     EVP_DigestUpdate(&md, passwd, passwd_len);
329     EVP_DigestUpdate(&md, "$", 1);
330     EVP_DigestUpdate(&md, magic, strlen(magic));
331     EVP_DigestUpdate(&md, "$", 1);
332     EVP_DigestUpdate(&md, salt_out, salt_len);
333
334     EVP_MD_CTX_init(&md2);
335     EVP_DigestInit_ex(&md2, EVP_md5(), NULL);
336     EVP_DigestUpdate(&md2, passwd, passwd_len);
337     EVP_DigestUpdate(&md2, salt_out, salt_len);
338     EVP_DigestUpdate(&md2, passwd, passwd_len);
339     EVP_DigestFinal_ex(&md2, buf, NULL);
340
341     for (i = passwd_len; i > sizeof buf; i -= sizeof buf)
342         EVP_DigestUpdate(&md, buf, sizeof buf);
343     EVP_DigestUpdate(&md, buf, i);
344
345     n = passwd_len;
346     while (n) {
347         EVP_DigestUpdate(&md, (n & 1) ? "\0" : passwd, 1);
348         n >>= 1;
349     }
350     EVP_DigestFinal_ex(&md, buf, NULL);
351
352     for (i = 0; i < 1000; i++) {
353         EVP_DigestInit_ex(&md2, EVP_md5(), NULL);
354         EVP_DigestUpdate(&md2, (i & 1) ? (unsigned const char *)passwd : buf,
355                          (i & 1) ? passwd_len : sizeof buf);
356         if (i % 3)
357             EVP_DigestUpdate(&md2, salt_out, salt_len);
358         if (i % 7)
359             EVP_DigestUpdate(&md2, passwd, passwd_len);
360         EVP_DigestUpdate(&md2, (i & 1) ? buf : (unsigned const char *)passwd,
361                          (i & 1) ? sizeof buf : passwd_len);
362         EVP_DigestFinal_ex(&md2, buf, NULL);
363     }
364     EVP_MD_CTX_cleanup(&md2);
365
366     {
367         /* transform buf into output string */
368
369         unsigned char buf_perm[sizeof buf];
370         int dest, source;
371         char *output;
372
373         /* silly output permutation */
374         for (dest = 0, source = 0; dest < 14;
375              dest++, source = (source + 6) % 17)
376             buf_perm[dest] = buf[source];
377         buf_perm[14] = buf[5];
378         buf_perm[15] = buf[11];
379 #  ifndef PEDANTIC              /* Unfortunately, this generates a "no
380                                  * effect" warning */
381         assert(16 == sizeof buf_perm);
382 #  endif
383
384         output = salt_out + salt_len;
385         assert(output == out_buf + strlen(out_buf));
386
387         *output++ = '$';
388
389         for (i = 0; i < 15; i += 3) {
390             *output++ = cov_2char[buf_perm[i + 2] & 0x3f];
391             *output++ = cov_2char[((buf_perm[i + 1] & 0xf) << 2) |
392                                   (buf_perm[i + 2] >> 6)];
393             *output++ = cov_2char[((buf_perm[i] & 3) << 4) |
394                                   (buf_perm[i + 1] >> 4)];
395             *output++ = cov_2char[buf_perm[i] >> 2];
396         }
397         assert(i == 15);
398         *output++ = cov_2char[buf_perm[i] & 0x3f];
399         *output++ = cov_2char[buf_perm[i] >> 6];
400         *output = 0;
401         assert(strlen(out_buf) < sizeof(out_buf));
402     }
403     EVP_MD_CTX_cleanup(&md);
404
405     return out_buf;
406 }
407 # endif
408
409 static int do_passwd(int passed_salt, char **salt_p, char **salt_malloc_p,
410                      char *passwd, BIO *out, int quiet, int table,
411                      int reverse, size_t pw_maxlen, int usecrypt, int use1,
412                      int useapr1)
413 {
414     char *hash = NULL;
415
416     assert(salt_p != NULL);
417     assert(salt_malloc_p != NULL);
418
419     /* first make sure we have a salt */
420     if (!passed_salt) {
421 # ifndef OPENSSL_NO_DES
422         if (usecrypt) {
423             if (*salt_malloc_p == NULL) {
424                 *salt_p = *salt_malloc_p = app_malloc(3, "salt buffer");
425             }
426             if (RAND_bytes((unsigned char *)*salt_p, 2) <= 0)
427                 goto end;
428             (*salt_p)[0] = cov_2char[(*salt_p)[0] & 0x3f]; /* 6 bits */
429             (*salt_p)[1] = cov_2char[(*salt_p)[1] & 0x3f]; /* 6 bits */
430             (*salt_p)[2] = 0;
431 #  ifdef CHARSET_EBCDIC
432             ascii2ebcdic(*salt_p, *salt_p, 2); /* des_crypt will convert back
433                                                 * to ASCII */
434 #  endif
435         }
436 # endif                         /* !OPENSSL_NO_DES */
437
438 # ifndef NO_MD5CRYPT_1
439         if (use1 || useapr1) {
440             int i;
441
442             if (*salt_malloc_p == NULL) {
443                 *salt_p = *salt_malloc_p = app_malloc(9, "salt buffer");
444             }
445             if (RAND_bytes((unsigned char *)*salt_p, 8) <= 0)
446                 goto end;
447
448             for (i = 0; i < 8; i++)
449                 (*salt_p)[i] = cov_2char[(*salt_p)[i] & 0x3f]; /* 6 bits */
450             (*salt_p)[8] = 0;
451         }
452 # endif                         /* !NO_MD5CRYPT_1 */
453     }
454
455     assert(*salt_p != NULL);
456
457     /* truncate password if necessary */
458     if ((strlen(passwd) > pw_maxlen)) {
459         if (!quiet)
460             /*
461              * XXX: really we should know how to print a size_t, not cast it
462              */
463             BIO_printf(bio_err,
464                        "Warning: truncating password to %u characters\n",
465                        (unsigned)pw_maxlen);
466         passwd[pw_maxlen] = 0;
467     }
468     assert(strlen(passwd) <= pw_maxlen);
469
470     /* now compute password hash */
471 # ifndef OPENSSL_NO_DES
472     if (usecrypt)
473         hash = DES_crypt(passwd, *salt_p);
474 # endif
475 # ifndef NO_MD5CRYPT_1
476     if (use1 || useapr1)
477         hash = md5crypt(passwd, (use1 ? "1" : "apr1"), *salt_p);
478 # endif
479     assert(hash != NULL);
480
481     if (table && !reverse)
482         BIO_printf(out, "%s\t%s\n", passwd, hash);
483     else if (table && reverse)
484         BIO_printf(out, "%s\t%s\n", hash, passwd);
485     else
486         BIO_printf(out, "%s\n", hash);
487     return 0;
488
489  end:
490     return 1;
491 }
492 #else
493
494 int passwd_main(int argc, char **argv)
495 {
496     fputs("Program not available.\n", stderr)
497         return (1);
498 }
499 #endif