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