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