]> eyrie.org Git - kerberos/krb5-strength.git/blob - tools/heimdal-history
Add hash benchmarking support to heimdal-history
[kerberos/krb5-strength.git] / tools / heimdal-history
1 #!/usr/bin/perl
2 #
3 # Password history via Heimdal external strength checking.
4 #
5 # This script is meant to be called via the Heimdal external password strength
6 # checking interface and maintains per-user password history.  Password
7 # history is stored as Crypt::PBKDF2 hashes with random salt for each
8 # password.
9 #
10 # Written by Russ Allbery <eagle@eyrie.org>
11 # Copyright 2013, 2014
12 #     The Board of Trustees of the Leland Stanford Junior University
13
14 ##############################################################################
15 # Declarations and configuration
16 ##############################################################################
17
18 require 5.010;
19 use autodie;
20 use strict;
21 use warnings;
22
23 use DB_File::Lock;
24 use Crypt::PBKDF2;
25 use Fcntl qw(O_CREAT O_RDWR);
26 use File::Basename qw(basename);
27 use Getopt::Long::Descriptive qw(describe_options);
28 use IPC::Run qw(run);
29 use JSON qw(encode_json decode_json);
30 use POSIX qw(setgid setuid);
31 use Readonly;
32 use Sys::Syslog qw(openlog syslog LOG_AUTH LOG_INFO LOG_WARNING);
33
34 # The most convenient interface to Berkeley DB files is ties.
35 ## no critic (Miscellanea::ProhibitTies)
36
37 # The number of PBKDF2 iterations to use when hashing passwords.  This number
38 # should be chosen so as to force the hash operation to take approximately 0.1
39 # seconds on current hardware.
40 Readonly my $HASH_ITERATIONS => 14592;
41
42 # Path to the history database.  Currently, this must be a Berkeley DB file in
43 # the old DB_HASH format.  Keys will be principal names, and values will be a
44 # JSON array of hashes.  Each hash will have two keys: timestamp, which holds
45 # the seconds since UNIX epoch at which the history entry was stored, and
46 # hash, which holds the Crypt::PBKDF2 LDAP-style password hash.
47 Readonly my $HISTORY_PATH => '/var/lib/heimdal-history/history.db';
48
49 # User and group used to do all password history lookups and writes, assuming
50 # that this program is invoked as root and can therefore change UID and GID.
51 Readonly my $HISTORY_USER  => '_history';
52 Readonly my $HISTORY_GROUP => '_history';
53
54 # Path to the Berkeley DB file (DB_HASH format) that stores statistics on
55 # password length of accepted passwords.  Each successful password validation
56 # will increase the counter for that length.  This is read and written with
57 # $HISTORY_USER and $HISTORY_GROUP.
58 Readonly my $LENGTH_STATS_PATH => '/var/lib/heimdal-history/lengths.db';
59
60 # The message to return to the user if we reject the password because it was
61 # found in the user's history.
62 Readonly my $REJECT_MESSAGE => 'password was previously used';
63
64 # The path to the external strength checking program to run.  This is done
65 # first before checking history, and if it fails, that failure is returned as
66 # the failure for this program.
67 Readonly my $STRENGTH_PROGRAM => '/usr/bin/heimdal-strength';
68
69 # User and group used to do password strength checking.  Generally, this
70 # doesn't require any privileges since the strength dictionary is
71 # world-readable.
72 Readonly my $STRENGTH_USER  => 'nobody';
73 Readonly my $STRENGTH_GROUP => 'nogroup';
74
75 ##############################################################################
76 # Utility functions
77 ##############################################################################
78
79 # Change real and effective UID and GID to those for the given user and group.
80 # Does nothing if not running as root.
81 #
82 # $user  - User to change the UID to
83 # $group - Group to change the GID to (and clear all supplemental groups)
84 #
85 # Returns: undef
86 #  Throws: Text exception on any failure
87 sub drop_privileges {
88     my ($user, $group) = @_;
89
90     # If running as root, drop privileges.  Fail if we can't get the UID and
91     # GID corresponding to our users.
92     if ($> == 0 || $< == 0) {
93         my $uid = getpwnam($user)
94           or die "$0: cannot get UID for $user\n";
95         my $gid = getgrnam($group)
96           or die "$0: cannot get GID for $group\n";
97         setgid($gid) or die "$0: cannot setgid to $gid: $!\n";
98         setuid($uid) or die "$0: cannot setuid to $uid: $!\n";
99         if ($> == 0 || $< == 0) {
100             die "$0: failed to drop permissions\n";
101         }
102     }
103     return;
104 }
105
106 ##############################################################################
107 # Logging
108 ##############################################################################
109
110 # Given a list of keys and values for a log message as a hash reference,
111 # return in encoded format following our logging protocol.  The log format is
112 # a set of <key>=<value> parameters separated by a space.  Values containing
113 # whitespace are quoted with double quotes, with any internal double quotes
114 # doubled.
115 #
116 # Here also is defined a custom sort order for the encoded key/value pairs to
117 # keep them in a reasonable order for a human to read.
118 #
119 # $params_ref - Reference to a hash of key/value pairs
120 #
121 # Returns: The encoded format as a string
122 sub encode_log_message {
123     my ($params_ref) = @_;
124
125     # Define the custom sort order for keys.
126     my $order = 1;
127     my %order
128       = map { $_ => $order++ } qw(action principal error result reason);
129
130     # Build the message from the parameters.
131     my $message;
132     for my $key (sort { $order{$a} <=> $order{$b} } keys %{$params_ref}) {
133         my $value = $params_ref->{$key};
134         $value =~ s{ \" }{\"\"}xmsg;
135         if ($value =~ m{ [ \"] }xms) {
136             $value = qq{"$value"};
137         }
138         $message .= qq{$key=$value };
139     }
140     chomp($message);
141     return $message;
142 }
143
144 # Log a non-fatal error encountered while trying to check or store password
145 # history.  This is used for errors where the password is accepted, but we ran
146 # into some anomalous event such as corrupted history data that should be
147 # drawn to the attention of an administrator.  The log format is a set of
148 # <key>=<value> parameters, with the following keys:
149 #
150 # - action:    the action performed (currently always "check")
151 # - principal: the principal to check a password for
152 # - error:     an error message explaining the anomalous situation
153 #
154 # Values containing whitespace are quoted with double quotes, with any
155 # internal double quotes doubled.
156 #
157 # $principal - Principal for which we checked a password
158 # $error     - The error message
159 #
160 # Returns: undef
161 sub log_error {
162     my ($principal, $error) = @_;
163     my $message = encode_log_message(
164         action    => 'check',
165         principal => $principal,
166         error     => $error,
167     );
168     syslog(LOG_WARNING, '%s', $message);
169     return;
170 }
171
172 # Log the disposition of a particular password strength checking request.  All
173 # log messages are logged through syslog at class info.  The log format is a
174 # set of <key>=<value> parameters, with the following keys:
175 #
176 # - action:    the action performed (currently always "check")
177 # - principal: the principal to check a password for
178 # - result:    either "accepted" or "rejected"
179 # - reason:    the reason for a rejection
180 #
181 # Values containing whitespace are quoted with double quotes, with any
182 # internal double quotes doubled.
183 #
184 # $principal - Principal for which we checked a password
185 # $result    - "accepted" or "rejected" per above
186 # $reason    - On rejection, the reason
187 #
188 # Returns: undef
189 sub log_result {
190     my ($principal, $result, $reason) = @_;
191
192     # Create the message.
193     my %message = (
194         action    => 'check',
195         principal => $principal,
196         result    => $result,
197     );
198     if ($result eq 'rejected' && defined($reason)) {
199         $message{reason} = $reason;
200     }
201     my $message = encode_log_message(\%message);
202
203     # Log the message.
204     syslog(LOG_INFO, '%s', $message);
205     return;
206 }
207
208 ##############################################################################
209 # Crypto
210 ##############################################################################
211
212 # Given a password, return the hash for that password.  Hashing is done with
213 # PBKDF2 using SHA-2 as the underlying hash function.  As of version 0.133330,
214 # this uses SHA-256.
215 #
216 # $password   - Password to hash
217 # $iterations - Optional iteration count, defaulting to $HASH_ITERATIONS
218 #
219 # Returns: Hash encoded in the LDAP-compatible Crypt::PBKDF2 format
220 sub password_hash {
221     my ($password, $iterations) = @_;
222     $iterations //= $HASH_ITERATIONS;
223     my $hasher = Crypt::PBKDF2->new(
224         hash_class => 'HMACSHA2',
225         iterations => $iterations,
226     );
227     return $hasher->generate($password);
228 }
229
230 # Given a password and the password history for the user as a reference to a
231 # array, check whether that password is found in the history.  The history
232 # array is expected to contain anonymous hashes.  The only key of interest is
233 # the "hash" key, whose value is expected to be a hash in the LDAP-compatible
234 # Crypt::PBKDF2 format.
235 #
236 # Invalid history entries are ignored for the purposes of this check and
237 # treated as if the entry did not exist.
238 #
239 # $principal   - Principal to check (solely for logging purposes)
240 # $password    - Password to check
241 # $history_ref - Reference to array of anonymous hashes with "hash" keys
242 #
243 # Returns: True if the password matches one of the history hashes, false
244 #          otherwise
245 sub is_in_history {
246     my ($principal, $password, $history_ref) = @_;
247     my $hasher = Crypt::PBKDF2->new(hash_class => 'HMACSHA2');
248
249     # Walk the history looking at each hash key.
250     for my $entry (@{$history_ref}) {
251         my $hash = $entry->{hash};
252         next if !defined($hash);
253
254         # validate throws an exception if the hash is in an invalid format.
255         # Treat that case the same as a miss, but log it.
256         if (eval { $hasher->validate($hash, $password) }) {
257             return 1;
258         } elsif ($@) {
259             log_error($principal, "hash validate failed: $@");
260         }
261     }
262
263     # No match.
264     return;
265 }
266
267 ##############################################################################
268 # Benchmarking
269 ##############################################################################
270
271 # Perform a binary search for a number of hash iterations that makes password
272 # hashing take the given target time on the current system.
273 #
274 # Assumptions:
275 #
276 # * The system load is low enough that this benchmark result is meaningful
277 #   and not heavily influenced by other programs running on the system.  The
278 #   binary search may be unstable if the system load is too variable.
279 #
280 # * The static "password" string used for benchmarking will exhibit similar
281 #   performance to the statistically average password.
282 #
283 # Information about the iteration search process is printed to standard output
284 # while the search runs.
285 #
286 # $target - The elapsed time, in real seconds, we're aiming for
287 # $delta  - The permissible delta around the target time
288 #
289 # Returns: The number of hash iterations with that performance characteristic
290 #  Throws: Text exception on failure to write to standard output
291 sub find_iteration_count {
292     my ($target, $delta) = @_;
293     my $high = 0;
294     my $low  = 0;
295
296     # A static password to use for benchmarking.
297     my $password = 'this is a benchmark';
298
299     # Start at the current configured iteration count.  If this doesn't take
300     # long enough, it becomes the new low mark and we try double that
301     # iteration count.  Otherwise, do binary search.
302     #
303     # We time twenty iterations each time, chosen because it avoids the
304     # warnings from Benchmark about too few iterations for a reliable count.
305     require Benchmark;
306     my $iterations = $HASH_ITERATIONS;
307     while (1) {
308         my $hash = sub { password_hash($password, $iterations) };
309         my $times = Benchmark::timethis(20, $hash, q{}, 'none');
310
311         # Extract the CPU time from the formatted time string.  This will be
312         # the total time for all of the iterations, so divide by the iteration
313         # count to recover the time per iteration.
314         my $report = Benchmark::timestr($times);
315         my ($time) = ($report =~ m{ ([\d.]+) [ ] CPU }xms);
316         $time = $time / 20;
317
318         # Tell the user what we discovered.
319         say {*STDOUT} "Performing $iterations iterations takes $time seconds"
320           or die "$0: cannot write to standard output: $!\n";
321
322         # If this is what we're looking for, we're done.
323         if (abs($time - $target) < $delta) {
324             last;
325         }
326
327         # Determine the new iteration target.
328         if ($time > $target) {
329             $high = $iterations;
330         } else {
331             $low = $iterations;
332         }
333         if ($time < $target && $high == 0) {
334             $iterations = $iterations * 2;
335         } else {
336             $iterations = int(($high + $low) / 2);
337         }
338     }
339
340     # Report the result and return it.
341     say {*STDOUT} "Use $iterations iterations"
342       or die "$0: cannot write to standard output: $!\n";
343     return $iterations;
344 }
345
346 ##############################################################################
347 # Database
348 ##############################################################################
349
350 # Given a principal and a password, determine whether the password was found
351 # in the password history for that user.
352 #
353 # $path      - Path to the history file
354 # $principal - Principal for which to check history
355 # $password  - Check history for this password
356 #
357 # Returns: True if $password is found in history, false otherwise
358 #  Throws: On failure to open, lock, or tie the database
359 sub check_history {
360     my ($path, $principal, $password) = @_;
361
362     # Open and lock the database and retrieve the history for the user.
363     # We have to lock for write so that we can create the database if it
364     # doesn't already exist.  Password change should be infrequent enough
365     # and our window is fast enough that it shouldn't matter.  We do this
366     # in a separate scope so that the history hash goes out of scope and
367     # is freed and unlocked.
368     my $history_json;
369     {
370         my %history;
371         my $mode = O_CREAT | O_RDWR;
372         tie(%history, 'DB_File::Lock', [$path, $mode, oct(600)], 'write')
373           or die "$0: cannot open $path: $!\n";
374         $history_json = $history{$principal};
375     }
376
377     # If there is no history for the user, return the trivial false.
378     if (!defined($history_json)) {
379         return;
380     }
381
382     # Decode history from JSON.  If this fails (corrupt history), treat it as
383     # if the user has no history, but log the error message.
384     my $history_ref = eval { decode_json($history_json) };
385     if (!defined($history_ref)) {
386         log_error($principal, "history JSON decoding failed: $@");
387         return;
388     }
389
390     # Finally, check the password against the hashes in history.
391     return is_in_history($principal, $password, $history_ref);
392 }
393
394 # Write a new history entry to the database given the principal and the
395 # password to record.  History records are stored as JSON arrays of objects,
396 # with keys "timestamp" and "hash".
397 #
398 # $path      - Path to the history file
399 # $principal - Principal for which to check history
400 # $password  - Check history for this password
401 #
402 # Returns: undef
403 #  Throws: On failure to open, lock, or tie the database
404 sub write_history {
405     my ($path, $principal, $password) = @_;
406
407     # Open and lock the database for write.
408     my %history;
409     my $mode = O_CREAT | O_RDWR;
410     tie(%history, 'DB_File::Lock', [$path, $mode, oct(600)], 'write')
411       or die "$0: cannot open $path: $!\n";
412
413     # Read the existing history.  If the existing history is corrupt, treat
414     # that as equivalent to not having any history, but log an error.
415     my $history_json = $history{$principal};
416     my $history_ref;
417     if (defined($history_json)) {
418         $history_ref = eval { decode_json($history_json) };
419         if ($@) {
420             log_error($principal, "history JSON decoding failed: $@");
421         }
422     }
423     if (!defined($history_ref)) {
424         $history_ref = [];
425     }
426
427     # Add a new history entry.
428     my $entry = { timestamp => time(), hash => password_hash($password) };
429     unshift(@{$history_ref}, $entry);
430
431     # Store the encoded data back in the history database.
432     $history{$principal} = encode_json($history_ref);
433
434     # The database is closed and unlocked when %history goes out of scope.
435     # Unfortunately, we lose on error detection here, since there doesn't
436     # appear to be a way to determine whether all the writes succeeded.  But
437     # losing a bit of history in the rare error case of failing to write to
438     # local disk is probably not a big deal.
439     return;
440 }
441
442 # Write statistics about password length.  Given the length of the password
443 # and the path to the length statistics database, increments the counter for
444 # that password length.
445 #
446 # Any failure to open or write to the database is ignored, since this is
447 # considered optional logging and should not block the password change.
448 #
449 # $path   - Path to the length statistics file
450 # $length - Length of the accepted password
451 #
452 # Returns: undef
453 sub update_length_counts {
454     my ($path, $length) = @_;
455
456     # Open and lock the database for write.
457     my %lengths;
458     my $mode = O_CREAT | O_RDWR;
459     tie(%lengths, 'DB_File::Lock', [$path, $mode, oct(600)], 'write')
460       or return;
461
462     # Write each of the hashes.
463     $lengths{$length}++;
464
465     # The database is closed and unlocked when %lengths goes out of scope.
466     return;
467 }
468
469 ##############################################################################
470 # Heimdal password quality protocol
471 ##############################################################################
472
473 # Run another external password quality checker and return the results.  This
474 # allows us to chain to another program that handles the actual strength
475 # checking prior to handling history.
476 #
477 # $principal - Principal attempting to change their password
478 # $password  - The new password
479 #
480 # Returns: Scalar context: true if the password was accepted, false otherwise
481 #          List context: whether the password is okay, the exit status of the
482 #            quality checking program, and the error message if the first
483 #            element is false
484 #  Throws: Text exception on failure to execute the program, or read or write
485 #          from it or to it, or if it fails without an error
486 sub strength_check {
487     my ($principal, $password) = @_;
488
489     # Run the external quality checking program.  If we're root, we'll run it
490     # as the strength checking user and group.
491     my $in = "principal: $principal\nnew-password: $password\nend\n";
492     my $init = sub { drop_privileges($STRENGTH_USER, $STRENGTH_GROUP) };
493     my ($out, $err);
494     run([$STRENGTH_PROGRAM, $principal], \$in, \$out, \$err, init => $init);
495     my $status = ($? >> 8);
496
497     # Check the results.
498     my $okay = ($status == 0 && $out eq "APPROVED\n");
499
500     # If the program failed, collect the error message.
501     if (!$okay) {
502         if ($err) {
503             $err =~ s{ \n .* }{}xms;
504         } else {
505             die "$0: password strength checking failed without an error\n";
506         }
507     }
508
509     # Return the results.
510     return wantarray ? ($okay, $err, $status) : $okay;
511 }
512
513 # Read a Heimdal external password quality checking request from the provided
514 # file handle and return the principal (ignored for our application) and the
515 # password.
516 #
517 # The protocol expects the following data (without leading whitespace) on
518 # standard input, in precisely this order:
519 #
520 #     principal: <principal>
521 #     new-password: <password>
522 #     end
523 #
524 # There is one and only one space after the colon, and any subsequent spaces
525 # are part of the value (such as leading spaces in the password).
526 #
527 # $fh - File handle from which to read
528 #
529 # Returns: Scalar context: the password
530 #          List context: a list of the password and the principal
531 #  Throws: Text exception on any protocol violations or IO errors
532 sub read_change_data {
533     my ($fh) = @_;
534     my @keys = qw(principal new-password);
535     my %data;
536
537     # Read the data elements we expect.  Verify that they come in the correct
538     # order and the correct format.
539     local $/ = "\n";
540     for my $key (@keys) {
541         my $line = readline($fh);
542         if (!defined($line)) {
543             die "$0: truncated input before $key: $!\n";
544         }
545         chomp($line);
546         if ($line =~ s{ \A \Q$key\E : [ ] }{}xms) {
547             $data{$key} = $line;
548         } else {
549             die "$0: unrecognized input line before $key\n";
550         }
551     }
552
553     # The final line of input must be a literal "end\n";
554     my $line = readline($fh);
555     if (!defined($line)) {
556         die "$0: truncated input before end: $!\n";
557     } elsif ($line ne "end\n") {
558         die "$0: unrecognized input line before end\n";
559     }
560
561     # Return the results.
562     my $password  = $data{'new-password'};
563     my $principal = $data{principal};
564     return wantarray ? ($password, $principal) : $password;
565 }
566
567 ##############################################################################
568 # Main routine
569 ##############################################################################
570
571 # Always flush output.
572 STDOUT->autoflush;
573
574 # Clean up the script name for error reporting.
575 my $fullpath = $0;
576 local $0 = basename($0);
577
578 # Parse the argument list.
579 my ($opt, $usage) = describe_options(
580     '%c %o',
581     ['benchmark|b=f', 'Benchmark hash iterations for this target time'],
582     ['database|d=s',  'Path to the history database, overriding the default'],
583     ['help|h',        'Print usage message and exit'],
584     ['manual|man|m',  'Print full manual and exit'],
585     ['stats|S=s',     'Path to hash of length statistics'],
586     ['strength|s=s',  'Path to strength checking program to run'],
587 );
588 if ($opt->help) {
589     print {*STDOUT} $usage->text
590       or die "$0: cannot write to standard output: $!\n";
591     exit(0);
592 } elsif ($opt->manual) {
593     say {*STDOUT} 'Feeding myself to perldoc, please wait...'
594       or die "$0: cannot write to standard output: $!\n";
595     exec('perldoc', '-t', $fullpath);
596 }
597 my $database = $opt->database || $HISTORY_PATH;
598 my $stats_db = $opt->stats    || $LENGTH_STATS_PATH;
599
600 # If asked to do benchmarking, ignore other arguments and just do that.
601 # Currently, we hard-code a 0.005-second granularity on our binary search.
602 if ($opt->benchmark) {
603     find_iteration_count($opt->benchmark, 0.005);
604     exit(0);
605 }
606
607 # Open syslog for result reporting.
608 openlog($0, 'pid', LOG_AUTH);
609
610 # Read the principal and password that we're supposed to check.
611 my ($password, $principal) = read_change_data(\*STDIN);
612
613 # Delegate to the external strength checking program.
614 my ($okay, $error, $status) = strength_check($principal, $password);
615 if (!$okay) {
616     log_result($principal, 'rejected', $error);
617     warn "$error\n";
618     exit($status);
619 }
620
621 # Drop privileges for the rest of the program.
622 drop_privileges($HISTORY_USER, $HISTORY_GROUP);
623
624 # Hash the password and check history.  Exit if a hash is in history.
625 if (check_history($database, $principal, $password)) {
626     log_result($principal, 'rejected', $REJECT_MESSAGE);
627     warn "$REJECT_MESSAGE\n";
628     exit(0);
629 }
630
631 # The password is accepted.  Record it, update the length counter, and return
632 # success.
633 log_result($principal, 'accepted');
634 write_history($database, $principal, $password);
635 say {*STDOUT} 'APPROVED'
636   or die "$0: cannot write to standard output: $!\n";
637 update_length_counts($stats_db, length($password));
638 exit(0);
639
640 __END__
641
642 ##############################################################################
643 # Documentation
644 ##############################################################################
645
646 =for stopwords
647 heimdal-history heimdal-strength Heimdal -hm BerkeleyDB timestamps POSIX
648 whitespace API Allbery sublicense MERCHANTABILITY NONINFRINGEMENT syslog
649 pseudorandom JSON LDAP-compatible PBKDF2 SHA-256
650
651 =head1 NAME
652
653 heimdal-history - Password history via Heimdal external strength checking
654
655 =head1 SYNOPSIS
656
657 B<heimdal-history> [B<-hm>] [B<-b> I<target-time>] [B<-d> I<database>]
658     [B<-S> I<length-stats-db>] [B<-s> I<strength-program>] [B<principal>]
659
660 =head1 DESCRIPTION
661
662 B<heimdal-history> is an implementation of password history via the
663 Heimdal external password strength checking interface.  It stores separate
664 history for each principal, hashed using Crypt::PBKDF2 with
665 randomly-generated salt.  (The randomness is from a weak pseudorandom
666 number generator, not strongly random.)
667
668 Password history is stored in a BerkeleyDB DB_HASH file.  The key is the
669 principal.  The value is a JSON array of objects, each of which has two
670 keys.  C<timestamp> contains the time when the history entry was added (in
671 POSIX seconds since UNIX epoch), and C<hash> contains the hash of a
672 previously-used password in the Crypt::PBKDF2 LDAP-compatible format.
673 Passwords are hashed using PBKDF2 (from PKCS#5) with SHA-256 as the
674 underlying hash function using a number of rounds configured in this
675 script.  See L<Crypt::PBKDF2> for more information.
676
677 B<heimdal-history> also checks password strength before checking history.
678 It does so by invoking another program that also uses the Heimdal external
679 password strength checking interface.  By default, it runs
680 B</usr/bin/heimdal-strength>.  Only if that program approves the password
681 does it hash it and check history.
682
683 As with any implementation of the Heimdal external password strength
684 checking protocol, B<heimdal-history> expects, on standard input:
685
686     principal: <principal>
687     new-password: <password>
688     end
689
690 (with no leading whitespace).  <principal> is the principal changing its
691 password (passed to the other password strength checking program but
692 otherwise unused here), and <password> is the new password.  There must
693 be exactly one space after the colon.  Any subsequent spaces are taken to
694 be part of the principal or password.
695
696 If invoked as root, B<heimdal-history> will run the external strength
697 checking program as user C<nobody> and group C<nogroup>, and will check
698 and write to the history database as user C<_history> and group
699 C<_history>.  These users must exist on the system if it is run as root.
700
701 The result of each password check will be logged to syslog (priority
702 LOG_INFO, facility LOG_AUTH).  Each log line will be a set of key/value
703 pairs in the format C<< I<key>=I<value> >>.  The keys are:
704
705 =over 4
706
707 =item action
708
709 The action performed (currently always C<check>).
710
711 =item principal
712
713 The principal for which a password was checked.
714
715 =item error
716
717 An internal error message that did not stop the history check, but which
718 may indicate that something is wrong with the history database (such as
719 corrupted entries or invalid hashes).  If this key is present, neither
720 C<result> nor C<reason> will be present.  There will be a subsequent log
721 message from the same invocation giving the final result of the history
722 check (assuming B<heimdal-history> doesn't exit with a fatal error).
723
724 =item result
725
726 Either C<accepted> or C<rejected>.
727
728 =item reason
729
730 If the password was rejected, the reason for the rejection.
731
732 =back
733
734 The value will be surrounded with double quotes if it contains a double
735 quote or space.  Any double quotes in the value will be doubled, so C<">
736 becomes C<"">.
737
738 =head1 OPTIONS
739
740 =over 4
741
742 =item B<-b> I<target-time>, B<--benchmark>=I<target-time>
743
744 Do not do a password history check.  Instead, benchmark the hash algorithm
745 with various possible iteration counts and find an iteration count that
746 results in I<target-time> seconds of computation time required to hash a
747 password (which should be a real number).  A result will be considered
748 acceptable if it is within 0.005 seconds of the target time.  The results
749 will be printed to standard output and then B<heimdal-history> will exit
750 successfully.
751
752 =item B<-d> I<database>, B<--database>=I<database>
753
754 Use I<database> as the history database file instead of the default
755 (F</var/lib/heimdal-history/history.db>).  Primarily used for testing,
756 since Heimdal won't pass this argument.
757
758 =item B<-h>, B<--help>
759
760 Print a short usage message and exit.
761
762 =item B<-m>, B<--manual>, B<--man>
763
764 Display this manual and exit.
765
766 =item B<-S> I<length-stats-db>, B<--stats>=I<length-stats-db>
767
768 Use I<length-stats-db> as the database file for password length statistics
769 instead of the default (F</var/lib/heimdal-history/lengths.db>).
770 Primarily used for testing, since Heimdal won't pass this argument.
771
772 =item B<-s> I<strength-program>, B<--strength>=I<strength-program>
773
774 Run I<strength-program> as the external strength-checking program instead
775 of the default (F</usr/bin/heimdal-strength>).  Primarily used for
776 testing, since Heimdal won't pass this argument.
777
778 =back
779
780 =head1 RETURN STATUS
781
782 On approval of the password, B<heimdal-history> will print C<APPROVED> and
783 a newline to standard output and exit with status 0.
784
785 If the password is rejected by the strength checking program or if it (or
786 a version with a single character removed) matches one of the hashes stored
787 in the password history, B<heimdal-history> will print the reason for
788 rejection to standard error and exit with status 0.
789
790 On any internal error, B<heimdal-history> will print the error to standard
791 error and exit with a non-zero status.
792
793 =head1 FILES
794
795 =over 4
796
797 =item F</usr/bin/heimdal-strength>
798
799 The default password strength checking program.  This program must follow
800 the Heimdal external password strength checking API.
801
802 =item F</var/lib/heimdal-history/history.db>
803
804 The default database path.  If B<heimdal-strength> is run as root, this
805 file needs to be readable and writable by user C<_history> and group
806 C<_history>.  If it doesn't exist, it will be created with mode 0600.
807
808 =item F</var/lib/heimdal-history/history.db.lock>
809
810 The lock file used to synchronize access to the history database.  As with
811 the history database, if B<heimdal-strength> is run as root, this file
812 needs to be readable and writable by user C<_history> and group
813 C<_history>.
814
815 =item F</var/lib/heimdal-history/lengths.db>
816
817 The default length statistics path, which will be a BerkeleyDB DB_HASH
818 file of password lengths to counts of passwords with that length.  If
819 B<heimdal-strength> is run as root, this file needs to be readable and
820 writable by user C<_history> and group C<_history>.  If it doesn't exist,
821 it will be created with mode 0600.
822
823 =item F</var/lib/heimdal-history/lengths.db.lock>
824
825 The lock file used to synchronize access to the length statistics
826 database.  As with the length statistics database, if B<heimdal-strength>
827 is run as root, this file needs to be readable and writable by user
828 C<_history> and group C<_history>.
829
830 =back
831
832 =head1 AUTHOR
833
834 Russ Allbery <eagle@eyrie.org>
835
836 =head1 COPYRIGHT AND LICENSE
837
838 Copyright 2013, 2014 The Board of Trustees of the Leland Stanford Junior
839 University
840
841 Permission is hereby granted, free of charge, to any person obtaining a
842 copy of this software and associated documentation files (the "Software"),
843 to deal in the Software without restriction, including without limitation
844 the rights to use, copy, modify, merge, publish, distribute, sublicense,
845 and/or sell copies of the Software, and to permit persons to whom the
846 Software is furnished to do so, subject to the following conditions:
847
848 The above copyright notice and this permission notice shall be included in
849 all copies or substantial portions of the Software.
850
851 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
852 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
853 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
854 THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
855 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
856 FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
857 DEALINGS IN THE SOFTWARE.
858
859 =head1 SEE ALSO
860
861 L<Crypt::PBKDF2>, L<heimdal-strength(1)>
862
863 =cut