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