Debian Codegraph @

README

raw
1 NAME
2 Session::Token - Secure, efficient, simple random session token
3 generation
4
5 SYNOPSIS
6 Simple 128-bit session token
7 my $token = Session::Token->new->get;
8 ## 74da9DABOqgoipxqQDdygw
9
10 Keep generator around
11 my $generator = Session::Token->new;
12
13 my $token = $generator->get;
14 ## bu4EXqWt5nEeDjTAZcbTKY
15
16 my $token2 = $generator->get;
17 ## 4Vez56Zc7el5Ggx4PoXCNL
18
19 Custom minimum entropy in bits
20 my $token = Session::Token->new(entropy => 256)->get;
21 ## WdLiluxxZVkPUHsoqnfcQ1YpARuj9Z7or3COA4HNNAv
22
23 Custom alphabet and length
24 my $token = Session::Token->new(alphabet => 'ACGT', length => 100_000_000)->get;
25 ## AGTACTTAGCAATCAGCTGGTTCATGGTTGCCCCCATAG...
26
27 DESCRIPTION
28 This module provides a secure, efficient, and simple interface for
29 creating session tokens, password reset codes, temporary passwords,
30 random identifiers, and anything else you can think of.
31
32 When a Session::Token object is created, 1024 bytes are read from
33 "/dev/urandom" (Linux, Solaris, most BSDs), "/dev/arandom" (some older
34 BSDs), or Crypt::Random::Source::Strong::Win32 (Windows). These bytes
35 are used to seed the ISAAC-32
36 <http://www.burtleburtle.net/bob/rand/isaacafa.html> pseudo random
37 number generator.
38
39 Once a generator is created, you can repeatedly call the "get" method on
40 the generator object and it will return a new token each time.
41
42 IMPORTANT: If your application calls "fork", make sure that any
43 generators are re-created in one of the processes after the fork since
44 forking will duplicate the generator state and both parent and child
45 processes will go on to produce identical tokens (just like perl's rand
46 after it is seeded).
47
48 After the generator context is created, no system calls are used to
49 generate tokens. This is one way that Session::Token helps with
50 efficiency. However, this is only important for certain use cases
51 (generally not web sessions).
52
53 ISAAC is a cryptographically secure PRNG that improves on the well-known
54 RC4 algorithm in some important areas. For instance, it doesn't have
55 short cycles or initial bias like RC4 does. A theoretical shortest
56 possible cycle in ISAAC is "2**40", although no cycles this short have
57 ever been found (and probably don't exist at all). On average, ISAAC
58 cycles are "2**8295".
59
60 GENERATORS AND URANDOM
61 Developers must choose whether a single token generator will be kept
62 around and used to generate all tokens, or if a new Session::Token
63 object will be created every time a token is needed. As mentioned above,
64 this module accesses urandom in its constructor for seeding purposes,
65 but not subsequently while generating tokens.
66
67 Generally speaking the generator should be kept around and re-used.
68 Probably the most important reason for this is that generating a new
69 token from an existing generator cannot fail due to a full
70 file-descriptor table. Creating a new Session::Token object for every
71 token can fail because, as described above, the constructor needs to
72 open "/dev/urandom" and this will not succeed if all allotted
73 descriptors are in use, or if the read is interrupted by a signal. In
74 these events a perl exception will be thrown.
75
76 Programs that re-use a generator are more likely to be portable to
77 "chroot"ed environments where "/dev/urandom" may not be present.
78 Finally, accessing urandom frequently is inefficient because it requires
79 making system calls and because (at least on linux) reading from urandom
80 acquires a system-wide kernel lock.
81
82 On the other hand, re-using a generator may be undesirable because
83 servers are typically started immediately after a system reboot and the
84 kernel's randomness pool might be poorly seeded at that point.
85 Similarly, when starting a virtual machine a previously used entropy
86 pool state may be restored. In these cases all subsequently generated
87 tokens will be derived from a weak/predictable seed. For this reason,
88 you might choose to defer creating the generator until the first request
89 actually comes in, periodically re-create the generator object, and/or
90 manually handle seeding in some other way.
91
92 Programs that assume opening "/dev/urandom" will always succeed can
93 return session tokens based only on the contents of nulled or
94 uninitialised memory. This is not the case with Session::Token since its
95 constructor will always throw an exception if it can't seed itself. Some
96 modern systems provide system calls with fewer failure modes (ie
97 `getentropy(2)` on OpenBSD and `getrandom(2)` on linux). Future versions
98 of Session::Token will likely use these system calls when available.
99
100 CUSTOM ALPHABETS
101 Being able to choose exactly which characters appear in your token is
102 sometimes useful. This set of characters is called the *alphabet*. The
103 default alphabet size is 62 characters: uppercase letters, lowercase
104 letters, and digits ("a-zA-Z0-9").
105
106 For some purposes, base-62 is a sweet spot. It is more compact than
107 hexadecimal encoding which helps with efficiency because session tokens
108 are usually transferred over the network many times during a session
109 (often uncompressed in HTTP headers).
110
111 Also, base-62 tokens don't use "wacky" characters like base-64 encodings
112 do. These characters sometimes cause encoding/escaping problems (ie when
113 embedded in URLs) and are annoying because often you can't select tokens
114 by double-clicking on them.
115
116 Although the default is base-62, there are all kinds of reasons for
117 using another alphabet. One example is if your users are reading tokens
118 from a print-out or SMS or whatever, you may choose to omit characters
119 like "o", "O", and 0 that can easily be confused.
120
121 To set a custom alphabet, just pass in either a string or an array of
122 characters to the "alphabet" parameter of the constructor:
123
124 Session::Token->new(alphabet => '01')->get;
125 Session::Token->new(alphabet => ['0', '1'])->get; # same thing
126 Session::Token->new(alphabet => ['a'..'z'])->get; # character range
127
128 Constructor args can be a hash-ref too:
129
130 Session::Token->new({ alphabet => ['a'..'z'] })->get;
131
132 ENTROPY
133 There are two ways to specify the length of tokens. The most primitive
134 is in terms of characters:
135
136 print Session::Token->new(length => 5)->get;
137 ## -> wpLH4
138
139 But the primary way is to specify their minimum entropy in terms of
140 bits:
141
142 print Session::Token->new(entropy => 24)->get;
143 ## -> Fo5SX
144
145 In the above example, the resulting token contains at least 24 bits of
146 entropy. Given the default base-62 alphabet, we can compute the exact
147 entropy of a 5 character token as follows:
148
149 $ perl -E 'say 5 * log(62)/log(2)'
150 29.7709815519344
151
152 So these tokens have about 29.8 bits of entropy. Note that if we removed
153 one character from this token, it would bring it below our desired 24
154 bits of entropy:
155
156 $ perl -E 'say 4 * log(62)/log(2)'
157 23.8167852415475
158
159 The default minimum entropy is 128 bits. Default tokens are 22
160 characters long and therefore have about 131 bits of entropy:
161
162 $ perl -E 'say 22 * log(62)/log(2)'
163 130.992318828511
164
165 An interesting observation is that in base-64 representation, 128-bit
166 minimum tokens also require 22 characters and that these tokens contain
167 only 1 more bit of entropy.
168
169 Another Session::Token design criterion is that all tokens should be the
170 same length. The default token length is 22 characters and the tokens
171 are always exactly 22 characters (no more, no less). Instead of tokens
172 that are exactly "N" characters, some libraries that use arbitrary
173 precision arithmetic end up creating tokens of *at most* "N" characters.
174
175 A fixed token length is nice because it makes writing matching regular
176 expressions easier, simplifies storage (you never have to store length),
177 causes various log files and things to line up neatly on your screen,
178 and ensures that encrypted tokens won't leak token entropy due to length
179 (see "VARIABLE LENGTH TOKENS").
180
181 In summary, the default token length of exactly 22 characters is a
182 consequence of these decisions: base-62 representation, 128 bit minimum
183 token entropy, and fixed token length.
184
185 MOD BIAS
186 Some token generation libraries that implement custom alphabets will
187 generate a random value, compute its modulus over the size of an
188 alphabet, and then use this modulus to index into the alphabet to
189 determine an output character.
190
191 Assume we have a uniform random number source that generates values in
192 the set "[0,1,2,3]" (most PRNGs provide sequences of bits, in other
193 words power-of-2 size sets) and wish to use the alphabet "abc".
194
195 If we use the naïve modulus algorithm described above then 0 maps to
196 "a", 1 maps to "b", 2 maps to "c", and 3 *also* maps to "a". This
197 results in the following biased distribution for each character in the
198 token:
199
200 P(a) = 2/4 = 1/2
201 P(b) = 1/4
202 P(c) = 1/4
203
204 Of course in an unbiased distribution, each character would have the
205 same chance:
206
207 P(a) = 1/3
208 P(b) = 1/3
209 P(c) = 1/3
210
211 Bias is undesirable because certain tokens are obvious starting points
212 when token guessing and certain other tokens are very unlikely. Tokens
213 that are unbiased are equally likely and therefore there is no obvious
214 starting point with them.
215
216 Session::Token provides unbiased tokens regardless of the size of your
217 alphabet (though see the "INTRODUCING BIAS" section for a mis-use
218 warning). It does this in the same way that you might simulate producing
219 unbiased random numbers from 1 to 5 given an unbiased 6-sided die:
220 Re-roll every time a 6 comes up.
221
222 In the above example, Session::Token eliminates bias by only using
223 values of 0, 1, and 2 (the "t/no-mod-bias.t" test contains some more
224 notes on this topic).
225
226 Note that mod bias can be made arbitrarily small by increasing the
227 amount of data consumed from a random number generator (provided that
228 arbitrary precision modulus is available). Because this module
229 fundamentally avoids mod bias, it can use each of the 4 bytes from an
230 ISAAC-32 word for a separate character (excepting "re-rolls").
231
232 EFFICIENCY OF RE-ROLLING
233 Throwing away a portion of random data in order to avoid mod bias is
234 slightly inefficient. How many bytes from ISAAC do we expect to consume
235 for every character in the token? It depends on the size of the
236 alphabet.
237
238 Session::Token masks off each byte using the smallest power of two
239 greater than or equal to the alphabet size minus one so the probability
240 that any particular byte can be used is:
241
242 P = alphabet_size / next_power_of_two(alphabet_size)
243
244 For example, with the default base-62 alphabet "P" is "62/64".
245
246 In order to find the average number of bytes consumed for each
247 character, calculate the expected value "E". There is a probability "P"
248 that the first byte will be used and therefore only one byte will be
249 consumed, and a probability "1 - P" that "1 + E" bytes will be consumed:
250
251 E = P*1 + (1 - P)*(1 + E)
252
253 E = P + 1 + E - P - P*E
254
255 0 = 1 - P*E
256
257 P*E = 1
258
259 E = 1/P
260
261 So for the default base-62 alphabet, the average number of bytes
262 consumed for each character in a token is:
263
264 E = 1/(62/64) = 64/62 ≅ 1.0323
265
266 Because of the next power of two masking optimisation described above,
267 "E" will always be less than 2. In the worst case scenario of an
268 alphabet with 129 characters, "E" is roughly 1.9845.
269
270 This minor inefficiency isn't an issue because the ISAAC implementation
271 used is quite fast and this module is very thrifty in how it uses
272 ISAAC's output.
273
274 INTRODUCING BIAS
275 If your alphabet contains the same character two or more times, this
276 character will be more biased than a character that only occurs once.
277 You should be careful that your alphabets don't repeat in this way if
278 you are trying to create random session tokens.
279
280 However, if you wish to introduce bias this library doesn't try to stop
281 you. (Maybe it should print a warning?)
282
283 Session::Token->new(alphabet => '0000001', length => 5000)->get; # don't do this
284 ## -> 0000000000010000000110000000000000000000000100...
285
286 Due to a limitation discussed below, alphabets larger than 256 aren't
287 currently supported so your bias can't get very granular.
288
289 Aside: If you have a constant-biased output stream like the above
290 example produces then you can re-construct an un-biased bit sequence
291 with the von neumann algorithm. This works by comparing pairs of bits.
292 If the pair consists of identical bits, it is discarded. Otherwise the
293 order of the different bits is used to determine an output bit, ie 00
294 and 11 are discarded but 01 and 10 are mapped to output bits of 0 and 1
295 respectively. This only works if the bias in each bit is constant (like
296 all characters in a Session::Token are).
297
298 ALPHABET SIZE LIMITATION
299 Due to a limitation in this module's code, alphabets can't be larger
300 than 256 characters. Everywhere the above manual says "characters" it
301 actually means bytes. This isn't a Unicode limitation per se, just the
302 maximum size of the alphabet. If you like, you can map tokens onto new
303 alphabets as long as they aren't more than 256 characters long. Here is
304 how to generate a 128-bit minimum entropy token using the lowercase
305 greek alphabet (note that both forms of lowercase sigma are included
306 which may not be desirable):
307
308 use utf8;
309 my $token = Session::Token->new(alphabet => [map {chr} 0..25])->get;
310 $token = join '', map {chr} map {ord($_) + ord('α')} split //, $token;
311 # ρφνδαπξδββφδοςλχτμγσψδψζειετ
312
313 Here's an interesting way to generate a uniform random integer between 0
314 to 999 inclusive:
315
316 0 + Session::Token->new(alphabet => ['0'..'9'], length => 3)->get
317
318 If you wanted to natively support high code points, there is no point in
319 hard-coding a limitation on the size of Unicode or even the (higher)
320 limitation of perl characters. Instead, arbitrary precision "characters"
321 should be supported with bigint. Here's an example of something similar
322 in lisp: isaac.lisp <http://hcsw.org/downloads/isaac.lisp>.
323
324 This module is not however designed to be the ultimate random number
325 generator and at this time I think changing the design as described
326 above would interfere with its goal of being secure, efficient, and
327 simple.
328
329 TOKEN TEMPLATES
330 String::Random has a method called "randpattern" where you provide a
331 pattern that serves as a template when creating the token. You define
332 the meaning of 1 or more template characters and each one that occurs in
333 the pattern is replaced by a random character from a corresponding
334 alphabet.
335
336 Andrew Beverley requested this feature for Session::Token and I
337 suggested approximately the following:
338
339 use Session::Token;
340
341 sub token_template {
342 my (%m) = @_;
343
344 %m = map { $_ => Session::Token->new(alphabet => $m{$_}, length => 1) } keys %m;
345
346 return sub {
347 my $v = shift;
348 $v =~ s/(.)/exists $m{$1} ? $m{$1}->get : $1/eg;
349 return $v;
350 };
351 }
352
353 In order to use "token_template" you should pass it key-vaue pairs of
354 the different token characters and the alphabets they represent. It will
355 return a sub that should be passed the template pattern and it will
356 return the resulting random tokens.
357
358 For example, here is how to create UUID version 4
359 <https://en.wikipedia.org/wiki/Universally_unique_identifier#Version_4_.
360 28random.29> tokens:
361
362 sub uuid_v4_generator {
363 my $t = token_template(
364 x => [ 0..9, 'a'..'f' ],
365 y => [ 8, 9, 'a', 'b' ],
366 );
367
368 return sub {
369 return $t->('xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx');
370 }
371 }
372
373 "uuid_v4_generator" returns a generator function that will return tokens
374 of the following form:
375
376 1b782499-9913-4726-a80a-25e7b2221a7c
377 90f85a64-d826-43bf-98e7-94ba87406bfb
378 b8b73175-3cce-4861-b43b-3dec5ed5d641
379 3afb64ab-6de3-4647-bbff-eb94dfa7d4b0
380 447d2001-2aec-4d32-9910-8c289ae34c48
381
382 Note that characters in the pattern which don't have template characters
383 defined ("-" and 4 in the above example) are passed through to the
384 output token.
385
386 SEEDING
387 This module is designed to always seed itself from your kernel's secure
388 random number source. You should never need to seed it yourself.
389
390 However if you know what you're doing you can pass in a custom seed as a
391 1024 byte long string. For example, here is how to create a "null
392 seeded" generator:
393
394 my $gen = Session::Token(seed => "\x00" x 1024);
395
396 This is done in the test-suite to compare against Jenkins' reference
397 ISAAC output, but obviously don't do this in regular applications
398 because the generated tokens will be the same every time your program is
399 run.
400
401 One valid reason for manually seeding is if you have some reason to
402 believe that there isn't enough entropy in your kernel's randomness pool
403 and therefore you don't trust "/dev/urandom". In this case you should
404 acquire your own seed data from somewhere trustworthy (maybe
405 "/dev/random" or a previously stored trusted seed).
406
407 VARIABLE LENGTH TOKENS
408 As mentioned above, all tokens produced by a Session::Token generator
409 are the same length. If you prefer tokens of variable length, it is
410 possible to post-process the tokens in order to achieve this so long as
411 you keep some things in mind.
412
413 If you randomly truncate tokens created by Session::Token, be careful
414 not to introduce bias. For example, if you choose the length of the
415 token as a uniformly distributed random length between 8 and 10, then
416 the output will be biased towards shorter token sizes. Length 8 tokens
417 should appear less frequently than length 9 or 10 tokens because there
418 are fewer of them.
419
420 Another approach is to eliminate leading characters of a given value in
421 the same way as leading 0s are commonly eliminated from numeric
422 representations. Although this approach doesn't introduce bias, the
423 tokens 1 and 01 are not distinct so it does not increase token entropy
424 given a fixed maximum token length which is the main reason for
425 preferring variable length tokens. The ideal variable length algorithm
426 would generate both 1 and 01 tokens (with identical frequency of
427 course).
428
429 Implementing unbiased, variable-length tokens would complicate the
430 Session::Token implementation especially since you should still be able
431 to specify minimum entropy variable-length tokens. Minimum entropy is
432 the primary input to Session::Token, not token length. This is the
433 reason that the default token length of 22 isn't hard-coded anywhere in
434 the Session::Token source code (but 128 is).
435
436 The final reason that Session::Token discourages variable length tokens
437 is that they can leak token information through a side-channel. This
438 could occur when a message is encrypted but the length of the original
439 message can be inferred from the encrypted ciphertext.
440
441 BUGS
442 Should check for biased alphabets and print warnings.
443
444 Would be cool if it could detect forks and warn or re-seed in the child
445 process (without incurring "getpid" overhead).
446
447 There is currently no way to extract the seed from a Session::Token
448 object. Note when implementing this: The saved seed must either store
449 the current state of the ISAAC round as well as the 1024 byte "randsl"
450 array or else do some kind of minimum fast forwarding in order to
451 protect against a partially duplicated output-stream bug.
452
453 Doesn't work on perl 5.6 and below due to the use of ":raw" (thanks CPAN
454 testers). It could probably use "binmode" instead, but meh.
455
456 On windows we use Crypt::Random::Source::Strong::Win32 which has a big
457 dependency tree. We should instead use a slimmer module like
458 Crypt::Random::Seed.
459
460 COMMAND-LINE APP
461 There is a command-line application called App::Session::Token which is
462 a convenience wrapper around Session::Token. You can generate session
463 tokens by running the "session-token" binary:
464
465 $ echo "Your password is `session-token`"
466 Your password is 8Yom6z4AeB1RXxCGzklJFt
467
468 It supports all the options of this module via command line parameters,
469 and multiple session tokens can be generated with the "--num" (aka "-n")
470 switch. For example:
471
472 $ session-token --alphabet ABC --entropy 32 --num 5
473 BACAACABCCCCAACBBBCAB
474 BCBACACBBCACCBABABCBA
475 ABBBCBABBACBBBCBBBCCA
476 AACCBBBCCAAACBABACABC
477 CCABCABBCCCAACAAACCAA
478
479 SEE ALSO
480 The Session::Token github repo
481 <https://github.com/hoytech/Session-Token>
482
483 App::Session::Token
484
485 Presentation for Toronto Perl Mongers
486 <https://www.youtube.com/watch?v=c2KZBTtrmZE?start=3705>
487
488 There are lots of different modules for generating random data. If the
489 characterisations of any of them below are inaccurate or out-of-date,
490 please file a github issue and I will correct them.
491
492 Like this module, perl's "rand()" function implements a user-space PRNG
493 seeded from "/dev/urandom". However, perl's "rand()" is not secure. Perl
494 doesn't specify a PRNG algorithm at all. On linux, whatever it is is
495 seeded with a mere 4 bytes from "/dev/urandom".
496
497 Data::Token is the first thing I saw when I looked around on CPAN. It
498 has an inflexible and unspecified alphabet. It tries to get its source
499 of unpredictability from UUIDs and then hashes these UUIDs with SHA-1. I
500 think this is bad design because some standard UUID formats aren't
501 designed to be unpredictable at all. This is acknowledged in RFC 4122
502 section 6: "Do not assume that UUIDs are hard to guess; they should not
503 be used as security capabilities (identifiers whose mere possession
504 grants access)." With certain UUIDs, knowing a target's MAC address or
505 the rough time the token was issued may help you predict a reduced area
506 of token-space to concentrate guessing attacks upon. I don't know if
507 Data::Token uses these types of UUIDs or the potentially secure "version
508 4" UUIDs, but because this wasn't addressed in the documentation and
509 because of an apparent misapplication of hash functions (if you really
510 had an unpredictable UUID, there would be no need to hash), I don't feel
511 good about using this module.
512
513 There are several decent random number generators like
514 Math::Random::Secure and Crypt::URandom but they usually don't implement
515 alphabets and some of them require you open or read from "/dev/urandom"
516 for every chunk of random bytes. Note that Math::Random::Secure does
517 prevent mod bias in its random integers and could be used to implement
518 unbiased alphabets (slowly).
519
520 String::Random has a neat regexp-like language for specifying random
521 tokens which is more flexible than alphabets. However, it uses perl's
522 "rand()" and its documentation fails to discuss performance, bias, or
523 security. See the "TOKEN TEMPLATES" section for a similar feature.
524
525 String::Urandom has alphabets, but it uses the flawed mod algorithm
526 described above and opens "/dev/urandom" for every token.
527
528 There are other modules like Data::Random, App::Genpass,
529 String::MkPasswd, Crypt::RandPasswd, Crypt::GeneratePassword, and
530 Data::SimplePassword but they use insecure PRNGs such as "rand()" or
531 mersenne twister, don't adequately deal with bias, and/or don't let you
532 specify generic alphabets.
533
534 Bytes::Random::Secure has alphabets (aka "bags"), uses ISAAC, and avoids
535 mod bias using the re-roll algorithm. It is much slower than
536 Session::Token (even when using Math::Random::ISAAC::XS) but does
537 support alphabets larger than 256 and might work in environments without
538 XS.
539
540 Neil Bowers has conducted a 3rd party review
541 <http://neilb.org/reviews/passwords.html> of various token/password
542 generation modules including Session::Token.
543
544 Leo Zovic has created a Common Lisp implementation of session-token
545 <https://github.com/Inaimathi/session-token>.
546
547 AUTHOR
548 Doug Hoyte, "<[email protected]>"
549
550 COPYRIGHT & LICENSE
551 Copyright 2012-2016 Doug Hoyte.
552
553 This module is licensed under the same terms as perl itself.
554
555 ISAAC code:
556
557 By Bob Jenkins. My random number generator, ISAAC. Public Domain
558