chiark / gitweb /
a1b149340ab0b7a49619aec251d3ffcb26a00ce5
[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 # Finally, the config file must finish with:
132
133 #  end
134
135 use POSIX;
136
137 $configfile= '/etc/sync-accounts';
138 $def_createuser= 'sync-accounts-createuser';
139 $ch_homebase= '/home';
140 $opt_usergroups= 1;
141 @groupglobs= [ '.*', 0 ];
142 regroupglobs();
143
144 END {
145     for $x (@unlocks) {
146         unlink $x or warn "unable to unlock by removing $x: $!\n";
147     }
148 }
149
150 $|=1;
151 $cdays= int(time/86400);
152
153 @envs_passwd= qw(USER x UID GID COMMENT HOME SHELL);
154
155 while ($ARGV[0] =~ m/^-/) {
156     $_= shift @ARGV;
157     last if m/^--$/;
158     if (m/^-C/) {
159         $configfile= $';
160     } elsif (m/^-n$/) {
161         $no_act= 1;
162     } else {
163         die "unknown option $_\n";
164     }
165 }
166
167 for $h (@ARGV) { $wanthost{$h}= 1; }    
168
169 open CF,"< $configfile" or die "$configfile: $!";
170
171 sub fetchfile (\%$) {
172     my ($ary_ref,$get_str) = @_;
173
174     undef %$ary_ref;
175     open G,"$get_str" or die "$get_str: $!";
176     while (<G>) {
177         chomp;
178         m/^([^:]+)\:/ or die "$ch_name: $get_str:$.: $_ ?\n";
179         $ary_ref->{$1}= [ split(/\:/,$_,-1) ];
180     }
181     close G; $? and die "$ch_name: $get_str: exit code $?\n";
182 }
183
184 sub fetchownfile (\@$$) {
185     my ($ary_ref,$fn_str,$lock_str) = @_;
186     die "$configfile:$.: lockfile name for $fn_str not".
187         " defined (use lockpasswd/lockgroup)\n" unless length $lock_str;
188     if ($lock_str ne '/dev/null' && !$no_act) {
189         $lock_str= "$fn_str$lock_str" unless $lock_str =~ m,^/,;
190         link $fn_str,$lock_str or die "cannot lock $fn_str by creating $lock_str: $!\n";
191         push @unlocks,$lock_str;
192     }
193     open O,"$fn_str" or die "$fn_str: $!";
194     while (<O>) {
195         chomp;
196         push @$ary_ref, [ split(/\:/,$_,-1) ];
197     }
198     close O or die "$fn_str: $!";
199 }
200
201 sub diag ($) {
202     print "$diagstr: $_[0]\n" or die $!;
203 }
204
205 sub regroupglobs () {
206     $nogroups= (@groupglobs == 1 &&
207                 $groupglobs[0]->[0] eq '.*' &&
208                 !$groupglobs[0]->[1]);
209     $ggfunc= "sub wantsyncgroup {\n  \$_= \$_[0];\n  return\n";
210     for $e (@groupglobs) { $ggfunc.= "    m/^$e->[0]\$/ ? $e->[1] :\n"; }
211     $ggfunc.= "    die;\n};\n1;\n";
212 #print STDERR "$ggfunc\n";
213     eval $ggfunc or die "$ggfunc // $@";
214 }
215
216 sub fetchown () {
217     if (!$own_fetchedpasswd) {
218         fetchownfile(@ownpasswd,'/etc/passwd',$ch_lockpasswd);
219         if (defined stat('/etc/shadow')) {
220             $own_haveshadow= 1;
221             $own_fetchedshadow= 1;
222             fetchownfile(@ownshadow,'/etc/shadow','/dev/null');
223         } elsif ($! == &ENOENT) {
224             $own_haveshadow= 0;
225         } else {
226             die "unable to check for /etc/shadow: $!\n";
227         }
228         $own_fetchedpasswd= 1;
229     }
230     if (!$own_fetchedgroup) {
231         fetchownfile(@owngroup,'/etc/group',$ch_lockgroup);
232         $own_fetchedgroup= 1;
233     }   
234 #print STDERR "fetchown() -> $#ownpasswd $#owngroup\n";
235 }
236
237 sub checkuid ($$) {
238     my ($useuid,$foruser) = @_;
239     for $e (@ownpasswd) {
240         if ($e->[0] ne $foruser && $e->[2] == $useuid) {
241             diag("uid clash with $e->[0] (uid $e->[2])");
242             return 0;
243         }
244     }
245     return 1;
246 }
247
248 sub copyfield ($$$$) {
249     my ($file,$entry,$field,$value) = @_;
250     eval "\$ary_ref= \\\@own$file; 1;" or die $@;
251 #print STDERR "copyfield($file,$entry,$field,$value)\n";
252     for $e (@$ary_ref) {
253 #print STDERR "copyfield($file,$entry,$field,$value) $e->[0] $e->[field] ".join(':',@$e)."\n";
254         next unless $e->[0] eq $entry;
255         next if $e->[$field] eq $value;
256         $e->[$field]= $value;
257         eval "\$modified$file= 1; 1;" or die $@;
258     }
259 }
260
261 sub fetchpasswd () {
262     return if $ch_fetchedpasswd;
263     die "$configfile:$.: getpasswd not specified for host $ch_name\n"
264         unless length $ch_getpasswd;
265     undef %remshadow;
266     fetchfile(%rempasswd,"$ch_getpasswd |");
267     if (length $ch_getshadow) {
268         fetchfile(%remshadow,"$ch_getshadow |");
269         for $k (keys %rempasswd) {
270             $rempasswd{$k}->[1]= 'xx' unless length $rempasswd{$k}->[1];
271         }
272         for $k (keys %remshadow) {
273             next unless exists $rempasswd{$k};
274             $rempasswd{$k}->[1]= $remshadow{$k}->[1];
275         }
276     }
277 }
278
279 sub fetchgroup () {
280     return if $ch_fetchedgroup;
281     die "$configfile:$.: getgroup not specified for host $ch_name\n"
282         unless length $ch_getgroup;
283     fetchfile(%remgroup,"$ch_getgroup |");
284 }
285
286 sub syncusergroup ($$) {
287     my ($lu,$luid) = @_;
288
289     return 1 if !$opt_usergroups;
290 #print STDERR "syncusergroup($lu,$luid)\n";
291     $ugfound=0;
292     
293     for $e (@owngroup) {
294         $samename= $e->[0] eq $lu;
295         $sameid= $e->[2] eq $luid;
296         next unless $samename || $sameid;
297         if (!$samename || !$sameid) {
298             diag("local group $e->[0] ($e->[2]) mismatch vs. local user $lu ($luid)");
299             return 0;
300         }
301         if ($ugfound) {
302             diag("per-user group $lu ($luid) duplicated");
303             return 0;
304         }
305         $ugfound=1;
306     }
307
308     return 1 if $ugfound;
309
310     if (!length $opt_createuser) {
311         diag("account creation not enabled, not creating per-user group");
312         return 0;
313     }
314     push @owngroup, [ $lu,'x',$luid,'' ];
315     $modifiedgroup= 1;
316     return 1;
317 }
318     
319 sub syncuser ($$) {
320     my ($lu,$ru) = @_;
321
322 #print STDERR "syncuser($lu,$ru)\n";
323     next unless $ch_doinghost;
324     return if $doneuser{$lu}++;
325     return if !length $ru;
326     $diagstr= "user $lu from $ch_name!$ru";
327
328     fetchown();
329 #print STDERR "syncuser($lu,$ru) doing\n";
330     fetchpasswd();
331
332     if (!$rempasswd{$ru}) { diag("no remote entry"); return; }
333     if (length $ch_getshadow && exists $remshadow{$ru} && length $remshadow{$ru}->[7]) {
334         diag("remote account disabled in shadow");
335         return;
336     }
337
338     if (!grep($_->[0] eq $lu, @ownpasswd)) {
339         if (!length $opt_createuser) { diag("account creation not enabled"); return; }
340         if ($no_act) { diag("-n specified; not creating account"); return; }
341
342         if ($opt_sameuid) {
343             $useuid= $rempasswd{$ru}->[2];
344         } else {
345             length $ch_uidmin or die "no uidmin specified, cannot create users";
346             length $ch_uidmax or die "no uidmax specified, cannot create users";
347             $ch_uidmin<$ch_uidmax or die "uidmin>=uidmax specified, cannot create users";
348         
349             $useuid= $ch_uidmin;
350             for $e (@ownpasswd, @owngroup) {
351                 $tuid= $e->[2]; next if $tuid<$useuid || $tuid>$ch_uidmax;
352                 if ($tuid==$ch_uidmax) {
353                     diag("uid/gid $ch_uidmax used, cannot create users");
354                     return;
355                 }
356                 $useuid= $tuid+1;
357             }
358         }
359         
360         @newpwent= ($lu,'x',$useuid,$useuid,$rempasswd{$ru}->[4],
361                     "$ch_homebase/$lu",$rempasswd{$ru}->[6]);
362         
363         defined($c= open CU,"-|") or die $!;
364         if (!$c) {
365             @unlocks= ();
366             defined($c2= open STDIN,"-|") or die $!;
367             if (!$c2) {
368                 print STDOUT join(':',@newpwent),"\n" or die $!;
369                 exit 0;
370             }
371             for ($i=0; $i<@envs_passwd; $i++) {
372                 next if $envs_passwd[$i] eq 'x';
373                 $ENV{"SYNCUSER_CREATE_$envs_passwd[$i]"}= $newpwent[$i];
374             }
375             exec $opt_createuser; die "$configfile:$.: ($lu): $opt_createuser: $!\n";
376         }
377         $newpwent= <CU>;
378         close CU; $? and die "$configfile:$.: ($lu): $opt_createuser: code $?\n";
379         chomp $newpwent;
380         if (length $newpwent) {
381             if ($newpwent !~ m/\:/) { diag("creation script demurred"); return; }
382             @newpwent= split(/\:/,$newpwent,-1);
383         }
384         die "$opt_createuser: bad output: $_\n" if @newpwent!=7 or $newpwent[0] ne $lu;
385         checkuid($newpwent[2],$lu) or return;
386         if ($own_haveshadow) {
387             push(@ownshadow,[ $lu, $newpwent[1], $cdays, 0,99999,7,'','','' ]);
388             $newpwent[1]= 'x';
389             $modifiedshadow= 1;
390         }
391         syncusergroup($lu,$newpwent[2]) or return;
392         push @ownpasswd,[ @newpwent ];
393         $modifiedpasswd= 1;
394     }
395
396     for $e (@ownpasswd) {
397         next unless $e->[0] eq $lu;
398         syncusergroup($lu,$e->[2]) or return;
399     }
400
401     $ruid= $rempasswd{$ru}->[2];
402     $rgid= $rempasswd{$ru}->[3];
403     if ($opt_sameuid && checkuid($ruid,$lu)) {
404         for $e (@ownpasswd) {
405             next unless $e->[0] eq $lu;
406             $luid= $e->[2]; $lgid= $e->[3];
407             die "$diagstr: local uid $luid, remote uid $ruid\n" if $luid ne $ruid;
408             die "$diagstr: local gid $lgid, remote gid $rgid\n" if $lgid ne $rgid;
409         }
410     }
411
412 #print STDERR "syncuser($lu,$ru) exists $own_haveshadow\n";
413     if ($own_haveshadow && grep($_->[0] eq $lu, @ownshadow)) {
414 #print STDERR "syncuser($lu,$ru) shadow $rempasswd{$ru}->[1]\n";
415         copyfield('shadow',$lu,1, $rempasswd{$ru}->[1]);
416     } else {
417 #print STDERR "syncuser($lu,$ru) passwd $rempasswd{$ru}->[1]\n";
418         copyfield('passwd',$lu,1, $rempasswd{$ru}->[1]);
419     }
420     copyfield('passwd',$lu,4, $rempasswd{$ru}->[4]); # comment
421     copyfield('passwd',$lu,6, $rempasswd{$ru}->[6]); # shell
422
423     if (!$nogroups) {
424         for $e (@owngroup) {
425             $tgroup= $e->[0];
426 #print STDERR "syncuser($lu,$ru) group $tgroup\n";
427             next unless &wantsyncgroup($tgroup);
428 #print STDERR "syncuser($lu,$ru) group $tgroup yes\n";
429             fetchgroup();
430             if (!exists $remgroup{$tgroup}) {
431                 diag("group $tgroup: not on remote host");
432                 next;
433             }
434             $inremote= grep($_ eq $ru, split(/\,/,$remgroup{$tgroup}->[3]));
435             $cusers= $e->[3]; $inlocal= grep($_ eq $lu, split(/\,/,$cusers));
436             if ($inremote && !$inlocal) {
437                 $cusers.= ',' if length $cusers;
438                 $cusers.= $lu;
439             } elsif ($inlocal && !$inremote) {
440                 $cusers= join(',', grep($_ ne $lu, split(/\,/, $cusers)));
441             } else {
442                 next;
443             }
444             $e->[3]= $cusers;
445             $modifiedgroup= 1;
446         }
447     }
448 }
449
450 sub banner () {
451     return if $bannerdone;
452     print "\n" or die $!; system 'date'; $? and die $?;
453     $bannerdone= 1;
454 }
455
456 sub finish () {
457     for $h (keys %wanthost) {
458         die "host $h not in config file\n" if $wanthost{$h};
459     }
460     
461     umask 077;
462     for $file (qw(passwd shadow group)) {
463         eval "\$modified= \$modified$file; \$data_ref= \\\@own$file;".
464             " \$fetched= \$own_fetched$file; 1;" or die $@;
465         next if !$modified;
466         die $file unless $fetched;
467         banner();
468         $newfile= $no_act ? "$file.new" : "/etc/$file.new";
469         open NF,"> $newfile";
470         for $e (@$data_ref) {
471             print NF join(':',@$e),"\n" or die $!;
472         }
473         close NF or die $!;
474         system "diff -U0 /etc/$file $newfile"; $?==256 or die $?;
475         if (!$no_act) {
476             if ($file eq 'shadow') {
477                 system "chown root.shadow $newfile"; $? and die $?;
478                 chmod 0640, $newfile or die $!;
479             } else {
480                 chown 0,0, $newfile or die $!;
481                 chmod 0644, $newfile or die $!;
482             }
483             rename $newfile, "/etc/$file" or die $!;
484         }
485     }
486     exit 0;
487 }
488
489 while (<CF>) {
490     chomp;
491     next if m/^\#/ || !m/\S/;
492     s/^\s*//; s/\s*$//;
493     finish() if m/^end$/;
494     if (m/^host\s+(\S+)$/) {
495         $ch_name= $1;
496         $ch_getpasswd= $ch_getgroup= $ch_getshadow= '';
497         $ch_fetchedpasswd= $ch_fetchedgroup;
498         if (!@ARGV) {
499             $ch_doinghost= 1;
500         } elsif (exists $wanthost{$ch_name}) {
501             $wanthost{$ch_name}= 0;
502             $ch_doinghost= 1;
503         } else {
504             $ch_doinghost= 0;
505         }
506     } elsif (m/^(getpasswd|getshadow|getgroup)\s+(.*\S)$/) {
507         eval "\$ch_$1= \$2; 1;" or die $@;
508     } elsif (m/^(lockpasswd|lockgroup)\s+(\S+)$/) {
509         eval "\$ch_$1= \$2; 1;" or die $@;
510     } elsif (m,^(homebase)\s+(/\S+)$,) {
511         eval "\$ch_$1= \$2; 1;" or die $@;
512     } elsif (m/^(uidmin|uidmax)\s+(\d+)$/ && $2>0) {
513         eval "\$ch_$1= \$2; 1;" or die $@;
514     } elsif (m/^createuser$/) {
515         $opt_createuser= $def_createuser;
516     } elsif (m/^nocreateuser$/) {
517         $opt_createuser= '';
518     } elsif (m/^createuser\s+(\S+)$/) {
519         $opt_createuser= $1;
520     } elsif (m/^logfile\s+(.*\S)$/) {
521         if ($no_act) {
522             print "would log to $1\n" or die $!;
523         } else {
524             open STDOUT,">> $1" or die "$1: $!"; $|=1;
525         }
526     } elsif (m/^(no|)(sameuid|usergroups)$/) {
527         eval "\$opt_$2= ".($1 eq 'no' ? 0 : 1)."; 1;" or die $@;
528     } elsif (m/^(no|)group\s+([-+.0-9a-zA-Z*?]+)$/) {
529         $yes= $1 eq 'no' ? 0 : 1;
530         $_= $2;
531         @groupglobs=() if $_ eq '*';
532         s/[-+._]/\\$1/g;
533         s/\*/\.\*/g;
534         s/\?/\./g;
535         unshift @groupglobs, [ $_, $yes ];
536         regroupglobs();
537     } elsif (m/^user\s+(\S+)$/) {
538         syncuser($1,$1);
539     } elsif (m/^user\s+(\S+)\s+remote\=(\S+)$/) {
540         syncuser($1,$2);
541     } elsif (m/^nouser\s+(\S+)$/) {
542         syncuser($1,'');
543     } elsif (m/^users\s+(\d+)\-(\d+)$/) {
544         $tmin= $1; $tmax= $2; $except= $3;
545         fetchpasswd();
546         for $k (keys %rempasswd) {
547             $tuid= $rempasswd{$k}->[2];
548             next if $tuid<$1 or $tuid>$2;
549             syncuser($k,$k);
550         }
551     } elsif (m/^addhere$/) {
552     } else {
553         die "$configfile:$.: unknown directive\n";
554     }
555 }
556
557 die "$configfile:$.: missing \`end', or read error\n";