File Coverage

File:blib/lib/Database/BI/Password.pm
Coverage:98.1%

linestmtbrancondsubtimecode
1package Database::BI::Password;
2
3
129
129
129
318394
98
799
use strict;
4
129
129
129
153
82
2823
use warnings;
5
6our $VERSION = '0.025.0';
7
8
129
129
129
160
71
1612
use Carp qw(croak);
9
129
129
129
148
76
1543
use Digest::SHA qw(hmac_sha256 sha256);
10
129
129
129
137
100
937
use Exporter qw(import);
11
129
129
129
168
109
1857
use MIME::Base64 qw(encode_base64 decode_base64);
12
129
129
129
522
91
521
use Database::BI::I18N ();
13
129
129
129
142
75
40829
use Readonly;
14
15our @EXPORT_OK = qw( hash_password verify_password is_password_hash );
16
17# PBKDF2-HMAC-SHA256 (RFC 8018), written out because no password-hashing
18# module is a prerequisite and Digest::SHA is core.  The work is in
19# hmac_sha256, which is XS: 200_000 rounds take about 0.4s here, which a reader
20# logging in does not notice and a guesser with a copy of the hash does.  The
21# rounds are stored in the hash, so a later default does not lock anyone out.
22Readonly my $DEFAULT_ROUNDS => 200_000;
23Readonly my $MIN_ROUNDS     => 10_000;
24Readonly my $MAX_ROUNDS     => 100_000_000;
25Readonly my $SALT_BYTES     => 16;
26Readonly my $KEY_BYTES      => 32;
27Readonly my $SCHEME         => 'pbkdf2-sha256';
28Readonly my $HASH_RE        => qr{\A\Q$SCHEME\E\$(\d{5,9})\$([A-Za-z0-9+/]{22})\$([A-Za-z0-9+/]{43})\z};
29
30# What hash_password croaks with, for whoever calls it (the password command, a
31# test), in the language Database::BI::I18N chooses from the locale.
32Readonly our %MESSAGES => (
33        error_password_required => 'hash_password: a password is required',
34        error_password_rounds   => 'hash_password: rounds must be a whole number from %d to %d',
35        error_password_salt     => 'hash_password: a salt is %d bytes',
36        error_password_nul      => 'hash_password: a password may not end in a NUL byte',
37        error_password_random   => 'hash_password: Crypt::URandom gave %d random bytes, not %d',
38);
39
40Readonly my $HMAC_BLOCK_BYTES => 64; # SHA-256's block size, RFC 2104
41
42# _text($key) -> the template for $key in the current language.
43
87
159
sub _text { return Database::BI::I18N::text(__PACKAGE__, \%MESSAGES, $_[0]) }
44
45# _pbkdf2($password, $salt, $rounds, $bytes) -> $key
46#
47# One block is all a 32-byte key needs, but the loop over blocks is kept so
48# the function is the RFC's and its test vectors apply.
49sub _pbkdf2 {
50
311
3684
        my ($password, $salt, $rounds, $bytes) = @_;
51        # Premise 1: HMAC (RFC 2104) replaces a key longer than the block (64 bytes)
52        # with its hash, so HMAC(K) = HMAC(H(K)).  Premise 2: the loop below calls
53        # HMAC with the same key every round.  Conclusion: hashing a long key once
54        # gives the same output and costs one hash, not one per round (a megabyte
55        # password was 10,000 megabytes of hashing).
56
311
616
        $password = sha256($password) if length($password) > $HMAC_BLOCK_BYTES;
57
311
8537
        my $key = '';
58        # TODO: the loop should be removed and just the contents of its body kept
59        # (Path analysis: every caller passes $KEY_BYTES = 32, one SHA-256 block, so the
60        # body runs exactly once.  It is kept on purpose for the RFC 7914 multi-block
61        # vectors t/function.t and t/path.t run through this private function.)
62
311
419
        for (my $block = 1; length($key) < $bytes; $block++) {
63
315
1409
                my $u = hmac_sha256($salt . pack('N', $block), $password);
64
315
205
                my $t = $u;
65
315
521
                for (2 .. $rounds) {
66
4711988
6785515
                        $u = hmac_sha256($u, $password);
67
4711988
1622631
                        $t ^= $u;
68                }
69
315
550
                $key .= $t;
70        }
71
311
729
        return substr($key, 0, $bytes);
72}
73
74# _random_bytes($n) -> $bytes
75#
76# Crypt::URandom is a prerequisite (Windows has no /dev/urandom, which this
77# once fell back to), and it croaks itself when the system has no source.
78sub _random_bytes {
79
34
52
        my ($n) = @_;
80
34
1247
        require Crypt::URandom;
81
34
8494
        my $bytes = Crypt::URandom::urandom($n);
82
34
407
        croak sprintf(_text('error_password_random'), length($bytes // ''), $n)
83                unless defined $bytes && length($bytes) == $n;
84
30
46
        return $bytes;
85}
86
87sub _b64 {
88
183
8195
        (my $s = encode_base64($_[0], '')) =~ s/=+\z//;
89
183
246
        return $s;
90}
91
92sub _unb64 {
93
519
7242
        my ($s) = @_;
94
519
541
        $s .= '=' x ((4 - length($s) % 4) % 4);
95
519
726
        return decode_base64($s);
96}
97
98sub _octets {
99
311
2332
        my ($password) = @_;
100
311
371
        utf8::encode($password) if utf8::is_utf8($password);
101
311
372
        return $password;
102}
103
104sub hash_password {
105
158
235742
        my ($password, %opts) = @_;
106
158
559
        croak _text('error_password_required') unless defined $password && !ref($password) && length $password;
107        # HMAC pads a short key with NUL bytes, so "x" and "x\0" would be one password.
108
142
166
        croak _text('error_password_nul') if $password =~ /\0\z/;
109
136
161
        my $rounds = $opts{rounds} // $DEFAULT_ROUNDS;
110
136
329
        croak sprintf(_text('error_password_rounds'), $MIN_ROUNDS, $MAX_ROUNDS)
111                unless $rounds =~ /\A[0-9]+\z/ && $rounds >= $MIN_ROUNDS && $rounds <= $MAX_ROUNDS;
112
97
423
        my $salt = $opts{salt} // _random_bytes($SALT_BYTES);
113        # A salt is bytes: a reference or a character past U+00FF is not one.
114
93
259
        croak sprintf(_text('error_password_salt'), $SALT_BYTES)
115                unless !ref($salt) && $salt !~ /[^\x00-\xff]/ && length($salt) == $SALT_BYTES;
116
71
168
        my $key = _pbkdf2(_octets($password), $salt, $rounds, $KEY_BYTES);
117
71
124
        return join '$', $SCHEME, $rounds, _b64($salt), _b64($key);
118}
119
120sub is_password_hash {
121
368
8520
        my ($hash) = @_;
122
368
887
        return 0 unless defined $hash && !ref $hash && $hash =~ $HASH_RE;
123
298
1222
        return $1 >= $MIN_ROUNDS && $1 <= $MAX_ROUNDS ? 1 : 0;
124}
125
126sub verify_password {
127
292
3024398
        my ($password, $hash) = @_;
128
292
1072
        return 0 unless defined $password && !ref($password) && length $password && $password !~ /\0\z/ && is_password_hash($hash);
129
238
1073
        my ($rounds, $salt, $want) = $hash =~ $HASH_RE;
130
238
768
        my $got = _pbkdf2(_octets($password), _unb64($salt), $rounds, $KEY_BYTES);
131
238
272
        $want = _unb64($want);
132
133        # Every byte is compared, so the time taken says nothing about how much
134        # of a guess was right.
135
238
233
        my $diff = length($got) ^ length($want);
136
238
1204
        $diff |= ord(substr($got, $_, 1)) ^ ord(substr($want, $_, 1)) for 0 .. length($want) - 1;
137
238
647
        return $diff == 0 ? 1 : 0;
138}
139
1401;
141