File: GeneratePassword.pm

package info (click to toggle)
libcrypt-generatepassword-perl 0.03-4
  • links: PTS, VCS
  • area: main
  • in suites: squeeze, wheezy
  • size: 2,040 kB
  • ctags: 13
  • sloc: perl: 225; makefile: 15
file content (446 lines) | stat: -rw-r--r-- 12,754 bytes parent folder | download
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
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
package Crypt::GeneratePassword;
use strict;

=head1 NAME

Crypt::GeneratePassword - generate secure random pronounceable passwords

=head1 SYNOPSIS

  use Crypt::GeneratePassword qw(word chars);
  $word = word($minlen,$maxlen);
  $word = chars($minlen,$maxlen);
  *Crypt::GeneratePassword::restrict = \&my_restriction_filter;
  *Crypt::GeneratePassword::random_number = \&my_random_number_generator;

=head1 DESCRIPTION

Crypt::GeneratePassword generates random passwords that are
(more or less) pronounceable. Unlike Crypt::RandPasswd, it
doesn't use the FIPS-181 NIST standard, which is proven to be
insecure. It does use a similar interface, so it should be a
drop-in replacement in most cases.

If you want to use passwords from a different language than english,
you can use one of the packaged alternate unit tables or generate
your own. See below for details.

For details on why FIPS-181 is insecure and why the solution
used in this module is reasonably secure, see "A New Attack on
Random Pronounceable Password Generators" by Ravi Ganesan and
Chris Davies, available online in may places - use your
favourite search engine.

This module improves on FIPS-181 using a true random selection with
the word generator as mere filter. Other improvements are
better pronounceability using third order approximation instead
of second order and multi-language support.
Drawback of this method is that it is usually slower. Then again,
computer speed has improved a little since 1977.

=head1 Functions

=cut

require Exporter;
@Crypt::GeneratePassword::ISA = ('Exporter');
@Crypt::GeneratePassword::EXPORT_OK = qw(word word3 analyze analyze3 chars generate_language load_language);
%Crypt::GeneratePassword::EXPORT_TAGS = ( 'all' => [ @Crypt::GeneratePassword::EXPORT_OK ] );

my $default_language = 'en';
use vars qw(%languages);
%languages = ();

=head2 chars

  $word = chars($minlen, $maxlen [, $set [, $characters, $maxcount ] ... ] );

Generatess a completely random word between $minlen and $maxlen in length.
If $set is given, it must be an array ref of characters to use. You can
restrict occurrence of some characters by providing ($characters, $maxcount)
pairs, as many as you like. $characters must be a string consisting of those
characters which may appear at most $maxcount times in the word.

Note that the length is determined via relative probability, not uniformly.

=cut

my @signs = ('0'..'9', '%', '$', '_', '-', '+', '*', '&', '/', '=', '!', '#');
my $signs = join('',@signs);
my @caps = ('A' .. 'Z');
my $caps = join('',@caps);

my @set = (
	   [ ["\x00",'a'..'z'], ["\x00",'a'..'z',@caps] ],
	   [ ["\x00",'a'..'z',@signs], ["\x00",'a'..'z',@caps,@signs] ]
	  );

sub chars($$;$@) {
  my ($minlen, $maxlen, $set, @restrict) = @_;
  $set ||= $set[1][1];
  my $res;
  my $diff = $maxlen-$minlen;
  WORD: {
    $res = join '', map { $$set[random_number(scalar(@$set))] } 1..$maxlen;
    $res =~ s/\x00{0,$diff}$//;
    redo if $res =~ m/\x00/;
    for (my $i = 0; $i < @restrict; $i+=2) {
      my $match = $restrict[$i];
      my $more = int($restrict[$i+1])+1;
      redo WORD if $res =~ m/([\Q$match\E].*){$more,}/;
    }
  }
  return $res;
}

