Home | History | Annotate | Download | only in other
      1 /* mkpasswd.c - encrypt the given passwd using salt
      2  *
      3  * Copyright 2013 Ashwini Kumar <ak.ashwini (at) gmail.com>
      4  * Copyright 2013 Kyungwan Han <asura321 (at) gmail.com>
      5  *
      6  * No Standard
      7 
      8 USE_MKPASSWD(NEWTOY(mkpasswd, ">2S:m:P#=0<0", TOYFLAG_USR|TOYFLAG_BIN))
      9 
     10 config MKPASSWD
     11   bool "mkpasswd"
     12   default y
     13   help
     14     usage: mkpasswd [-P FD] [-m TYPE] [-S SALT] [PASSWORD] [SALT]
     15 
     16     Crypt PASSWORD using crypt(3)
     17 
     18     -P FD   Read password from file descriptor FD
     19     -m TYPE Encryption method (des, md5, sha256, or sha512; default is des)
     20     -S SALT
     21 */
     22 
     23 #define FOR_mkpasswd
     24 #include "toys.h"
     25 
     26 GLOBALS(
     27   long pfd;
     28   char *method;
     29   char *salt;
     30 )
     31 
     32 void mkpasswd_main(void)
     33 {
     34   char salt[MAX_SALT_LEN] = {0,};
     35   int i;
     36 
     37   if (!TT.method) TT.method = "des";
     38   if (toys.optc == 2) {
     39     if (TT.salt) error_exit("duplicate salt");
     40     TT.salt = toys.optargs[1];
     41   }
     42 
     43   if (-1 == (i = get_salt(salt, TT.method))) error_exit("bad -m");
     44   if (TT.salt) {
     45     char *s = TT.salt;
     46 
     47     // In C locale, isalnum() means [A-Za-Z0-0]
     48     while (isalnum(*s) || *s == '.' || *s == '/') s++;
     49     if (*s) error_exit("salt not in [./A-Za-z0-9]");
     50 
     51     snprintf(salt+i, sizeof(salt)-i, "%s", TT.salt);
     52   }
     53 
     54   // Because read_password() doesn't have an fd argument
     55   if (TT.pfd) {
     56     if (dup2(TT.pfd, 0) == -1) perror_exit("fd");
     57     close(TT.pfd);
     58   }
     59 
     60   // If we haven't got a password on the command line, read it from tty or FD
     61   if (!*toys.optargs) {
     62     // Prompt and read interactively?
     63     if (isatty(0)) {
     64       if (read_password(toybuf, sizeof(toybuf), "Password: "))
     65         perror_exit("password read failed");
     66     } else {
     67       for (i = 0; i<sizeof(toybuf)-1; i++) {
     68         if (!xread(0, toybuf+i, 1)) break;
     69         if (toybuf[i] == '\n' || toybuf[i] == '\r') break;
     70       }
     71       toybuf[i] = 0;
     72     }
     73   }
     74 
     75   // encrypt & print the password
     76   xprintf("%s\n",crypt(*toys.optargs ? *toys.optargs : toybuf, salt));
     77 }
     78