Trog-Vault.t 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. #!/usr/bin/env perl
  2. # The vault, the code that authorizes opening it, and the hashing underneath
  3. # both. Nothing here needs a webserver: what is being tested is that a database
  4. # on its own is not enough, and that a code is worth one thing.
  5. use strict;
  6. use warnings;
  7. use FindBin;
  8. use lib "$FindBin::Bin/../lib";
  9. use Test::More;
  10. use Test::MockModule qw{strict};
  11. our ( $REPO, $ROOT, $OLDCWD );
  12. BEGIN {
  13. require Cwd;
  14. require File::Copy;
  15. require File::Path;
  16. require File::Temp;
  17. $REPO = Cwd::abs_path("$FindBin::Bin/..");
  18. $OLDCWD = Cwd::getcwd();
  19. $ROOT = File::Temp::tempdir( 'tcms-vault-XXXXXX', TMPDIR => 1, CLEANUP => 1 );
  20. $ENV{HOME} = $ROOT;
  21. File::Path::make_path( map { "$ROOT/$_" } qw{config schema logs totp} );
  22. File::Copy::copy( "$REPO/schema/auth.schema", "$ROOT/schema/auth.schema" ) or die $!;
  23. open( my $fh, '>', "$ROOT/config/default.cfg" ) or die $!;
  24. print {$fh} "[general]\n data_model=FlatFile\n hostname=vault.example.com\n";
  25. close $fh;
  26. # The key the way a deployment hands one over: base64, in the environment,
  27. # put there by tpsgi.sh out of a systemd credential. Trog::Vault takes it
  28. # out of %ENV as it loads, which is the behaviour tested below.
  29. require Crypt::PRNG;
  30. require Crypt::Misc;
  31. $ENV{TCMS_VAULT_KEY} = Crypt::Misc::encode_b64( Crypt::PRNG::random_bytes(32) );
  32. chdir($ROOT) or die "could not chdir to the sandbox: $!";
  33. }
  34. END {
  35. chdir($OLDCWD) if $OLDCWD;
  36. }
  37. require_ok('Trog::Auth') or BAIL_OUT("Can't find Trog::Auth");
  38. require_ok('Trog::Vault') or BAIL_OUT("Can't find SUT");
  39. Trog::Auth::useradd( 'bob', 'Bob Bobson', 'hunter2', ['admin'], 'bob@example.com' )
  40. or BAIL_OUT('could not make a user to test with');
  41. Trog::Auth::useradd( 'eve', 'Eve Evilson', 'letmein', ['public'], 'eve@example.com' )
  42. or BAIL_OUT('could not make a second user');
  43. subtest 'the key is taken out of the environment' => sub {
  44. ok( Trog::Vault::has_key(), 'the key was read' );
  45. ok( !exists $ENV{TCMS_VAULT_KEY}, 'and is gone from the environment, so nothing we fork inherits it' );
  46. like( Trog::Vault::key_id(), qr/^[0-9a-f]{16}$/, 'and fingerprints to something a row can name' );
  47. };
  48. subtest 'what a secret looks like on disk' => sub {
  49. my ( $ok, $why ) = Trog::Vault::set( 'bob', 'keepass', 'correct horse battery staple' );
  50. is( $ok, 1, 'a secret can be stored' ) or diag($why);
  51. my $dbh = Trog::SQLite::dbh( 'schema/auth.schema', 'config/auth.db' );
  52. my $rows = $dbh->selectall_arrayref( "SELECT * FROM user_secret WHERE username='bob'", { Slice => {} } );
  53. is( scalar(@$rows), 1, 'and lands in one row' );
  54. my $row = $rows->[0];
  55. unlike( $row->{ciphertext}, qr/correct horse/, 'which does not contain the secret' );
  56. is( length( $row->{salt} ), 32, 'carries a fresh 32 byte salt' );
  57. is( length( $row->{tag} ), 16, 'and a GCM tag' );
  58. is( $row->{key_id}, Trog::Vault::key_id(), 'naming the key it was sealed under' );
  59. is( Trog::Vault::get( 'bob', 'keepass' ), 'correct horse battery staple', 'and it comes back out' );
  60. };
  61. subtest 'a fresh salt every write' => sub {
  62. my $dbh = Trog::SQLite::dbh( 'schema/auth.schema', 'config/auth.db' );
  63. Trog::Vault::set( 'bob', 'same', 'the very same secret' );
  64. my ($first) = $dbh->selectrow_array("SELECT hex(ciphertext) FROM user_secret WHERE username='bob' AND name='same'");
  65. Trog::Vault::set( 'bob', 'same', 'the very same secret' );
  66. my ($second) = $dbh->selectrow_array("SELECT hex(ciphertext) FROM user_secret WHERE username='bob' AND name='same'");
  67. # Same plaintext, same key, different ciphertext -- which is what a random
  68. # salt per write buys, and what GCM needs to stay safe.
  69. isnt( $first, $second, 'the same secret stored twice does not look the same twice' );
  70. is( Trog::Vault::get( 'bob', 'same' ), 'the very same secret', 'and still reads back' );
  71. };
  72. subtest 'a row cannot be moved or renamed' => sub {
  73. my $dbh = Trog::SQLite::dbh( 'schema/auth.schema', 'config/auth.db' );
  74. # Exactly what somebody with write access to the database would try: take
  75. # the admin's sealed passphrase and make it their own.
  76. $dbh->do("INSERT OR REPLACE INTO user_secret (username, name, key_id, salt, ciphertext, tag, created) SELECT 'eve', name, key_id, salt, ciphertext, tag, created FROM user_secret WHERE username='bob' AND name='keepass'");
  77. is( Trog::Vault::get( 'eve', 'keepass' ), undef, 'a row lifted into another account does not open' );
  78. $dbh->do("INSERT OR REPLACE INTO user_secret (username, name, key_id, salt, ciphertext, tag, created) SELECT 'bob', 'renamed', key_id, salt, ciphertext, tag, created FROM user_secret WHERE username='bob' AND name='keepass'");
  79. is( Trog::Vault::get( 'bob', 'renamed' ), undef, 'nor does one renamed into being the answer to a different question' );
  80. is( Trog::Vault::get( 'bob', 'keepass' ), 'correct horse battery staple', 'while the row it was copied from is untouched' );
  81. $dbh->do("DELETE FROM user_secret WHERE name IN ('renamed') OR username='eve'");
  82. };
  83. subtest 'and not without the key it was sealed under' => sub {
  84. my $dbh = Trog::SQLite::dbh( 'schema/auth.schema', 'config/auth.db' );
  85. # A different installation's key, which is what a stolen database meets.
  86. my $theirs = Trog::Vault::key();
  87. {
  88. no warnings qw{once};
  89. local $Trog::Vault::master = Crypt::PRNG::random_bytes(32);
  90. is( Trog::Vault::get( 'bob', 'keepass' ), undef, 'the wrong key opens nothing' );
  91. my $listed = Trog::Vault::list('bob');
  92. my ($keepass) = grep { $_->{name} eq 'keepass' } @$listed;
  93. is( $keepass->{readable}, 0, 'and the listing says so rather than pretending' );
  94. }
  95. is( Trog::Vault::get( 'bob', 'keepass' ), 'correct horse battery staple', 'the right one still does' );
  96. # Tampering, as opposed to the wrong key: the tag is what notices.
  97. $dbh->do("UPDATE user_secret SET ciphertext = ciphertext || X'00' WHERE username='bob' AND name='keepass'");
  98. is( Trog::Vault::get( 'bob', 'keepass' ), undef, 'a row somebody edited does not open either' );
  99. Trog::Vault::set( 'bob', 'keepass', 'correct horse battery staple' );
  100. };
  101. subtest 'the listing never shows a value' => sub {
  102. my $listed = Trog::Vault::list('bob');
  103. ok( scalar(@$listed) >= 2, 'lists what bob has' );
  104. foreach my $secret (@$listed) {
  105. ok( !exists $secret->{ciphertext}, "$secret->{name} is listed without its ciphertext" );
  106. ok( exists $secret->{created}, "$secret->{name} says when it was stored" );
  107. }
  108. is_deeply( Trog::Vault::list('eve'), [], 'and one user cannot see another\'s' );
  109. ok( Trog::Vault::forget( 'bob', 'same' ), 'a secret can be forgotten' );
  110. is( Trog::Vault::get( 'bob', 'same' ), undef, 'after which it is gone' );
  111. is( Trog::Vault::forget( 'bob', 'same' ), 0, 'and forgetting it twice is not a thing that happened' );
  112. };
  113. subtest 'a name is a name' => sub {
  114. foreach my $bad ( '../../etc/passwd', 'has spaces', '', 'a' x 100, '.hidden' ) {
  115. my ( $ok, $why ) = Trog::Vault::set( 'bob', $bad, 'nope' );
  116. is( $ok, 0, "'$bad' is refused as a name" );
  117. }
  118. my ( $ok, $why ) = Trog::Vault::set( 'bob', 'fine', '' );
  119. is( $ok, 0, 'and an empty secret is not a secret' );
  120. };
  121. subtest 'no key, no vault' => sub {
  122. no warnings qw{once};
  123. local $Trog::Vault::master = undef;
  124. local $Trog::Vault::looked_further = 1;
  125. ok( !Trog::Vault::has_key(), 'an installation with no key has no vault' );
  126. my ( $ok, $why ) = Trog::Vault::set( 'bob', 'nowhere', 'to put it' );
  127. is( $ok, 0, 'storing is refused' );
  128. like( $why, qr/no vault key/, 'saying why, since this is a thing to go and configure' );
  129. is( Trog::Vault::get( 'bob', 'keepass' ), undef, 'and nothing already stored is offered' );
  130. };
  131. subtest 'a code is worth one thing' => sub {
  132. my ( $uri, $qr, $failure, $message, $totp ) = Trog::Auth::totp( 'bob', 'vault.example.com' );
  133. ok( $uri, 'bob is enrolled' ) or diag($message);
  134. my $now = time();
  135. my $code = $totp->expected_totp_code($now);
  136. my ( $ok, $why ) = Trog::Auth::spend_totp( 'bob', $code );
  137. is( $ok, 1, 'the code from their authenticator is accepted' ) or diag($why);
  138. ( $ok, $why ) = Trog::Auth::spend_totp( 'bob', $code );
  139. is( $ok, 0, 'and is not accepted a second time' );
  140. like( $why, qr/already been used/, 'saying so, since the answer is to wait thirty seconds' );
  141. # A code from before the one just spent is also spent, whatever the
  142. # arithmetic says: that is what walking the counter forward is for.
  143. my $previous = $totp->expected_totp_code( $now - 30 );
  144. ( $ok, $why ) = Trog::Auth::spend_totp( 'bob', $previous );
  145. is( $ok, 0, 'nor is an older code from inside the tolerance window' );
  146. ( $ok, $why ) = Trog::Auth::spend_totp( 'bob', '000000' );
  147. is( $ok, 0, 'a wrong code is refused' );
  148. ( $ok, $why ) = Trog::Auth::spend_totp( 'bob', 'notacode' );
  149. is( $ok, 0, 'and so is something that is not a code at all' );
  150. ( $ok, $why ) = Trog::Auth::spend_totp( 'eve', $totp->expected_totp_code( $now + 30 ) );
  151. is( $ok, 0, 'somebody who has not enrolled cannot spend anything' );
  152. like( $why, qr/no second factor/, 'and is told that rather than that their code was wrong' );
  153. # The next window is a new code and works, which is the whole cost of this.
  154. ( $ok, $why ) = Trog::Auth::spend_totp( 'bob', $totp->expected_totp_code( $now + 30 ) );
  155. is( $ok, 1, 'the next code works' ) or diag($why);
  156. };
  157. subtest 'passwords are argon2id, and become it' => sub {
  158. my $dbh = Trog::SQLite::dbh( 'schema/auth.schema', 'config/auth.db' );
  159. my ($hash) = $dbh->selectrow_array("SELECT hash FROM user WHERE name='bob'");
  160. like( $hash, qr/^\$argon2id\$/, 'a user made today is stored as argon2id' );
  161. ok( Trog::Auth::check_password( 'bob', 'hunter2' ), 'and their password checks out' );
  162. ok( !Trog::Auth::check_password( 'bob', 'hunter3' ), 'while a wrong one does not' );
  163. ok( !Trog::Auth::check_password( 'bob', '' ), 'and neither does nothing at all' );
  164. # A row as it was before this change: one unstretched sha256 of the password
  165. # and the salt beside it.
  166. require Digest::SHA;
  167. $dbh->do( "UPDATE user SET hash=?, salt=? WHERE name=?", undef, Digest::SHA::sha256( 'letmein' . 'oldsalt' ), 'oldsalt', 'eve' );
  168. my ($legacy) = $dbh->selectrow_array("SELECT hash FROM user WHERE name='eve'");
  169. unlike( $legacy, qr/^\$argon2/, 'a row from before this reads as the old kind' );
  170. ok( !Trog::Auth::check_password( 'eve', 'wrong' ), 'which still refuses a wrong password' );
  171. ($legacy) = $dbh->selectrow_array("SELECT hash FROM user WHERE name='eve'");
  172. unlike( $legacy, qr/^\$argon2/, 'and is left alone when it does' );
  173. ok( Trog::Auth::check_password( 'eve', 'letmein' ), 'and accepts the right one' );
  174. my ($upgraded) = $dbh->selectrow_array("SELECT hash FROM user WHERE name='eve'");
  175. like( $upgraded, qr/^\$argon2id\$/, 'rewriting it as argon2id on the way past' );
  176. ok( Trog::Auth::check_password( 'eve', 'letmein' ), 'after which the same password still works' );
  177. # Raising the cost later is a one line change, not a migration, for the same
  178. # reason: the next correct password rewrites the row.
  179. {
  180. no warnings qw{once};
  181. local $Trog::Auth::argon2_time = $Trog::Auth::argon2_time + 1;
  182. ok( Trog::Auth::check_password( 'eve', 'letmein' ), 'a hash made under weaker parameters still verifies' );
  183. my ($rehashed) = $dbh->selectrow_array("SELECT hash FROM user WHERE name='eve'");
  184. isnt( $rehashed, $upgraded, 'and is rewritten under the stronger ones' );
  185. }
  186. };
  187. subtest 'logging in spends a code' => sub {
  188. my ( $uri, $qr, $failure, $message, $totp ) = Trog::Auth::totp( 'bob', 'vault.example.com' );
  189. # The subtest above spent the code for the window we are standing in, and
  190. # the counter only walks forwards. Standing here for thirty seconds would
  191. # say the same thing and cost thirty seconds.
  192. my $dbh = Trog::SQLite::dbh( 'schema/auth.schema', 'config/auth.db' );
  193. $dbh->do("DELETE FROM totp_spent WHERE username='bob'");
  194. my $now = time();
  195. my $code = $totp->expected_totp_code($now);
  196. is( Trog::Auth::mksession( 'bob', 'hunter2', '' ), '', 'an enrolled user cannot log in without a code' );
  197. is( Trog::Auth::mksession( 'bob', 'wrong', $code ), '', 'nor with a wrong password' );
  198. # And a login that failed on the password did not spend the code on the way
  199. # past, or a wrong guess would cost the person their next thirty seconds.
  200. ok( Trog::Auth::mksession( 'bob', 'hunter2', $code ), 'the right password and a live code get a session' );
  201. is( Trog::Auth::mksession( 'bob', 'hunter2', $code ), '', 'and that code cannot be replayed into a second one' );
  202. };
  203. done_testing();