mkpasswd.c (1694B)
1 /* see LICENSE file for copyright and license details */ 2 #ifndef _DEFAULT_SOURCE 3 #define _DEFAULT_SOURCE 4 #endif 5 #ifndef _XOPEN_SOURCE 6 #define _XOPEN_SOURCE 500 7 #endif 8 9 #include "passwd.h" 10 #include "util.h" 11 12 #include <stdio.h> 13 #include <stdlib.h> 14 #include <string.h> 15 #include <termios.h> 16 #include <unistd.h> 17 18 static void 19 usage(void) 20 { 21 eprintf("usage: %s [password]\n", argv0); 22 } 23 24 // ?man mkpasswd: generate a crypt(3) password hash 25 // ?man arguments: [password] 26 // ?man hash a password for use in /etc/passwd or /etc/shadow. reads 27 // ?man the password from the command line, or prompts for it if not given 28 int 29 main(int argc, char *argv[]) 30 { 31 static char buf[128]; 32 struct termios old, raw; 33 char salt[PW_SALT_MAX]; 34 char *pass, *hash; 35 int have_old; 36 size_t n; 37 38 ARGBEGIN 39 { 40 default: 41 usage(); 42 } 43 ARGEND 44 45 if (argc > 0) { 46 pass = argv[0]; 47 } else { 48 fputs("Password: ", stdout); 49 fflush(stdout); 50 51 have_old = tcgetattr(STDIN_FILENO, &old) == 0; 52 if (have_old) { 53 raw = old; 54 raw.c_lflag &= ~ECHO; 55 tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw); 56 } 57 58 if (!fgets(buf, sizeof(buf), stdin)) { 59 if (have_old) 60 tcsetattr(STDIN_FILENO, TCSAFLUSH, &old); 61 exit(1); 62 } 63 64 if (have_old) { 65 tcsetattr(STDIN_FILENO, TCSAFLUSH, &old); 66 fputc('\n', stdout); 67 } 68 69 n = strlen(buf); 70 if (n && buf[n - 1] == '\n') 71 buf[--n] = '\0'; 72 pass = buf; 73 } 74 75 pw_init(); 76 if (pw_gensalt(salt, sizeof(salt)) < 0) 77 eprintf("mkpasswd: cannot generate salt\n"); 78 79 hash = crypt(pass, salt); 80 if (!hash) 81 eprintf("mkpasswd: crypt:"); 82 83 printf("%s\n", hash); 84 return 0; 85 }