/
gen-password
executable file
·377 lines (271 loc) · 8.78 KB
/
gen-password
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
#!/usr/bin/perl
# Copyright (C) 2021 Keith Thompson
# This file is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, see <http://www.gnu.org/licenses/>.
use strict;
use warnings;
use File::Spec ();
use Getopt::Long qw(:config no_ignore_case); # hexadecimal vs. -Hexadecimal
use Pod::Usage ();
my $program_name = (File::Spec->splitpath($0))[2];
my %opt = (
length => 12
);
Getopt::Long::GetOptions(
\%opt,
qw(
help|hel|he|h!
help1!
help2!
man!
n!
length=i
charset=s
decimal|digits!
hexadecimal!
Hexadecimal|HEXADECIMAL!
octal!
lower!
upper!
alphanumeric!
printable!
1lower!
1upper!
1decimal|1digit!
1punctuation!
1charset=s@
split=i
dev-random!
debugging!
)
) or Pod::Usage::pod2usage(-verbose => 0, -exitvalue => 2);
Pod::Usage::pod2usage(-verbose => 2, -exitvalue => 0) if $opt{man};
Pod::Usage::pod2usage(-verbose => 2, -exitvalue => 0, -perldocopt, '-T -t') if $opt{help2};
Pod::Usage::pod2usage(-verbose => 1, -exitvalue => 0) if $opt{help1};
Pod::Usage::pod2usage(-verbose => 0, -exitvalue => 0) if $opt{help};
Pod::Usage::pod2usage(-verbose => 0, -exitvalue => 2) if @ARGV;
$| = 1;
my $format_count = 0;
foreach my $opt (qw(charset decimal hexadecimal Hexadecimal octal
lower upper alphanumeric printable))
{
$format_count ++ if defined $opt{$opt};
}
if ($format_count == 0) { $opt{charset} = '0-9a-z' }
elsif ($format_count > 1) {
Pod::Usage::pod2usage(
-message => "Use only one charset option\n",
-verbose => 0,
-exitvalue => 2
)
}
elsif ($opt{decimal}) { $opt{charset} = '0-9' }
elsif ($opt{hexadecimal}) { $opt{charset} = '0-9a-f' }
elsif ($opt{Hexadecimal}) { $opt{charset} = '0-9A-F' }
elsif ($opt{octal}) { $opt{charset} = '0-7' }
elsif ($opt{lower}) { $opt{charset} = 'a-z' }
elsif ($opt{upper}) { $opt{charset} = 'A-Z' }
elsif ($opt{alphanumeric}) { $opt{charset} = 'A-Za-z0-9' }
elsif ($opt{printable}) { $opt{charset} = '!-~' }
my @valid_chars = split //, build_charset($opt{charset});
my $password = '';
my $device = $opt{'dev-random'} ? '/dev/random' : '/dev/urandom';
open my $DEVICE, '<', $device or die "${device}: $!\n";
for (my $i = 0; $i < $opt{length}; $i ++) {
$password .= $valid_chars[random(scalar @valid_chars, $DEVICE)];
}
my @singletons = ();
if ($opt{'1decimal'}) {
push @singletons, '0-9';
}
if ($opt{'1lower'}) {
push @singletons, 'a-z';
}
if ($opt{'1upper'}) {
push @singletons, 'A-Z';
}
if ($opt{'1punctuation'}) {
my $singleton = join('', map {chr $_} 33..126);
$singleton =~ s/[0-9a-zA-Z]//g;
push @singletons, $singleton;
}
if (defined $opt{'1charset'}) {
push @singletons, @{$opt{'1charset'}};
}
die "Too many singletons\n" if scalar @singletons > length $password;
my @indices = 0 .. length($password) - 1;
foreach my $singleton (@singletons) {
my $index = $indices[random(scalar @indices, $DEVICE)];
substr($password, $index, 1) = single_character($singleton, $DEVICE);
my $last_index = pop @indices;
if ($index <= $#indices) {
$indices[$index] = $last_index;
}
}
close $DEVICE or die "${device}: $!\n";
if (defined $opt{split}) {
my $N_chars = '.' x $opt{split};
$password =~ s/$N_chars(?!$)/$& /g;
}
if ($opt{n}) {
print $password;
}
else {
print "$password\n";
}
########################################################################
#
# random($upper, $DEVICE) returns a random number in the range 0 .. $upper-1
# $DEVICE is a file handle already opened to /dev/urandom or /dev/random
#
sub random {
my($upper, $DEVICE) = @_;
my $buf;
my $short_bound = 2**16;
my $value_bound = $short_bound - ($short_bound % $upper);
my $value;
# Values read from the device will be in the range 0 .. $short_bound-1
# (0..65535). Repeat if necessary to get a value in the range
# 0..$value_bound-1, which is computed to avoid bias; the number of possible
# values read is a multiple of $upper.
#
# Read 2 bytes from device.
# Discard high values to avoid bias.
#
do {
my $bytes_read = read $DEVICE, $buf, 2;
die "Failed to read from $device\n" if $bytes_read != 2;
$value = unpack 'S', $buf;
debugf("Read value 0x%04x\n", $value);
} while $value >= $value_bound;
my $result = $value % $upper;
debugf("random: 0x%04x %% %d --> %d\n",
$value, $upper, $result);
return $result;
}
sub expand_range {
my($range) = @_;
my $result;
die "Internal error in expand_range\n" if $range !~ /^(.)-(.)$/;
my($lo, $hi) = ($1, $2);
die "Bad range $range\n" if ord $lo > ord $hi;
foreach my $i (ord $lo .. ord $hi) {
$result .= chr $i;
}
return $result;
}
sub build_charset {
my($charset) = @_;
$charset =~ s/.-./expand_range($&)/eg;
my %result = map { $_ => 1 } split //, $charset;
return join '', sort keys %result;
}
sub single_character {
my($charset, $DEVICE) = @_;
$charset =~ s/.-./expand_range($&)/eg;
return substr($charset, random(length($charset), $DEVICE), 1);
}
sub debug {
print @_ if $opt{debugging};
return;
} # debug
sub debugf {
printf @_ if $opt{debugging};
return;
} # debugf
__END__
=head1 NAME
gen-password - Generate random passwords
=head1 SYNOPSIS
gen-password [options]
Options:
-help|-help1|-help2 Show short|medium|long usage message
-man Show long usage message (invokes pager)
Too many options to show here.
Use B<-help1>, B<-help2>, or B<-man> to see more options.
=head1 DESCRIPTION
B<gen-password> generates random passwords.
It is part of the B<random-passwords> package, available at
L<https://github.com/Keith-S-Thompson/random-passwords>
More documentation is available there.
By default, a 12-character password is generated, consisting of
lowercase letters and decimal digits. Options let you control the
length and valid characters, and to add specified single characters
(for example if you need a 16-character password with 1 digit,
1 uppercase letter, and 1 punctuation character).
There is currently no option to use non-ASCII characters.
=head1 OPTIONS
All options may be abbreviated uniquely. B<-help> may be abbreviated as B<-h>.
=over 4
=item B<-help>
Show short usage message
=item B<-help1>
Show medium usage message
=item B<-help2>
Show long usage message
=item B<-man>
Show long usage message using B<perldoc>, invokes pager
=item B<-n>
Don't print a newline after the password
=item B<-length N>
Length of generated password, default is 12
=item B<-charset ...>
Character set, default is "a-z0-9"
The argument is a single word.
=item B<-decimal>, B<-digits>
Equivalent to B<-charset 0-9>
=item B<-hexadecimal>
Equivalent to B<-charset 0-9a-f>
=item B<-Hexadecimal>
Equivalent to B<-charset 0-9A-F>
=item B<-octal>
Equivalent to B<-charset 0-7>
=item B<-lower>
Equivalent to B<-charset a-z>
=item B<-upper>
Equivalent to B<-charset A-Z>
=item B<-alphanumeric>
Equivalent to B<-charset A-Za-z0-9>
=item B<-printable>
Equivalent to "-charset !-~" (ASCII non-blank printable characters)
=item B<-1lower>
Include (at least) 1 lower case letter
=item B<-1upper>
Include (at least) 1 upper case letter
=item B<-1decimal> B<-1digit>
Include (at least) 1 decimal digit
=item B<-1punctuation>
Include (at least) 1 punctuation character
=item B<-1charset ...>
Include (at least) 1 character from the specified set
This option may be given multiple times.
(The other B<-1...> options may only be given once.)
Use B<-1charset 0-9 -1charset 0-9> for 2 decimal digits.
NOTE: A literal hyphen B<-> character should be specified first or
last; otherwise it specifies a range.
=item B<-split N>
Split with a blank every N characters
=item B<-dev-random>
Use /dev/random rather than /dev/urandom
This can be much slower and is probably unnecessary.
=item B<-debugging>
Produce debugging output (developer option)
=back
=head1 SEE ALSO
B<gen-password>, also part of the B<random-passwords> package.
L<https://github.com/Keith-S-Thompson/random-passwords>.
=head1 AUTHOR
Keith Thompson <Keith.S.Thompson@gmail.com>
=head1 LICENSE AND COPYRIGHT
B<random-password> is released under GPL version 2 or later.
=cut