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