=head2 word

  $word = word($minlen, $maxlen [, $lang [, $signs [, $caps [, $minfreq, $avgfreq ] ] ] );
  $word = word3($minlen, $maxlen [, $lang [, $signs [, $caps [, $minfreq, $avgfreq ] ] ] );

Generates a random pronounceable word. The length of the returned
word will be between $minlen and $maxlen. If you supply a non-zero
value for $numbers, up to that many numbers and special characters
will occur in the password. If you specify a non-zero value for $caps,
up to this many characters will be upper case. $lang is the language
description to use, loaded via load_language or built-in. Built-in
languages are: 'en' (english) and 'de' (german). Contributions
welcome. The default language is 'en' but may be changed by calling
load_language with a true value as third parameter. Pass undef as
language to select the current default language. $minfreq and $minsum
determine quality of the password: $minfreq and $avgfreq are the minimum
frequency each quad/trigram must have and the average frequency that the
quad/trigrams must have for a word to be selected. Both are values between 0.0
and 1.0, specifying the percentage of the maximum frequency. Higher
values create less secure, better pronounceable passwords and are slower.
Useful $minfreq values are usually between 0.001 and 0.0001, useful $avgfreq
values are around 0.05 for trigrams (word3) and 0.001 for quadgrams (word).

=cut

use vars qw($total);

sub word($$;$$$$$) {
  my $language = splice(@_,2,1) || '';
  $language =~ s/[^a-zA-Z_]//g;
  $language ||= $default_language;
  eval "require Crypt::GeneratePassword::$language";
  my $lang = $languages{$language};
  die "language '${language}' not found" if !$lang;

  my ($minlen, $maxlen, $numbers, $capitals, $minfreq, $avgfreq) = map { int($_) } @_;
  $minfreq ||= 0;
  $avgfreq ||= 0.001;
  $minfreq = int($$lang{'maxquad'}*$minfreq) || 1;
  $avgfreq = int($$lang{'maxquad'}*$avgfreq);

 WORD: {
    my $randword = chars($minlen,$maxlen,$set[$numbers?1:0][$capitals?1:0],($numbers?($signs,$numbers):()),($capitals?($caps,$capitals):()));
    $total++;
    my $stripped = lc($randword);
    $stripped =~ s/[\Q$signs\E]//g;
    my $sum = 0;
    my $k0 = -1;
    my $k1 = -1;
    my $k2 = -1;
    my $k3 = -1;

    foreach my $char (split(//,$stripped)) {
      $k3 = $char;
      if ($k3 gt 'Z') {
	$k3 = ord($k3) - ord('a');
      } else {
	$k3 = ord($k3) - ord('A');
      }

      if ($k0 > 0) {
	redo WORD if $$lang{'quads'}[$k0][$k1][$k2][$k3] < $minfreq;
	$sum += $$lang{'quads'}[$k0][$k1][$k2][$k3];
      }

      $k0 = $k1;
      $k1 = $k2;
      $k2 = $k3;
    }
    redo if $sum/length($stripped) < $avgfreq;
    redo if (restrict($stripped,$language));
    return $randword;
  }
}

sub word3($$;$$$$$) {
  my $language = splice(@_,2,1) || '';
  $language =~ s/[^a-zA-Z_]//g;
  $language ||= $default_language;
  eval "require Crypt::GeneratePassword::$language";
  my $lang = $languages{$language};
  die "language '${language}' not found" if !$lang;

  my ($minlen, $maxlen, $numbers, $capitals, $minfreq, $avgfreq) = map { int($_) } @_;
  $minfreq ||= 0.01;
  $avgfreq ||= 0.05;
  $minfreq = int($$lang{'maxtri'}*$minfreq) || 1;
  $avgfreq = int($$lang{'maxtri'}*$avgfreq);

 WORD: {
    my $randword = chars($minlen,$maxlen,$set[$numbers?1:0][$capitals?1:0],($numbers?($signs,$numbers):()),($capitals?($caps,$capitals):()));
    $total++;
    my $stripped = lc($randword);
    $stripped =~ s/[\Q$signs\E]//g;
    my $sum = 0;
    my $k1 = -1;
    my $k2 = -1;
    my $k3 = -1;

    foreach my $char (split(//,$stripped)) {
      $k3 = $char;
      if ($k3 gt 'Z') {
	$k3 = ord($k3) - ord('a');
      } else {
	$k3 = ord($k3) - ord('A');
      }

      if ($k1 > 0) {
	redo WORD if $$lang{'tris'}[$k1][$k2][$k3] < $minfreq;
	$sum += $$lang{'tris'}[$k1][$k2][$k3];
      }

      $k1 = $k2;
      $k2 = $k3;
    }
    redo if $sum/length($stripped) < $avgfreq;
    redo if (restrict($stripped,$language));
    return $randword;
  }
}

=head2 analyze

  $ratio = analyze($count,@word_params);
  $ratio = analyze3($count,@word_params);

Returns a statistical(!) security ratio to measure password
quality. $ratio is the ratio of passwords chosen among all
possible ones, e.g. a ratio of 0.0149 means 1.49% of the
theoretical password space was actually considered a
pronounceable password. Since this analysis is only
statistical, it proves absolutely nothing if you are deeply
concerned about security - but in that case you should use
chars(), not word() anyways. In reality, it says a lot
about your chosen parameters if you use large values for
$count.

=cut

sub analyze($@) {
  my $count = shift;
  $total = 0;
  for (1..$count) {
    my $word = &word(@_);
  }
  return $count/$total;
}

sub analyze3($@) {
  my $count = shift;
  $total = 0;
  for (1..$count) {
    my $word = &word3(@_);
  }
  return $count/$total;
}

=head2 generate_language

  $language_description = generate_language($wordlist);

Generates a language description which can be saved in a file and/or
loaded with load_language. $wordlist can be a string containing
whitespace separated words, an array ref containing one word per
element or a file handle or name to read words from, one word per line7.
Alternatively, you may pass an array directly, not as reference.
A language description is about 1MB in size.

If you generate a general-purpose language description for a
language not yet built-in, feel free to contribute it for inclusion
into this package.

=cut

sub generate_language($@) {
  my ($wordlist) = @_;
  if (@_ > 1) {
    $wordlist = \@_;
  } elsif (!ref($wordlist)) {
    $wordlist = [ split(/\s+/,$wordlist) ];
    if (@$wordlist == 1) {
      local *FH;
      open(FH,'<'.$$wordlist[0]);
      $wordlist = [ <FH> ];
      close(FH);
    }
  } elsif (ref($wordlist) ne 'ARRAY') {
    $wordlist = [ <$wordlist> ];
  }

  my @quads = map { [ map { [ map { [ map { 0 } 1..26 ] } 1..26 ] } 1..26 ] } 1..26;
  my @tris = map { [ map { [ map { 0 } 1..26 ] } 1..26 ] } 1..26;
  my $sigmaquad = 0;
  my $maxquad = 0;
  my $sigmatri = 0;
  my $maxtri = 0;

  foreach my $word (@$wordlist) {
    my $k0 = -1;
    my $k1 = -1;
    my $k2 = -1;
    my $k3 = -1;

    foreach my $char (split(//,$word)) {
      $k3 = $char;
      if ($k3 gt 'Z') {
	$k3 = ord($k3) - ord('a');
      } else {
	$k3 = ord($k3) - ord('A');
      }

      next unless ($k3 >= 0 && $k3 <= 25);

      if ($k0 >= 0) {
	$quads[$k0][$k1][$k2][$k3]++;
	$sigmaquad++;
	if ($quads[$k0][$k1][$k2][$k3] > $maxquad) {
	  $maxquad = $quads[$k0][$k1][$k2][$k3];
	}
      }

      if ($k1 >= 0) {
	$tris[$k1][$k2][$k3]++;
	$sigmatri++;
	if ($tris[$k1][$k2][$k3] > $maxtri) {
	  $maxtri = $tris[$k1][$k2][$k3];
	}
      }

      $k0 = $k1;
      $k1 = $k2;
      $k2 = $k3;
    }
  }

  {
    require Data::Dumper;
    local $Data::Dumper::Indent = 0;
    local $Data::Dumper::Purity = 0;
    local $Data::Dumper::Pad = '';
    local $Data::Dumper::Deepcopy = 1;
    local $Data::Dumper::Terse = 1;

    my $res = Data::Dumper::Dumper(
			    {
			     maxtri => $maxtri,
			     sigmatri => $sigmatri,
			     maxquad => $maxquad,
			     sigmaquad => $sigmaquad,
			     tris => \@tris,
			     quads => \@quads,
			    }
			   );
    $res =~ s/[' ]//g;
    return $res;
  }
}

=head2 load_language

  load_language($language_description, $name [, $default]);

Loads a language description which is then available in words().
$language_desription is a string returned by generate_language,
$name is a name of your choice which is used to select this
language as the fifth parameter of words(). You should use the
well-known ISO two letter language codes if possible, for best
interoperability.

If you specify $default with a true value, this language will
be made global default language. If you give undef as
$language_description, only the default language will be changed.

=cut

sub load_language($$;$) {
  my ($desc,$name,$default) = @_;
  $languages{$name} = eval $desc if $desc;
  $default_language = $name if $default;
}

=head2 random_number

  $number = random_number($limit);

Returns a random integer between 0 (inclusive) and $limit (exclusive).
Change this to a function of your choice by doing something like this:

    {
      local $^W; # squelch sub redef warning.
      *Crypt::GeneratePassword::random_number = \&my_rng;
    }

The default implementation uses perl's rand(), which might not be
appropriate for some sites.

=cut

sub random_number($) {
  return int(rand()*$_[0]);
}

=head2 restrict

  $forbidden = restrict($word,$language);

Filters undesirable words. Returns false if the $word is allowed
in language $lang, false otherwise. Change this to a function of
your choice by doing something like this:

    {
      local $^W; # squelch sub redef warning.
      *Crypt::GeneratePassword::restrict = \&my_filter;
    }

The default implementation scans for a few letter sequences that
english or german people might find offending, mostly because of
their sexual nature. You might want to hook up a regular password
checker here, or a wordlist comparison.

=cut

sub restrict($$) {
  return ($_[0] =~ m/f.ck|ass|rsch|tit|cum|ack|asm|orn|eil|otz|oes/i);
}

=head1 VERSION

This document describes version 0.03

=cut

$Crypt::GeneratePassword::VERSION = 0.03;

=head1 AUTHOR

Copyright 2002 by Jrg Walter <jwalt@cpan.org>,
inspired by ideas from Tom Van Vleck and Morris
Gasser/FIPS-181.

=head1 COPYRIGHT

This perl module is free software; it may be redistributed and/or modified
under the same terms as Perl itself.


=head1 SEE ALSO

L<Crypt::RandPasswd>.

=cut