chiark / gitweb /
New -q mode.
[chiark-utils.git] / sync-accounts / sync-accounts
1 #!/usr/bin/perl
2 # $Id: sync-accounts,v 1.5 1999-01-03 00:53:07 ian Exp $
3 # usage: sync-accounts [-n] [-C<config-file>] [<host> ...]
4 # options:
5 #   -n     do not really do anything
6 #   -C     alternative config file (default is /etc/sync-accounts)
7 #   -q     display accounts synched, not synched, etc.
8 # if no host(s) specified, does all
9 #
10 # The config file consists of directives, one per line.  Leading and
11 # trailing whitespace, blank lines and lines starting # are ignored.
12 #
13 # Some config file directives apply globally and should appear first:
14 #
15 #  lockpasswd <suffix/filename>
16 #  lockgroup <suffix/filename>
17 #      Specifies the lockfile suffix or pathname to use when editing
18 #      the passwd and group files.  The value is a suffix if it does
19 #      not start with `/'.
20 #
21 #  logfile <filename>
22 #      Append log messages to <filename> instead of stdout.
23 #      Errors still go to stderr.
24 #
25 # Some config file directives set options which may be different at
26 # different points in the file.  The most-recently-seen value is used
27 # at each point:
28 #
29 #  uidmin <min>
30 #  uidmax <max>
31 #  homebase <pathname>
32 #      When an account is to be created, a uid/gid will be chosen
33 #      which is one higher than the highest currently in use (except
34 #      that ids outside the range <min>-<max> are ignored and will
35 #      never be used).  The default home directory location is
36 #      <pathname>/<username>.
37 #
38 #  sameuid
39 #  nosameuid
40 #      Specifies whether uids are supposed to match.  The default is
41 #      nosameuid.  When sameuid is on, it is an error for the uid or
42 #      gid of a local account not to match the corresponding remote
43 #      account, and new local accounts will get the remote accounts'
44 #      ids.
45 #
46 #  usergroups
47 #  nousergroups
48 #      Specifies whether local accounts are supposed to have
49 #      corresponding groups.  If this is set then when a new account
50 #      is created, the corresponding per-user group will be created as
51 #      well, and per-user groups are created for existing accounts if
52 #      necessary (if account creation is enabled).  If the gid or
53 #      group name for a per-user group is already taken for a
54 #      different group name or gid this will be logged, and processing
55 #      of that account will be inhibited, but it is not a fatal
56 #      error.  The default is `usergroups'.
57 #
58 #  createuser
59 #  createuser <commandname>
60 #  nocreateuser
61 #      Specifies whether accounts found on the remote host should be
62 #      created if necessary, and what command to run to do the
63 #      creation (eg, setup of home directory).  The default is
64 #      nocreateuser.  If createuser is specified without a commandname
65 #      then sync-accounts-createuser is used.  The command is found on
66 #      the PATH if necessary.  Either sameuid, or both uidmin and
67 #      uidmax, must be specified, if accounts are to be created.
68 #
69 #  group <glob-pattern>
70 #  nogroup <glob-pattern>
71 #      Specifies that the membership of the local groups specified
72 #      should be adjusted or not adjusted whenever account data for a
73 #      particular user is copied, so that the account will be a member
74 #      of the affected group locally iff it is a member of the same
75 #      group on the remote host.  The most recently-encountered
76 #      glob-pattern for a particular group takes effect.  The default
77 #      is `nogroups *'.
78 #
79 # Some config file directives are per-host, and should appear before
80 # any directives which actually modify accounts:
81 #
82 #  host <shorthostname>
83 #      Starts a host's section.  This resets the per-host parameters
84 #      to the defaults.  The shorthostname need not be the host's
85 #      official name in any sense.  If sync-accounts is invoked with
86 #      host names on the command line they are compared with the
87 #      shorthostnames.
88 #
89 #  getpasswd <command>
90 #  getgroup <command>
91 #      Commands to run on the local host to get the passwd, shadow and
92 #      group data for the host in question.  getpasswd must be
93 #      specified if user data is to be transferred; getgroup must be
94 #      specified if group data is to be transferred.
95 #
96 #  getshadow <command>
97 #      Specifies that shadow file data is to be used (by default,
98 #      password information is found from the output of getpasswd).
99 #      The command should emit shadow data in the format specified by
100 #      shadow(5) on Linux.  getshadow should not be specified without
101 #      getpasswd.
102 #
103 # Some configuration file directives specify that account data is to
104 # transferred from the current host.  They should appear as the last
105 # thing(s) in a host section:
106 #
107 #  user <username> [remote=<remoteusername>]
108 #      Specifies that account data should be copied for local user
109 #      <username> from the remote account <remoteusername> (assumed to
110 #      be the same as <username> if not specified).  The account
111 #      password, comment field, and shell will be copied
112 #      unconditionally.  If sameuid is specified the uid will be
113 #      checked.
114 #
115 #  users <ruidmin>-<ruidmax>
116 #      Specifies that all remote users whose uid is in the given range
117 #      are to be copied to corresponding local user accounts.
118 #
119 #  nouser <username>
120 #      Specifies that data for <username> is _not_ to be copied, even
121 #      if subsequent user or users directives suggest that it should
122 #      be.
123 #
124 #   (A note is made when a `user', `users' or `nouser' directive is
125 #   encountered for a particular account, and no subsequent directives
126 #   for that account will take effect.)
127 #
128 #  addhere
129 #      This directive has no effect on `sync-accounts'.  However, it
130 #      is used as a placeholder by `grab-account': new accounts for
131 #      creation are inserted just before `addhere'.
132 #
133 # Finally, the config file must finish with:
134
135 #  end
136
137 use POSIX;
138
139 $configfile= '/etc/sync-accounts';
140 $def_createuser= 'sync-accounts-createuser';
141 $ch_homebase= '/home';
142 $opt_usergroups= 1;
143 @groupglobs= [ '.*', 0 ];
144 regroupglobs();
145
146 END {
147     for $x (@unlocks) {
148         unlink $x or warn "unable to unlock by removing $x: $!\n";
149     }
150 }
151
152 $|=1;
153 $cdays= int(time/86400);
154
155 @envs_passwd= qw(USER x UID GID COMMENT HOME SHELL);
156
157 while ($ARGV[0] =~ m/^-/) {
158     $_= shift @ARGV;
159     last if m/^--$/;
160     if (m/^-C/) {
161         $configfile= $';
162     } elsif (m/^-n$/) {
163         $no_act= 1;
164         $display= 0;
165     } elsif (m/^-q$/) {
166         $no_act= 1;
167         $display= 1;
168     } else {
169         die "unknown option $_\n";
170     }
171 }
172
173 for $h (@ARGV) { $wanthost{$h}= 1; }    
174
175 open CF,"< $configfile" or die "$configfile: $!";
176
177 sub fetchfile (\%$) {
178     my ($ary_ref,$get_str) = @_;
179
180     undef %$ary_ref;
181     open G,"$get_str" or die "$get_str: $!";
182     while (<G>) {
183         chomp;
184         m/^([^:]+)\:/ or die "$ch_name: $get_str:$.: $_ ?\n";
185         $ary_ref->{$1}= [ split(/\:/,$_,-1) ];
186     }
187     close G; $? and die "$ch_name: $get_str: exit code $?\n";
188 }
189
190 sub fetchownfile (\@$$) {
191     my ($ary_ref,$fn_str,$lock_str) = @_;
192     die "$configfile:$.: lockfile name for $fn_str not".
193         " defined (use lockpasswd/lockgroup)\n" unless length $lock_str;
194     if ($lock_str ne '/dev/null' && !$no_act) {
195         $lock_str= "$fn_str$lock_str" unless $lock_str =~ m,^/,;
196         link $fn_str,$lock_str or die "cannot lock $fn_str by creating $lock_str: $!\n";
197         push @unlocks,$lock_str;
198     }
199     open O,"$fn_str" or die "$fn_str: $!";
200     while (<O>) {
201         chomp;
202         push @$ary_ref, [ split(/\:/,$_,-1) ];
203     }
204     close O or die "$fn_str: $!";
205 }
206
207 sub diag ($) {
208     print "$diagstr: $_[0]\n" or die $!;
209 }
210
211 sub regroupglobs () {
212     $nogroups= (@groupglobs == 1 &&
213                 $groupglobs[0]->[0] eq '.*' &&
214                 !$groupglobs[0]->[1]);
215     $ggfunc= "sub wantsyncgroup {\n  \$_= \$_[0];\n  return\n";
216     for $e (@groupglobs) { $ggfunc.= "    m/^$e->[0]\$/ ? $e->[1] :\n"; }
217     $ggfunc.= "    die;\n};\n1;\n";
218 #print STDERR "$ggfunc\n";
219     eval $ggfunc or die "$ggfunc // $@";
220 }
221
222 sub fetchown () {
223     if (!$own_fetchedpasswd) {
224         fetchownfile(@ownpasswd,'/etc/passwd',$ch_lockpasswd);
225         if (defined stat('/etc/shadow')) {
226             $own_haveshadow= 1;
227             $own_fetchedshadow= 1;
228             fetchownfile(@ownshadow,'/etc/shadow','/dev/null');
229         } elsif ($! == &ENOENT) {
230             $own_haveshadow= 0;
231         } else {
232             die "unable to check for /etc/shadow: $!\n";
233         }
234         $own_fetchedpasswd= 1;
235     }
236     if (!$own_fetchedgroup) {
237         fetchownfile(@owngroup,'/etc/group',$ch_lockgroup);
238         $own_fetchedgroup= 1;
239     }   
240 #print STDERR "fetchown() -> $#ownpasswd $#owngroup\n";
241 }
242
243 sub checkuid ($$) {
244     my ($useuid,$foruser) = @_;
245     for $e (@ownpasswd) {
246         if ($e->[0] ne $foruser && $e->[2] == $useuid) {
247             diag("uid clash with $e->[0] (uid $e->[2])");
248             return 0;
249         }
250     }
251     return 1;
252 }
253
254 sub copyfield ($$$$) {
255     my ($file,$entry,$field,$value) = @_;
256     eval "\$ary_ref= \\\@own$file; 1;" or die $@;
257 #print STDERR "copyfield($file,$entry,$field,$value)\n";
258     for $e (@$ary_ref) {
259 #print STDERR "copyfield($file,$entry,$field,$value) $e->[0] $e->[field] ".join(':',@$e)."\n";
260         next unless $e->[0] eq $entry;
261         next if $e->[$field] eq $value;
262         $e->[$field]= $value;
263         eval "\$modified$file= 1; 1;" or die $@;
264     }
265 }
266
267 sub fetchpasswd () {
268     return if $ch_fetchedpasswd;
269     die "$configfile:$.: getpasswd not specified for host $ch_name\n"
270         unless length $ch_getpasswd;
271     undef %remshadow;
272     fetchfile(%rempasswd,"$ch_getpasswd |");
273     if (length $ch_getshadow) {
274         fetchfile(%remshadow,"$ch_getshadow |");
275         for $k (keys %rempasswd) {
276             $rempasswd{$k}->[1]= 'xx' unless length $rempasswd{$k}->[1];
277         }
278         for $k (keys %remshadow) {
279             next unless exists $rempasswd{$k};
280             $rempasswd{$k}->[1]= $remshadow{$k}->[1];
281         }
282     }
283 }
284
285 sub fetchgroup () {
286     return if $ch_fetchedgroup;
287     die "$configfile:$.: getgroup not specified for host $ch_name\n"
288         unless length $ch_getgroup;
289     fetchfile(%remgroup,"$ch_getgroup |");
290 }
291
292 sub syncusergroup ($$) {
293     my ($lu,$luid) = @_;
294
295     return 1 if !$opt_usergroups;
296 #print STDERR "syncusergroup($lu,$luid)\n";
297     $ugfound=0;
298     
299     for $e (@owngroup) {
300         $samename= $e->[0] eq $lu;
301         $sameid= $e->[2] eq $luid;
302         next unless $samename || $sameid;
303         if (!$samename || !$sameid) {
304             diag("local group $e->[0] ($e->[2]) mismatch vs. local user $lu ($luid)");
305             return 0;
306         }
307         if ($ugfound) {
308             diag("per-user group $lu ($luid) duplicated");
309             return 0;
310         }
311         $ugfound=1;
312     }
313
314     return 1 if $ugfound;
315
316     if (!length $opt_createuser) {
317         diag("account creation not enabled, not creating per-user group");
318         return 0;
319     }
320     push @owngroup, [ $lu,'x',$luid,'' ];
321     $modifiedgroup= 1;
322     return 1;
323 }
324
325 sub hosthead ($) {
326     my ($th) = @_;
327     return if $hostheaddone eq $th;
328     print "\n\n" or die $! if length $hostheaddone;
329     print "==== $th ====\n" or die $!;
330     $hostheaddone= $th;
331 }
332
333 sub syncuser ($$) {
334     my ($lu,$ru) = @_;
335
336 #print STDERR "syncuser($lu,$ru)\n";
337     next unless $ch_doinghost;
338     return if $doneuser{$lu}++;
339     return if !length $ru;
340
341     fetchown();
342
343     if ($display) {
344         for $e (@ownpasswd) {
345             next unless $e->[0] eq $lu;
346             hosthead("from $ch_name");
347             print ($lu eq $ru ? " $lu" : " $lu($ru)") or die $!;
348             print "<DUPLICATE>" if $displaydone{$lu}++;
349         }
350         return;
351     }
352     
353     $diagstr= "user $lu from $ch_name!$ru";
354
355 #print STDERR "syncuser($lu,$ru) doing\n";
356     fetchpasswd();
357
358     if (!$rempasswd{$ru}) { diag("no remote entry"); return; }
359     if (length $ch_getshadow && exists $remshadow{$ru} && length $remshadow{$ru}->[7]) {
360         diag("remote account disabled in shadow");
361         return;
362     }
363
364     if (!grep($_->[0] eq $lu, @ownpasswd)) {
365         if (!length $opt_createuser) { diag("account creation not enabled"); return; }
366         if ($no_act) { diag("-n specified; not creating account"); return; }
367
368         if ($opt_sameuid) {
369             $useuid= $rempasswd{$ru}->[2];
370         } else {
371             length $ch_uidmin or die "no uidmin specified, cannot create users";
372             length $ch_uidmax or die "no uidmax specified, cannot create users";
373             $ch_uidmin<$ch_uidmax or die "uidmin>=uidmax specified, cannot create users";
374         
375             $useuid= $ch_uidmin;
376             for $e (@ownpasswd, @owngroup) {
377                 $tuid= $e->[2]; next if $tuid<$useuid || $tuid>$ch_uidmax;
378                 if ($tuid==$ch_uidmax) {
379                     diag("uid/gid $ch_uidmax used, cannot create users");
380                     return;
381                 }
382                 $useuid= $tuid+1;
383             }
384         }
385         
386         @newpwent= ($lu,'x',$useuid,$useuid,$rempasswd{$ru}->[4],
387                     "$ch_homebase/$lu",$rempasswd{$ru}->[6]);
388         
389         defined($c= open CU,"-|") or die $!;
390         if (!$c) {
391             @unlocks= ();
392             defined($c2= open STDIN,"-|") or die $!;
393             if (!$c2) {
394                 print STDOUT join(':',@newpwent),"\n" or die $!;
395                 exit 0;
396             }
397             for ($i=0; $i<@envs_passwd; $i++) {
398                 next if $envs_passwd[$i] eq 'x';
399                 $ENV{"SYNCUSER_CREATE_$envs_passwd[$i]"}= $newpwent[$i];
400             }
401             exec $opt_createuser; die "$configfile:$.: ($lu): $opt_createuser: $!\n";
402         }
403         $newpwent= <CU>;
404         close CU; $? and die "$configfile:$.: ($lu): $opt_createuser: code $?\n";
405         chomp $newpwent;
406         if (length $newpwent) {
407             if ($newpwent !~ m/\:/) { diag("creation script demurred"); return; }
408             @newpwent= split(/\:/,$newpwent,-1);
409         }
410         die "$opt_createuser: bad output: $_\n" if @newpwent!=7 or $newpwent[0] ne $lu;
411         checkuid($newpwent[2],$lu) or return;
412         if ($own_haveshadow) {
413             push(@ownshadow,[ $lu, $newpwent[1], $cdays, 0,99999,7,'','','' ]);
414             $newpwent[1]= 'x';
415             $modifiedshadow= 1;
416         }
417         syncusergroup($lu,$newpwent[2]) or return;
418         push @ownpasswd,[ @newpwent ];
419         $modifiedpasswd= 1;
420     }
421
422     for $e (@ownpasswd) {
423         next unless $e->[0] eq $lu;
424         syncusergroup($lu,$e->[2]) or return;
425     }
426
427     $ruid= $rempasswd{$ru}->[2];
428     $rgid= $rempasswd{$ru}->[3];
429     if ($opt_sameuid && checkuid($ruid,$lu)) {
430         for $e (@ownpasswd) {
431             next unless $e->[0] eq $lu;
432             $luid= $e->[2]; $lgid= $e->[3];
433             die "$diagstr: local uid $luid, remote uid $ruid\n" if $luid ne $ruid;
434             die "$diagstr: local gid $lgid, remote gid $rgid\n" if $lgid ne $rgid;
435         }
436     }
437
438 #print STDERR "syncuser($lu,$ru) exists $own_haveshadow\n";
439     if ($own_haveshadow && grep($_->[0] eq $lu, @ownshadow)) {
440 #print STDERR "syncuser($lu,$ru) shadow $rempasswd{$ru}->[1]\n";
441         copyfield('shadow',$lu,1, $rempasswd{$ru}->[1]);
442     } else {
443 #print STDERR "syncuser($lu,$ru) passwd $rempasswd{$ru}->[1]\n";
444         copyfield('passwd',$lu,1, $rempasswd{$ru}->[1]);
445     }
446     copyfield('passwd',$lu,4, $rempasswd{$ru}->[4]); # comment
447     copyfield('passwd',$lu,6, $rempasswd{$ru}->[6]); # shell
448
449     if (!$nogroups) {
450         for $e (@owngroup) {
451             $tgroup= $e->[0];
452 #print STDERR "syncuser($lu,$ru) group $tgroup\n";
453             next unless &wantsyncgroup($tgroup);
454 #print STDERR "syncuser($lu,$ru) group $tgroup yes\n";
455             fetchgroup();
456             if (!exists $remgroup{$tgroup}) {
457                 diag("group $tgroup: not on remote host");
458                 next;
459             }
460             $inremote= grep($_ eq $ru, split(/\,/,$remgroup{$tgroup}->[3]));
461             $cusers= $e->[3]; $inlocal= grep($_ eq $lu, split(/\,/,$cusers));
462             if ($inremote && !$inlocal) {
463                 $cusers.= ',' if length $cusers;
464                 $cusers.= $lu;
465             } elsif ($inlocal && !$inremote) {
466                 $cusers= join(',', grep($_ ne $lu, split(/\,/, $cusers)));
467             } else {
468                 next;
469             }
470             $e->[3]= $cusers;
471             $modifiedgroup= 1;
472         }
473     }
474 }
475
476 sub banner () {
477     return if $bannerdone;
478     print "\n" or die $!; system 'date'; $? and die $?;
479     $bannerdone= 1;
480 }
481
482 sub finish () {
483     for $h (keys %wanthost) {
484         die "host $h not in config file\n" if $wanthost{$h};
485     }
486
487     if ($display) {
488         for $pw (1,-1,0) {
489 #print STDERR "\n\nfinish display=$display pw=$pw\n\n";
490             for $e (@ownpasswd) {
491                 $tu= $e->[0];
492                 next if $displaydone{$tu};
493                 $tpw= $e->[1];
494                 for $e2 (@ownshadow) {
495                     next unless $e2->[0] eq $tu;
496                     $tpw= $e2->[1]; last;
497                 }
498                 $tpw= length($tpw)==13 ? 1 : length($tpw) ? -1 : 0;
499                 next unless $pw == $tpw;
500                 hosthead($pw == 1 ? "unsynched normal account" :
501                          $pw == 0 ? "unsynched, passwordless" :
502                          "unsynched, no logins");
503                 print " $e->[0]" or die $!;
504             }
505         }
506         print "\n\n" or die $! if $hostheaddone;
507         exit 0;
508     }
509     
510     umask 077;
511     for $file (qw(passwd shadow group)) {
512         eval "\$modified= \$modified$file; \$data_ref= \\\@own$file;".
513             " \$fetched= \$own_fetched$file; 1;" or die $@;
514         next if !$modified;
515         die $file unless $fetched;
516         banner();
517         $newfile= $no_act ? "$file.new" : "/etc/$file.new";
518         open NF,"> $newfile";
519         for $e (@$data_ref) {
520             print NF join(':',@$e),"\n" or die $!;
521         }
522         close NF or die $!;
523         system "diff -U0 /etc/$file $newfile"; $?==256 or die $?;
524         if (!$no_act) {
525             if ($file eq 'shadow') {
526                 system "chown root.shadow $newfile"; $? and die $?;
527                 chmod 0640, $newfile or die $!;
528             } else {
529                 chown 0,0, $newfile or die $!;
530                 chmod 0644, $newfile or die $!;
531             }
532             rename $newfile, "/etc/$file" or die $!;
533         }
534     }
535     exit 0;
536 }
537
538 while (<CF>) {
539     chomp;
540     next if m/^\#/ || !m/\S/;
541     s/^\s*//; s/\s*$//;
542     finish() if m/^end$/;
543     if (m/^host\s+(\S+)$/) {
544         $ch_name= $1;
545         $ch_getpasswd= $ch_getgroup= $ch_getshadow= '';
546         $ch_fetchedpasswd= $ch_fetchedgroup;
547         if (!@ARGV) {
548             $ch_doinghost= 1;
549         } elsif (exists $wanthost{$ch_name}) {
550             $wanthost{$ch_name}= 0;
551             $ch_doinghost= 1;
552         } else {
553             $ch_doinghost= 0;
554         }
555     } elsif (m/^(getpasswd|getshadow|getgroup)\s+(.*\S)$/) {
556         eval "\$ch_$1= \$2; 1;" or die $@;
557     } elsif (m/^(lockpasswd|lockgroup)\s+(\S+)$/) {
558         eval "\$ch_$1= \$2; 1;" or die $@;
559     } elsif (m,^(homebase)\s+(/\S+)$,) {
560         eval "\$ch_$1= \$2; 1;" or die $@;
561     } elsif (m/^(uidmin|uidmax)\s+(\d+)$/ && $2>0) {
562         eval "\$ch_$1= \$2; 1;" or die $@;
563     } elsif (m/^createuser$/) {
564         $opt_createuser= $def_createuser;
565     } elsif (m/^nocreateuser$/) {
566         $opt_createuser= '';
567     } elsif (m/^createuser\s+(\S+)$/) {
568         $opt_createuser= $1;
569     } elsif (m/^logfile\s+(.*\S)$/) {
570         if (!$no_act) {
571             open STDOUT,">> $1" or die "$1: $!"; $|=1;
572         } elsif (!$display) {
573             print "would log to $1\n" or die $!;
574         }
575     } elsif (m/^(no|)(sameuid|usergroups)$/) {
576         eval "\$opt_$2= ".($1 eq 'no' ? 0 : 1)."; 1;" or die $@;
577     } elsif (m/^(no|)group\s+([-+.0-9a-zA-Z*?]+)$/) {
578         $yes= $1 eq 'no' ? 0 : 1;
579         $_= $2;
580         @groupglobs=() if $_ eq '*';
581         s/[-+._]/\\$1/g;
582         s/\*/\.\*/g;
583         s/\?/\./g;
584         unshift @groupglobs, [ $_, $yes ];
585         regroupglobs();
586     } elsif (m/^user\s+(\S+)$/) {
587         syncuser($1,$1);
588     } elsif (m/^user\s+(\S+)\s+remote\=(\S+)$/) {
589         syncuser($1,$2);
590     } elsif (m/^nouser\s+(\S+)$/) {
591         syncuser($1,'');
592     } elsif (m/^users\s+(\d+)\-(\d+)$/) {
593         $tmin= $1; $tmax= $2; $except= $3;
594         fetchpasswd();
595         for $k (keys %rempasswd) {
596             $tuid= $rempasswd{$k}->[2];
597             next if $tuid<$1 or $tuid>$2;
598             syncuser($k,$k);
599         }
600     } elsif (m/^addhere$/) {
601     } else {
602         die "$configfile:$.: unknown directive\n";
603     }
604 }
605
606 die "$configfile:$.: missing \`end', or read error\n";