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