sngrep: fix error if gnutls and openssl are both enabled
[buildroot-gz.git] / package / mkpasswd / mkpasswd.c
blob5820f325019e8e374642bc0bf346c9077612481d
1 /*
2 * Copyright (C) 2001-2008 Marco d'Itri
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 /* for crypt, snprintf and strcasecmp */
20 #define _XOPEN_SOURCE
21 #define _BSD_SOURCE
23 /* System library */
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <unistd.h>
27 #include "config.h"
28 #ifdef HAVE_GETOPT_LONG
29 #include <getopt.h>
30 #endif
31 #include <fcntl.h>
32 #include <string.h>
33 #include <time.h>
34 #include <sys/types.h>
35 #ifdef HAVE_XCRYPT
36 #include <xcrypt.h>
37 #include <sys/stat.h>
38 #endif
39 #ifdef HAVE_LINUX_CRYPT_GENSALT
40 #define _OW_SOURCE
41 #include <crypt.h>
42 #endif
43 #ifdef HAVE_GETTIMEOFDAY
44 #include <sys/time.h>
45 #endif
47 /* Application-specific */
48 #include "utils.h"
50 /* Global variables */
51 #ifdef HAVE_GETOPT_LONG
52 static const struct option longopts[] = {
53 {"method", optional_argument, NULL, 'm'},
54 /* for backward compatibility with versions < 4.7.25 (< 20080321): */
55 {"hash", optional_argument, NULL, 'H'},
56 {"help", no_argument, NULL, 'h'},
57 {"password-fd", required_argument, NULL, 'P'},
58 {"stdin", no_argument, NULL, 's'},
59 {"salt", required_argument, NULL, 'S'},
60 {"rounds", required_argument, NULL, 'R'},
61 {"version", no_argument, NULL, 'V'},
62 {NULL, 0, NULL, 0 }
64 #else
65 extern char *optarg;
66 extern int optind;
67 #endif
69 static const char valid_salts[] = "abcdefghijklmnopqrstuvwxyz"
70 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789./";
72 struct crypt_method {
73 const char *method; /* short name used by the command line option */
74 const char *prefix; /* salt prefix */
75 const unsigned int minlen; /* minimum salt length */
76 const unsigned int maxlen; /* maximum salt length */
77 const unsigned int rounds; /* supports a variable number of rounds */
78 const char *desc; /* long description for the methods list */
81 static const struct crypt_method methods[] = {
82 /* method prefix minlen, maxlen rounds description */
83 { "des", "", 2, 2, 0,
84 N_("standard 56 bit DES-based crypt(3)") },
85 { "md5", "$1$", 8, 8, 0, "MD5" },
86 #if defined OpenBSD || defined FreeBSD || (defined __SVR4 && defined __sun)
87 { "bf", "$2a$", 22, 22, 1, "Blowfish" },
88 #endif
89 #if defined HAVE_LINUX_CRYPT_GENSALT
90 { "bf", "$2a$", 22, 22, 1, "Blowfish, system-specific on 8-bit chars" },
91 /* algorithm 2y fixes CVE-2011-2483 */
92 { "bfy", "$2y$", 22, 22, 1, "Blowfish, correct handling of 8-bit chars" },
93 #endif
94 #if defined FreeBSD
95 { "nt", "$3$", 0, 0, 0, "NT-Hash" },
96 #endif
97 #if defined HAVE_SHA_CRYPT
98 /* http://people.redhat.com/drepper/SHA-crypt.txt */
99 { "sha-256", "$5$", 8, 16, 1, "SHA-256" },
100 { "sha-512", "$6$", 8, 16, 1, "SHA-512" },
101 #endif
102 /* http://www.crypticide.com/dropsafe/article/1389 */
104 * Actually the maximum salt length is arbitrary, but Solaris by default
105 * always uses 8 characters:
106 * http://cvs.opensolaris.org/source/xref/onnv/onnv-gate/ \
107 * usr/src/lib/crypt_modules/sunmd5/sunmd5.c#crypt_gensalt_impl
109 #if defined __SVR4 && defined __sun
110 { "sunmd5", "$md5$", 8, 8, 1, "SunMD5" },
111 #endif
112 { NULL, NULL, 0, 0, 0, NULL }
115 void generate_salt(char *const buf, const unsigned int len);
116 void *get_random_bytes(const int len);
117 void display_help(int error);
118 void display_version(void);
119 void display_methods(void);
121 int main(int argc, char *argv[])
123 int ch, i;
124 int password_fd = -1;
125 unsigned int salt_minlen = 0;
126 unsigned int salt_maxlen = 0;
127 unsigned int rounds_support = 0;
128 const char *salt_prefix = NULL;
129 const char *salt_arg = NULL;
130 unsigned int rounds = 0;
131 char *salt = NULL;
132 char rounds_str[30];
133 char *password = NULL;
135 #ifdef ENABLE_NLS
136 setlocale(LC_ALL, "");
137 bindtextdomain(NLS_CAT_NAME, LOCALEDIR);
138 textdomain(NLS_CAT_NAME);
139 #endif
141 /* prepend options from environment */
142 argv = merge_args(getenv("MKPASSWD_OPTIONS"), argv, &argc);
144 while ((ch = GETOPT_LONGISH(argc, argv, "hH:m:5P:R:sS:V", longopts, 0))
145 > 0) {
146 switch (ch) {
147 case '5':
148 optarg = (char *) "md5";
149 /* fall through */
150 case 'm':
151 case 'H':
152 if (!optarg || strcaseeq("help", optarg)) {
153 display_methods();
154 exit(0);
156 for (i = 0; methods[i].method != NULL; i++)
157 if (strcaseeq(methods[i].method, optarg)) {
158 salt_prefix = methods[i].prefix;
159 salt_minlen = methods[i].minlen;
160 salt_maxlen = methods[i].maxlen;
161 rounds_support = methods[i].rounds;
162 break;
164 if (!salt_prefix) {
165 fprintf(stderr, _("Invalid method '%s'.\n"), optarg);
166 exit(1);
168 break;
169 case 'P':
171 char *p;
172 password_fd = strtol(optarg, &p, 10);
173 if (p == NULL || *p != '\0' || password_fd < 0) {
174 fprintf(stderr, _("Invalid number '%s'.\n"), optarg);
175 exit(1);
178 break;
179 case 'R':
181 char *p;
182 rounds = strtol(optarg, &p, 10);
183 if (p == NULL || *p != '\0' || rounds < 0) {
184 fprintf(stderr, _("Invalid number '%s'.\n"), optarg);
185 exit(1);
188 break;
189 case 's':
190 password_fd = 0;
191 break;
192 case 'S':
193 salt_arg = optarg;
194 break;
195 case 'V':
196 display_version();
197 exit(0);
198 case 'h':
199 display_help(EXIT_SUCCESS);
200 default:
201 fprintf(stderr, _("Try '%s --help' for more information.\n"),
202 argv[0]);
203 exit(1);
206 argc -= optind;
207 argv += optind;
209 if (argc == 2 && !salt_arg) {
210 password = argv[0];
211 salt_arg = argv[1];
212 } else if (argc == 1) {
213 password = argv[0];
214 } else if (argc == 0) {
215 } else {
216 display_help(EXIT_FAILURE);
219 /* default: DES password */
220 if (!salt_prefix) {
221 salt_minlen = methods[0].minlen;
222 salt_maxlen = methods[0].maxlen;
223 salt_prefix = methods[0].prefix;
226 if (streq(salt_prefix, "$2a$") || streq(salt_prefix, "$2y$")) {
227 /* OpenBSD Blowfish and derivatives */
228 if (rounds <= 5)
229 rounds = 5;
230 /* actually for 2a/2y it is the logarithm of the number of rounds */
231 snprintf(rounds_str, sizeof(rounds_str), "%02u$", rounds);
232 } else if (rounds_support && rounds)
233 snprintf(rounds_str, sizeof(rounds_str), "rounds=%u$", rounds);
234 else
235 rounds_str[0] = '\0';
237 if (salt_arg) {
238 unsigned int c = strlen(salt_arg);
239 if (c < salt_minlen || c > salt_maxlen) {
240 if (salt_minlen == salt_maxlen)
241 fprintf(stderr, ngettext(
242 "Wrong salt length: %d byte when %d expected.\n",
243 "Wrong salt length: %d bytes when %d expected.\n", c),
244 c, salt_maxlen);
245 else
246 fprintf(stderr, ngettext(
247 "Wrong salt length: %d byte when %d <= n <= %d"
248 " expected.\n",
249 "Wrong salt length: %d bytes when %d <= n <= %d"
250 " expected.\n", c),
251 c, salt_minlen, salt_maxlen);
252 exit(1);
254 while (c-- > 0) {
255 if (strchr(valid_salts, salt_arg[c]) == NULL) {
256 fprintf(stderr, _("Illegal salt character '%c'.\n"),
257 salt_arg[c]);
258 exit(1);
262 salt = NOFAIL(malloc(strlen(salt_prefix) + strlen(rounds_str)
263 + strlen(salt_arg) + 1));
264 *salt = '\0';
265 strcat(salt, salt_prefix);
266 strcat(salt, rounds_str);
267 strcat(salt, salt_arg);
268 } else {
269 #ifdef HAVE_SOLARIS_CRYPT_GENSALT
270 #error "This code path is untested on Solaris. Please send a patch."
271 salt = crypt_gensalt(salt_prefix, NULL);
272 if (!salt)
273 perror(stderr, "crypt_gensalt");
274 #elif defined HAVE_LINUX_CRYPT_GENSALT
275 void *entropy = get_random_bytes(64);
277 salt = crypt_gensalt(salt_prefix, rounds, entropy, 64);
278 if (!salt) {
279 fprintf(stderr, "crypt_gensalt failed.\n");
280 exit(2);
282 free(entropy);
283 #else
284 unsigned int salt_len = salt_maxlen;
286 if (salt_minlen != salt_maxlen) { /* salt length can vary */
287 srand(time(NULL) + getpid());
288 salt_len = rand() % (salt_maxlen - salt_minlen + 1) + salt_minlen;
291 salt = NOFAIL(malloc(strlen(salt_prefix) + strlen(rounds_str)
292 + salt_len + 1));
293 *salt = '\0';
294 strcat(salt, salt_prefix);
295 strcat(salt, rounds_str);
296 generate_salt(salt + strlen(salt), salt_len);
297 #endif
300 if (password) {
301 } else if (password_fd != -1) {
302 FILE *fp;
303 char *p;
305 if (isatty(password_fd))
306 fprintf(stderr, _("Password: "));
307 password = NOFAIL(malloc(128));
308 fp = fdopen(password_fd, "r");
309 if (!fp) {
310 perror("fdopen");
311 exit(2);
313 if (!fgets(password, 128, fp)) {
314 perror("fgets");
315 exit(2);
318 p = strpbrk(password, "\n\r");
319 if (p)
320 *p = '\0';
321 } else {
322 password = getpass(_("Password: "));
323 if (!password) {
324 perror("getpass");
325 exit(2);
330 const char *result;
331 result = crypt(password, salt);
332 /* xcrypt returns "*0" on errors */
333 if (!result || result[0] == '*') {
334 fprintf(stderr, "crypt failed.\n");
335 exit(2);
337 /* yes, using strlen(salt_prefix) on salt. It's not
338 * documented whether crypt_gensalt may change the prefix */
339 if (!strneq(result, salt, strlen(salt_prefix))) {
340 fprintf(stderr, _("Method not supported by crypt(3).\n"));
341 exit(2);
343 printf("%s\n", result);
346 exit(0);
349 #ifdef RANDOM_DEVICE
350 void* get_random_bytes(const int count)
352 char *buf;
353 int fd;
355 buf = NOFAIL(malloc(count));
356 fd = open(RANDOM_DEVICE, O_RDONLY);
357 if (fd < 0) {
358 perror("open(" RANDOM_DEVICE ")");
359 exit(2);
361 if (read(fd, buf, count) != count) {
362 if (count < 0)
363 perror("read(" RANDOM_DEVICE ")");
364 else
365 fprintf(stderr, "Short read of %s.\n", RANDOM_DEVICE);
366 exit(2);
368 close(fd);
370 return buf;
372 #endif
374 #ifdef RANDOM_DEVICE
376 void generate_salt(char *const buf, const unsigned int len)
378 unsigned int i;
380 unsigned char *entropy = get_random_bytes(len * sizeof(unsigned char));
381 for (i = 0; i < len; i++)
382 buf[i] = valid_salts[entropy[i] % (sizeof valid_salts - 1)];
383 buf[i] = '\0';
386 #else /* RANDOM_DEVICE */
388 void generate_salt(char *const buf, const unsigned int len)
390 unsigned int i;
392 # ifdef HAVE_GETTIMEOFDAY
393 struct timeval tv;
395 gettimeofday(&tv, NULL);
396 srand(tv.tv_sec ^ tv.tv_usec);
398 # else /* HAVE_GETTIMEOFDAY */
399 # warning "This system lacks a strong enough random numbers generator!"
402 * The possible values of time over one year are 31536000, which is
403 * two orders of magnitude less than the allowed entropy range (2^32).
405 srand(time(NULL) + getpid());
407 # endif /* HAVE_GETTIMEOFDAY */
409 for (i = 0; i < len; i++)
410 buf[i] = valid_salts[rand() % (sizeof valid_salts - 1)];
411 buf[i] = '\0';
414 #endif /* RANDOM_DEVICE */
416 void display_help(int error)
418 fprintf((EXIT_SUCCESS == error) ? stdout : stderr,
419 _("Usage: mkpasswd [OPTIONS]... [PASSWORD [SALT]]\n"
420 "Crypts the PASSWORD using crypt(3).\n\n"));
421 fprintf(stderr, _(
422 " -m, --method=TYPE select method TYPE\n"
423 " -5 like --method=md5\n"
424 " -S, --salt=SALT use the specified SALT\n"
425 " -R, --rounds=NUMBER use the specified NUMBER of rounds\n"
426 " -P, --password-fd=NUM read the password from file descriptor NUM\n"
427 " instead of /dev/tty\n"
428 " -s, --stdin like --password-fd=0\n"
429 " -h, --help display this help and exit\n"
430 " -V, --version output version information and exit\n"
431 "\n"
432 "If PASSWORD is missing then it is asked interactively.\n"
433 "If no SALT is specified, a random one is generated.\n"
434 "If TYPE is 'help', available methods are printed.\n"
435 "\n"
436 "Report bugs to %s.\n"), "<md+whois@linux.it>");
437 exit(error);
440 void display_version(void)
442 printf("mkpasswd %s\n\n", VERSION);
443 puts("Copyright (C) 2001-2008 Marco d'Itri\n"
444 "This is free software; see the source for copying conditions. There is NO\n"
445 "warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.");
448 void display_methods(void)
450 unsigned int i;
452 printf(_("Available methods:\n"));
453 for (i = 0; methods[i].method != NULL; i++)
454 printf("%s\t%s\n", methods[i].method, methods[i].desc);