Debian Codegraph @

tools/krb5-sync-backend

raw
1 #!/usr/bin/perl
2 #
3 # Manipulate Kerberos password and status change queue.
4 #
5 # Provides various utility commands to manipulate the queue of password and
6 # status changes created by krb5-sync's Kerberos plugin. Uses the krb5-sync
7 # utility to process changes.
8
9 ##############################################################################
10 # Declarations and site configuration
11 ##############################################################################
12
13 use 5.006;
14 use strict;
15 use warnings;
16
17 use Fcntl qw(LOCK_EX O_WRONLY O_CREAT O_EXCL);
18 use File::Basename qw(basename);
19 use Getopt::Long qw(GetOptions);
20 use IPC::Run qw(run);
21 use Net::Remctl::Backend;
22 use Pod::Usage qw(pod2usage);
23 use POSIX qw(EEXIST);
24
25 # Path to the krb5-sync binary.
26 my $SYNC = '/usr/sbin/krb5-sync';
27
28 # Default path to the directory that contains queued changes.
29 my $QUEUE = '/var/spool/krb5-sync';
30
31 # Regular expression prefix to match when ignoring error messages.
32 my $IGNORE_PREFIX = qr{
33 \A krb5-sync: [ ]
34 AD [ ] (?:password|status) [ ] change [ ] for [ ] \S+ [ ] failed:
35 }xms;
36
37 # Regexes of error messages to ignore when running in silent mode. These are
38 # all error messages that can indicate that the target account doesn't exist
39 # in Active Directory yet, as opposed to some more serious error.
40 my @IGNORE = (
41 qr{ $IGNORE_PREFIX .* Connection [ ] timed [ ] out \z }xms,
42 qr{ $IGNORE_PREFIX .* Authentication error \z }xms,
43 qr{ $IGNORE_PREFIX .* for [ ] service_locator \z }xms,
44 qr{ $IGNORE_PREFIX .* Operation [ ] not [ ] permitted \z }xms,
45 qr{ $IGNORE_PREFIX .* user [ ] .* [ ] not [ ] found [ ] via [ ] \S+\z}xms,
46 );
47
48 ##############################################################################
49 # Writing queue files
50 ##############################################################################
51
52 # Lock the queue. We have to do this around any change to the queue or any
53 # place where we need a consistent snapshot of the queue. Note that we use
54 # flock locking; other callers will have to match.
55 #
56 # $queue - Queue directory to use
57 #
58 # Returns: The file handle of the queue lock, to pass to unlock_queue
59 # Throws: Text exception on failure to open or lock the queue
60 sub lock_queue {
61 my ($queue) = @_;
62 open(my $lock_fh, '+>', "$queue/.lock")
63 or die "$0: cannot open $queue/.lock: $!\n";
64 flock($lock_fh, LOCK_EX)
65 or die "$0: cannot lock $queue/.lock: $!\n";
66 return $lock_fh;
67 }
68
69 # Unlock the queue.
70 #
71 # $lock_fh - The file handle of the queue lock
72 #
73 # Returns: undef
74 # Throws: Text exception on failure to close the lock file
75 sub unlock_queue {
76 my ($lock_fh) = @_;
77 close($lock_fh) or die "$0: cannot unlock queue: $!\n";
78 return;
79 }
80
81 # Generate a timestamp for queue file names from the current time. We want
82 # something that sorts even if time_t adds another digit (okay, this code
83 # won't last that long, but anyway...).
84 #
85 # Returns: The formatted timestamp for the current time.
86 sub queue_timestamp {
87 my ($sec, $min, $hour, $mday, $mon, $year) = gmtime;
88 $mon++;
89 $year += 1900;
90 return sprintf('%04d%02d%02dT%02d%02d%02dZ',
91 $year, $mon, $mday, $hour, $min, $sec);
92 }
93
94 # Write out a new queue file. We currently hard-code the target system to be
95 # "ad", since that's the only one that's currently implemented, but we keep
96 # the data field for future expansion. The queue file will be written with a
97 # timestamp for the current time.
98 #
99 # $queue - Queue directory to use
100 # $principal - Principal to queue an operation for
101 # $operation - Operation, chosen from enable, disable, or password
102 # @data - Additional data to add to the queue file
103 #
104 # Returns: undef
105 # Throws: Text exception on invalid arguments, write failure, or inability
106 # to create a usable queue file name
107 sub queue {
108 my ($queue, $principal, $operation, @data) = @_;
109
110 # Convert the principal to a simple username, used for our queue format.
111 my $user = $principal;
112 $user =~ s{ @ .* }{}xms;
113 $user =~ tr{/}{.};
114
115 # Both enable and disable use the same type in the file name.
116 my $type = $operation;
117 if ($type eq 'disable') {
118 $type = 'enable';
119 }
120
121 # Create the filename prefix for the queue file. "-" and a sequence
122 # number from 00 to 99 will be appended.
123 my $base = "$queue/$user-ad-$type-" . queue_timestamp();
124
125 # Find the next file name.
126 my $lock = lock_queue($queue);
127 my ($filename, $file);
128 for my $count (0 .. 99) {
129 $filename = "$base-" . sprintf('%02d', $count);
130 if (sysopen($file, $filename, O_WRONLY | O_CREAT | O_EXCL, 0600)) {
131 last;
132 }
133 if ($! != EEXIST) {
134 die "$0: cannot create $filename: $!\n";
135 }
136 }
137
138 # Write the data to the queue file.
139 print {$file} "$user\nad\n$operation\n"
140 or die "$0: cannot write to $filename: $!\n";
141 for my $data (@data) {
142 print {$file} $data or die "$0: cannot write to $filename: $!\n";
143 if ($data !~ m{\n}xms) {
144 print {$file} "\n" or die "$0: cannot write to $filename: $!\n";
145 }
146 }
147 close($file) or die "$0: cannot flush $filename: $!\n";
148
149 # Done. Unlock the queue.
150 unlock_queue($lock);
151 return;
152 }
153
154 # Handle a command that writes out a queue file. This is the command function
155 # called by Net::Remctl::Backend for the enable, disable, and password
156 # commands. It transforms the arguments into the format expected by the queue
157 # function.
158 #
159 # Due to a bug in Net::Remctl::Backend prior to 3.7, we have to check that we
160 # got sufficient arguments for the password action.
161 #
162 # $operation - The operation (enable, disable, or password)
163 # $options_ref - Reference to hash of command-line options
164 # directory - The queue directory to use
165 # $principal - The principal for which to queue a change
166 # @data - Any extra data (for password changes, the password)
167 #
168 # Returns: 0, indicating success
169 # Throws: Text exception on invalid arguments, write failure, or inability
170 # to create a usable queue file name
171 sub queue_command {
172 my ($operation, $options_ref, $principal, @data) = @_;
173 my $queue = $options_ref->{directory} || $QUEUE;
174 if ($operation eq 'password' && !@data) {
175 die "sync password: insufficient arguments\n";
176 }
177 queue($queue, $principal, $operation, @data);
178 return 0;
179 }
180
181 ##############################################################################
182 # Queue listing
183 ##############################################################################
184
185 # List all files in the queue and return them as a list of file names. The
186 # caller is responsible for locking the queue.
187 #
188 # $queue - The queue directory to read
189 #
190 # Returns: List of queue file names
191 # Throws: Text exception on failure to read the queue
192 sub queue_files {
193 my ($queue) = @_;
194
195 # Read the files, ignoring ones with a leading period.
196 opendir(my $dir, $queue) or die "$0: cannot open $queue: $!\n";
197 my @files = sort grep { !m{ \A [.] }xms } readdir($dir);
198 closedir($dir) or die "$0: cannot close $queue: $!\n";
199 return @files;
200 }
201
202 # List the current queue. Displays the user, the type of event, the
203 # destination service, and the timestamp. Sort the events the same way
204 # they're read when processing the queue.
205 #
206 # $options_ref - Reference to hash of command-line options
207 # directory - The queue directory to use
208 #
209 # Returns: 0, indicating success
210 # Throws: Text exception on failure to read the queue
211 sub list {
212 my ($options_ref) = @_;
213 my $queue = $options_ref->{directory} || $QUEUE;
214
215 # Read in the files within a queue lock.
216 my $lock = lock_queue($queue);
217 my @files = queue_files($queue);
218 unlock_queue($lock);
219
220 # Walk through the files and read in the data for each. We don't hold a
221 # lock for this, since it doesn't really matter if things disappear out
222 # from under us when listing the queue.
223 for my $filename (@files) {
224 my ($user, undef, undef, $time) = split(m{-}xms, $filename);
225 $time =~ s{^(\d\d\d\d)(\d\d)(\d\d)T(\d\d)(\d\d)(\d\d)Z\z}
226 {$1-$2-$3 $4:$5:$6 UTC}xms;
227
228 # Each data element is on one line. The first is the user, the second
229 # is the domain, the third is the operation, and the fourth is the
230 # password for password changes. Ignore corrupt files. If we can't
231 # open the file, it's probably been processed by another copy running
232 # process, so just ignore it.
233 if (open(my $file, '<', "$queue/$filename")) {
234 my @data = <$file>;
235 close($file) or die "$0: cannot read $queue/$filename: $!\n";
236 chomp(@data);
237 next if @data < 3;
238 printf {*STDOUT} "%-8s %-8s %-4s %s\n",
239 $user, $data[2], $data[1], $time;
240 }
241 }
242 return 0;
243 }
244
245 ##############################################################################
246 # Queue processing
247 ##############################################################################
248
249 # Go through the queue and process each pending event using krb5-sync.
250 # krb5-sync will remove the files when the processing is successful. If
251 # processing any of the queue files of a particular type fails, we skip all
252 # subsequent queue files of the same type for the same user.
253 #
254 # $options_ref - Reference to hash of command-line options
255 # directory - The queue directory to use
256 # silent - Filter out error messages indicating a missing user in AD
257 #
258 # Returns: 0 if all processing succeeded, 1 otherwise
259 # Throws: Text exception on failure to read the queue or spawn the command
260 sub process {
261 my ($options_ref) = @_;
262 my $queue = $options_ref->{directory} || $QUEUE;
263 my $silent = $options_ref->{silent};
264
265 # Read in the files within a queue lock.
266 my $list_lock = lock_queue($queue);
267 my @files = queue_files($queue);
268 unlock_queue($list_lock);
269
270 # Walk through the list of files and process each in turn, but keep track
271 # of which ones failed with an error and skip processing of other files
272 # with the same user, domain, and operation. We don't hold a lock across
273 # the entire operation, since it takes too long, but we do hold a queue
274 # lock while dealing with any single file.
275 my (%skip, $has_errors);
276 for my $filename (queue_files($queue)) {
277 my $path = "$queue/$filename";
278
279 # Grab the queue lock.
280 my $lock = lock_queue($queue);
281
282 # Skip missing files, since they've probably been processed by some
283 # other job running in parallel.
284 next if !-f "$path";
285
286 # Skip determinations are based on the first three elements of the
287 # file name, which will be the username, domain, and operation with
288 # enable and disable smashed to enable. Be sure the file name is
289 # sane.
290 my ($id) = ($filename =~ m{ \A ([^-]+-[^-]+-[^-]+)- }xms);
291 if (!defined($id)) {
292 warn "$0: invalid queue file name $path\n";
293 $has_errors = 1;
294 next;
295 }
296
297 # Skip if we already failed a conflicting change.
298 next if $skip{$id};
299
300 # Run the krb5-sync command on the queued change.
301 my ($stdout, $stderr);
302 run([$SYNC, '-f', $path], q{>}, \$stdout, q{2>}, \$stderr);
303
304 # Done with this file. Unlock the queue.
305 unlock_queue($lock);
306
307 # If the comamnd failed, skip conflicting changes and note errors.
308 if ($? != 0) {
309 $skip{$id} = 1;
310 $has_errors = 1;
311 }
312
313 # If in silent mode, filter standard error. Otherwise, print out
314 # everything, including standard output.
315 if ($options_ref->{silent}) {
316 STDERR:
317 for my $line (split(m{\n}xms, $stderr)) {
318 for my $ignore (@IGNORE) {
319 next STDERR if $line =~ m{ $ignore }xms;
320 }
321 print {*STDERR} $line, "\n"
322 or warn "$0: cannot write to standard error: $!\n";
323 }
324 } else {
325 print {*STDERR} $stderr
326 or warn "$0: cannot write to standard error: $!\n";
327 print {*STDOUT} $stdout
328 or warn "$0: cannot write to standard output: $!\n";
329 }
330 }
331
332 # Return an exit status.
333 return $has_errors ? 1 : 0;
334 }
335
336 ##############################################################################
337 # Queue cleanup
338 ##############################################################################
339
340 # Given a number of days, remove all queue files older than that number of
341 # days.
342 #
343 # $options_ref - Reference to hash of command-line options
344 # directory - The queue directory to use
345 # $days - Maximum age in days, beyond which queue files are removed
346 #
347 # Returns: 0 for success, 1 if we failed to unlink any files
348 # Throws: Text exception on any failures
349 sub purge {
350 my ($options_ref, $days) = @_;
351 my $queue = $options_ref->{directory} || $QUEUE;
352
353 # Lock the queue walk through the queue files and check their age.
354 my $has_errors;
355 my $lock = lock_queue($queue);
356 for my $filename (queue_files($queue)) {
357 my $path = "$queue/$filename";
358 if (-M $path > $days) {
359 if (!unlink($path)) {
360 warn "$0: cannot delete $path: $!\n";
361 $has_errors = 1;
362 }
363 }
364 }
365
366 # Return an exit status.
367 return $has_errors ? 1 : 0;
368 }
369
370 ##############################################################################
371 # Main routine
372 ##############################################################################
373
374 # Always flush output.
375 STDOUT->autoflush;
376
377 # Clean up the script name for error reporting.
378 my $fullpath = $0;
379 local $0 = basename($0);
380
381 # Standard options that all commands take.
382 my @options = qw(directory|d=s elp|h silent|s);
383
384 # The Net::Remctl::Backend configuration for our commands.
385 my %commands = (
386 disable => {
387 args_min => 1,
388 args_max => 1,
389 code => sub { queue_command('disable', @_) },
390 options => ['directory|d=s'],
391 summary => 'Queue disable of <user> in AD',
392 syntax => '<user>',
393 },
394 enable => {
395 args_min => 1,
396 args_max => 1,
397 code => sub { queue_command('enable', @_) },
398 options => ['directory|d=s'],
399 summary => 'Queue enable of <user> in AD',
400 syntax => '<user>',
401 },
402 list => {
403 args_max => 0,
404 code => \&list,
405 options => ['directory|d=s'],
406 summary => 'List pending queued actions',
407 syntax => q{},
408 },
409 manual => {
410 args_max => 0,
411 code => sub { pod2usage(-exitval => 0, -verbose => 2) },
412 summary => 'Show full manual including options',
413 syntax => q{},
414 },
415 password => {
416 args_min => 1,
417 args_max => 2,
418 code => sub { queue_command('password', @_) },
419 options => ['directory|d=s'],
420 stdin => 2,
421 summary => 'Queue <user> password change in AD',
422 syntax => '<user> <password>',
423 },
424 process => {
425 args_max => 0,
426 code => \&process,
427 options => ['directory|d=s', 'silent|s'],
428 summary => 'Process pending queued actions',
429 syntax => q{},
430 },
431 purge => {
432 args_min => 1,
433 args_max => 1,
434 code => \&purge,
435 options => ['directory|d=s'],
436 summary => 'Delete queued actions older than <days>',
437 syntax => '<days>',
438 },
439 );
440
441 # Configure Net::Remctl::Backend.
442 my $backend = Net::Remctl::Backend->new(
443 {
444 command => 'sync',
445 commands => \%commands,
446 help_banner => 'Kerberos status synchronization help:',
447 }
448 );
449
450 # Dispatch to the appropriate command.
451 exit($backend->run);
452 __END__
453
454 ##############################################################################
455 # Documentation
456 ##############################################################################
457
458 =for stopwords
459 krb5-sync-backend krb5-sync UTC Allbery timestamp username propagations
460 Kerberos regexes MERCHANTABILITY NONINFRINGEMENT sublicense
461
462 =head1 NAME
463
464 krb5-sync-backend - Manipulate Kerberos password and status change queue
465
466 =head1 SYNOPSIS
467
468 B<krb5-sync-backend> (help|manual)
469
470 B<krb5-sync-backend> (disable|enable) [B<-d> I<queue>] I<user>
471
472 B<krb5-sync-backend> list [B<-d> I<queue>]
473
474 B<krb5-sync-backend> process [B<-s>] [B<-d> I<queue>]
475
476 B<krb5-sync-backend> password [B<-d> I<queue>] I<user> ad < I<password>
477
478 B<krb5-sync-backend> purge [B<-d> I<queue>] I<days>
479
480 =head1 DESCRIPTION
481
482 B<krb5-sync-backend> provides an interface to the queue of pending
483 password and account status changes written by either this utility or by
484 the synchronization plugin after failures. It can queue account enables,
485 disables, or password changes for Active Directory, list the queued
486 actions, or process the queued actions with B<krb5-sync> (telling it to
487 take its action from a file).
488
489 The queue directory will contain files with names in the format:
490
491 <username>-<domain>-<action>-<timestamp>-<count>
492
493 where <username> is the name of the affected account (C</> will be
494 replaced with C<.> in the file name and the realm will be removed),
495 <domain> is C<ad>, <action> is either C<enable> (used for both enabling
496 and disabling accounts) or C<password>, <timestamp> is a ISO 8601
497 timestamp in UTC, and <count> is a two-digit zero-padded number between 0
498 and 99 (so that we can handle multiple changes that arrive in the same
499 second). Each file contains a queued change in the format described in
500 krb5-sync(8).
501
502 Supported arguments to B<krb5-sync-backend> are:
503
504 =over 4
505
506 =item disable I<user>
507
508 Queue a disable action (in Active Directory, as that's the only system
509 currently supported for enable and disable) for I<user>.
510
511 =item enable I<user>
512
513 Queue an enable action (in Active Directory, as that's the only system
514 currently supported for enable and disable) for I<user>.
515
516 =item help
517
518 List the supported commands.
519
520 =item list
521
522 List the current contents of the queue.
523
524 =item manual
525
526 Display this documentation.
527
528 =item process
529
530 Process the queue. All queued actions will be sorted alphanumerically
531 (which due to the timestamp means that all changes for a particular user of
532 a particular type will be done in the order queued). B<krb5-sync> will be
533 called for each queued action, as long as it continues to succeed. If it
534 fails for a queued action, all other actions sharing the same username,
535 domain, and action will be skipped and queue processing will continue with
536 the next action that differs in one of those three parameters.
537
538 =item password I<user> ad < I<password>
539
540 Queue a password change for I<user> in Active Directory, setting their
541 password to I<password>. By default, I<password> is read from standard input.
542 It can also be passed as a command-line argument, but this is less secure
543 since the password is then readable by anyone on the system who can see the
544 command-line arguments of processes.
545
546 The entire standard input is taken as the password, including any trailing
547 newlines, so be careful how the password is provided. If using something like
548 B<echo>, use C<echo -n> or the C<\c> flag, depending on your system.
549
550 =item purge I<days>
551
552 Delete all queued actions last modified longer than I<days> days ago. This
553 can be used to clean up old failed change propagations in situations where
554 accounts may be created or have password changes queued that are later
555 removed and never created in other environments.
556
557 =back
558
559 =head1 OPTIONS
560
561 Options must be specified after the command.
562
563 =over 4
564
565 =item B<-d> I<queue>, B<--directory>=I<queue>
566
567 Use I<queue> as the queue directory instead of the default of
568 F</var/spool/krb5-sync>. This also changes the lock file accordingly. This
569 option is supported for all commands except C<help> and C<manual>.
570
571 =item B<-s>, B<--silent>
572
573 This option is only allowed for the C<process> command. Filter out the
574 output of B<krb5-sync> to ignore common errors and success messages and
575 only show uncommon errors. This option will filter out all output when
576 B<krb5-sync> is successful and will filter out error messages that
577 normally indicate the account is missing in Active Directory. The regexes
578 can be modified at the start of this script.
579
580 =back
581
582 =head1 FILES
583
584 =over 4
585
586 =item F</usr/sbin/krb5-sync>
587
588 The path to the B<krb5-sync> utility. This may be changed at the top of
589 this script.
590
591 =item F</var/spool/krb5-sync>
592
593 The default path to the queue. This must match the queue_dir parameter in
594 F<krb5.conf> used by the plugin. It can be changed at the top of this
595 script.
596
597 =item F</var/spool/krb5-sync/.lock>
598
599 An empty file used for locking the queue. When writing to or querying the
600 queue, B<krb5-sync-backend> will open and lock this file with the Perl flock
601 function, which normally calls flock(2). Any other queue writers need to
602 use the same locking mechanism for safe operation.
603
604 =back
605
606 =head1 AUTHOR
607
608 Russ Allbery <[email protected]>
609
610 =head1 COPYRIGHT AND LICENSE
611
612 Copyright 2007, 2008, 2010, 2012, 2013 The Board of Trustees of the Leland
613 Stanford Junior University
614
615 Permission is hereby granted, free of charge, to any person obtaining a
616 copy of this software and associated documentation files (the "Software"),
617 to deal in the Software without restriction, including without limitation
618 the rights to use, copy, modify, merge, publish, distribute, sublicense,
619 and/or sell copies of the Software, and to permit persons to whom the
620 Software is furnished to do so, subject to the following conditions:
621
622 The above copyright notice and this permission notice shall be included in
623 all copies or substantial portions of the Software.
624
625 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
626 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
627 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
628 THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
629 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
630 FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
631 DEALINGS IN THE SOFTWARE.
632
633 =head1 SEE ALSO
634
635 krb5-sync(8)
636
637 The current version of this program is available from its web page at
638 L<http://www.eyrie.org/~eagle/software/krb5-sync/>.
639
640 =cut