1 /* pwgen.c - A password generator.
2 *
3 * Copyright 2020 Moritz R�hrich <[email protected]>
4
5 USE_PWGEN(NEWTOY(pwgen, ">2r(remove):c(capitalize)n(numerals)y(symbols)s(secure)B(ambiguous)h(help)C1vA(no-capitalize)0(no-numerals)[-cA][-n0][-C1]", TOYFLAG_USR|TOYFLAG_BIN))
6
7 config PWGEN
8 bool "pwgen"
9 default y
10 help
11 usage: pwgen [-cAn0yrsBC1v] [-r CHARS] [LENGTH] [COUNT]
12
13 Generate human-readable random passwords. Default output to tty fills screen
14 with passwords to defeat shoulder surfing (pick one and clear the screen).
15
16 -0 No numbers (--no-numerals)
17 -1 Output one per line
18 -A No capital letters (--no-capitalize)
19 -B Avoid ambiguous characters like 0O and 1lI (--ambiguous)
20 -C Output in columns
21 -c Add capital letters (--capitalize)
22 -n Add numbers (--numerals)
23 -r Don't include the given CHARS (--remove)
24 -v No vowels.
25 -y Add punctuation (--symbols)
26 */
27
28 #define FOR_pwgen
29 #include "toys.h"
30
GLOBALS(char * r;)31 GLOBALS(
32 char *r;
33 )
34
35 void pwgen_main(void)
36 {
37 int length = 8, count, ii, jj, c, rand = 0, x = 0;
38 unsigned xx = 80, yy = 24;
39 char randbuf[16];
40
41 if (isatty(1)) terminal_size(&xx, &yy);
42 else toys.optflags |= FLAG_1;
43
44 if (toys.optc && (length = atolx(*toys.optargs))>sizeof(toybuf))
45 error_exit("bad length");
46 if (toys.optc>1) count = atolx(toys.optargs[1]);
47 else count = FLAG(1) ? 1 : (xx/(length+1))*(yy-1);
48
49 for (jj = 0; jj<count; jj++) {
50 for (ii = 0; ii<length;) {
51 // Don't fetch more random than necessary, give each byte 2 tries to fit
52 if (!rand) xgetrandom(randbuf, rand = sizeof(randbuf));
53 c = 33+randbuf[--rand]%94; // remainder 67 makes >102 less likely
54 randbuf[rand] = 0;
55
56 if (c>='A' && c<='Z') {
57 if (FLAG(A)) continue;
58 // take out half the capital letters to be more human readable
59 else c |= (0x80&randbuf[rand])>>2;
60 }
61 if (FLAG(0) && c>='0' && c<='9') continue;
62 if (FLAG(B) && strchr("0O1lI8B5S2ZD'`.,", c)) continue;
63 if (FLAG(v) && strchr("aeiou", tolower(c))) continue;
64 if (!FLAG(y) || (0x80&randbuf[rand]))
65 if (c<'0' || (c>'9' && c<'A') || (c>'Z' && c<'a') || c>'z') continue;
66 if (TT.r && strchr(TT.r, c)) continue;
67
68 toybuf[ii++] = c;
69 }
70 if (FLAG(1) || (x += length+1)+length>=xx) x = 0;
71 xprintf("%.*s%c", length, toybuf, x ? ' ' : '\n');
72 }
73 if (x) xputc('\n');
74 }
75