chiark / gitweb /
Initial checkin, seems to sort of work.
[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 #  createuser
45 #  createuser <commandname>
46 #  nocreateuser
47 #      Specifies whether accounts found on the remote host should be
48 #      created if necessary, and what command to run to do the
49 #      creation (eg, setup of home directory).  The default is
50 #      nocreateuser.  If createuser is specified without a commandname
51 #      then sync-accounts-createuser is used.  The command is found on
52 #      the PATH if necessary.  Either sameuid, or both uidmin and
53 #      uidmax, must be specified, if accounts are to be created.
54 #
55 #  groups [!]<glob-pattern> ...
56 #      Specifies that the membership of the local groups specified
57 #      should be adjusted whenever account data for a particular user
58 #      is copied, so that the account will be a member of the affected
59 #      group locally iff it is a member of the same group on the
60 #      remote host.  The specification is read from left to right,
61 #      until a match on a glob pattern is found.  Then, the membership
62 #      is adjusted iff the glob pattern was not preceded by `!'.
63 #      THIS FEATURE IS NOT YET IMPLEMENTED.
64 #
65 # Some config file directives are per-host, and should appear before
66 # any directives which actually modify accounts:
67 #
68 #  host <shorthostname>
69 #      Starts a host's section.  This resets the per-host parameters
70 #      to the defaults.  The shorthostname need not be the host's
71 #      official name in any sense.  If sync-accounts is invoked with
72 #      host names on the command line they are compared with the
73 #      shorthostnames.
74 #
75 #  getpasswd <command>
76 #  getgroup <command>
77 #      Commands to run on the local host to get the passwd, shadow and
78 #      group data for the host in question.  getpasswd must be
79 #      specified if user data is to be transferred; getgroup must be
80 #      specified if group data is to be transferred.
81 #
82 #  getshadow <command>
83 #      Specifies that shadow file data is to be used (by default,
84 #      password information is found from the output of getpasswd).
85 #      The command should emit shadow data in the format specified by
86 #      shadow(5) on Linux.  getshadow should not be specified without
87 #      getpasswd.
88 #
89 # Some configuration file directives specify that account or group
90 # data is to transferred from the current host.  They should appear as
91 # the last thing(s) in a host section:
92 #
93 #  user <username> [remote=<remoteusername>]
94 #      Specifies that account data should be copied for local user
95 #      <username> from the remote account <remoteusername> (assumed to
96 #      be the same as <username> if not specified).  The account
97 #      password, comment field, and shell will be copied
98 #      unconditionally.  If sameuid is specified the uid will be
99 #      checked.
100 #
101 #  users <ruidmin>-<ruidmax>
102 #      Specifies that all remote users whose uid is in the given range
103 #      are to be copied to corresponding local user accounts.
104
105 use POSIX;
106
107 $configfile= '/etc/sync-accounts';
108 $def_createuser= 'sync-accounts-createuser';
109 $ch_homebase= '/home';
110
111 END {
112     for $x (@unlocks) {
113         unlink $x or warn "unable to unlock by removing $x: $!\n";
114     }
115 }
116
117 $|=1;
118 $cdays= int(time/86400);
119
120 @envs_passwd= qw(USER x UID GID COMMENT HOME SHELL);
121
122 while ($ARGV[0] =~ m/^-/) {
123     $_= shift @ARGV;
124     last if m/^--$/;
125     if (m/^-C/) {
126         $configfile= $';
127     } elsif (m/^-n$/) {
128         $no_act= 1;
129     } else {
130         die "unknown option $_\n";
131     }
132 }
133
134 open CF,"< $configfile" or die "$configfile: $!";
135
136 sub fetchfile (\%$) {
137     my ($ary_ref,$get_str) = @_;
138
139     undef %$ary_ref;
140     open G,"$get_str" or die "$get_str: $!";
141     while (<G>) {
142         chomp;
143         m/^([^:]+)\:/ or die "$ch_name: $get_str:$.: $_ ?\n";
144         $ary_ref->{$1}= [ split(/\:/,$_,-1) ];
145     }
146     close G; $? and die "$ch_name: $get_str: exit code $?\n";
147 }
148
149 sub fetchownfile (\@$$) {
150     my ($ary_ref,$fn_str,$lock_str) = @_;
151     die "$configfile:$.: lockfile name for $fn_str not".
152         " defined (use lockpasswd/lockgroup)\n" unless length $lock_str;
153     if ($lock_str ne '/dev/null' && !$no_act) {
154         $lock_str= "$fn_str$lock_str" unless $lock_str =~ m,^/,;
155         link $fn_str,$lock_str or die "cannot lock $fn_str by creating $lock_str: $!\n";
156         push @unlocks,$lock_str;
157     }
158     open O,"$fn_str" or die "$fn_str: $!";
159     while (<O>) {
160         chomp;
161         push @$ary_ref, [ split(/\:/,$_,-1) ];
162     }
163     close O or die "$fn_str: $!";
164 }
165
166 sub diag ($) {
167     print "$diagstr: $_[0]\n" or die $!;
168 }
169
170 sub fetchown () {
171     if (!$own_fetchedpasswd) {
172         fetchownfile(@ownpasswd,'/etc/passwd',$ch_lockpasswd);
173         if (defined stat('/etc/shadow')) {
174             $own_haveshadow= 1;
175             $own_fetchedshadow= 1;
176             fetchownfile(@ownshadow,'/etc/shadow','/dev/null');
177         } elsif ($! == &ENOENT) {
178             $own_haveshadow= 0;
179         } else {
180             die "unable to check for /etc/shadow: $!\n";
181         }
182         $own_fetchedpasswd= 1;
183     }
184     if (!$own_fetchedgroup) {
185         fetchownfile(@owngroup,'/etc/group',$ch_lockgroup);
186         $own_fetchedgroup= 1;
187     }   
188 #print STDERR "fetchown() -> $#ownpasswd $#owngroup\n";
189 }
190
191 sub checkuid ($$) {
192     my ($useuid,$foruser) = @_;
193     for $e (@ownpasswd) {
194         if ($e->[0] ne $foruser && $e->[2] == $useuid) {
195             diag("uid clash with $e->[0] (uid $e->[2])");
196             return 0;
197         }
198     }
199     return 1;
200 }
201
202 sub copyfield ($$$$) {
203     my ($file,$entry,$field,$value) = @_;
204     eval "\$ary_ref= \\\@own$file; 1;" or die $@;
205 #print STDERR "copyfield($file,$entry,$field,$value)\n";
206     for $e (@$ary_ref) {
207 #print STDERR "copyfield($file,$entry,$field,$value) $e->[0] $e->[field] ".join(':',@$e)."\n";
208         next unless $e->[0] eq $entry;
209         next if $e->[$field] eq $value;
210         $e->[$field]= $value;
211         eval "\$modified$file= 1; 1;" or die $@;
212     }
213 }
214
215 sub fetchpasswd () {
216     return if $ch_fetchedpasswd;
217     die "$configfile:$.: getpasswd not specified for host $ch_name\n"
218         unless length $ch_getpasswd;
219     undef %remshadow;
220     fetchfile(%rempasswd,"$ch_getpasswd |");
221     if (length $ch_getshadow) {
222         fetchfile(%remshadow,"$ch_getshadow |");
223         for $k (keys %rempasswd) {
224             $rempasswd{$k}->[1]= 'xx' unless length $rempasswd{$k}->[1];
225         }
226         for $k (keys %remshadow) {
227             next unless exists $rempasswd{$k};
228             $rempasswd{$k}->[1]= $remshadow{$k}->[1];
229         }
230     }
231 }
232
233 sub syncuser ($$) {
234     my ($lu,$ru) = @_;
235
236     next unless $ch_doinghost;
237     $diagstr= "user $lu from $ch_name!$ru";
238
239     fetchown();
240 #print STDERR "syncuser($lu,$ru)\n";
241     fetchpasswd();
242
243     if (!$rempasswd{$ru}) { diag("no remote entry"); return; }
244     if (length $ch_getshadow && exists $remshadow{$ru} && length $remshadow{$ru}->[7]) {
245         diag("remote account disabled in shadow");
246         return;
247     }
248     
249     if (!grep($_->[0] eq $lu, @ownpasswd)) {
250         if (!length $opt_createuser) { diag("account creation not enabled"); return; }
251         if ($no_act) { diag("-n specified; not creating account"); return; }
252
253         if ($opt_sameuid) {
254             $useuid= $rempasswd{$ru}->[2];
255         } else {
256             length $ch_uidmin or die "no uidmin specified, cannot create users";
257             length $ch_uidmax or die "no uidmax specified, cannot create users";
258             $ch_uidmin<$ch_uidmax or die "uidmin>=uidmax specified, cannot create users";
259         
260             $useuid= $ch_uidmin;
261             for $e (@ownpasswd, @owngroup) {
262                 $tuid= $e->[2]; next if $tuid<$useuid || $tuid>$ch_uidmax;
263                 if ($tuid==$ch_uidmax) {
264                     diag("uid/gid $ch_uidmax used, cannot create users");
265                     return;
266                 }
267                 $useuid= $tuid+1;
268             }
269         }
270         
271         @newpwent= ($lu,'x',$useuid,$useuid,$rempasswd{$ru}->[4],
272                     "$ch_homebase/$lu",$rempasswd{$ru}->[6]);
273         
274         defined($c= open CU,"-|") or die $!;
275         if (!$c) {
276             @unlocks= ();
277             defined($c2= open STDIN,"-|") or die $!;
278             if (!$c2) {
279                 print STDOUT join(':',@newpwent),"\n" or die $!;
280                 exit 0;
281             }
282             for ($i=0; $i<@envs_passwd; $i++) {
283                 next if $envs_passwd[$i] eq 'x';
284                 $ENV{"SYNCUSER_CREATE_$envs_passwd[$i]"}= $newpwent[$i];
285             }
286             exec $opt_createuser; die "$configfile:$.: ($lu): $opt_createuser: $!\n";
287         }
288         $newpwent= <CU>;
289         close CU; $? and die "$configfile:$.: ($lu): $opt_createuser: code $?\n";
290         chomp $newpwent;
291         if (length $newpwent) {
292             if ($newpwent !~ m/\:/) { diag("creation script demurred"); return; }
293             @newpwent= split(/\:/,$newpwent,-1);
294         }
295         die "$opt_createuser: bad output: $_\n" if @newpwent!=7 or $newpwent[0] ne $lu;
296         checkuid($newpwent[2],$lu) or return;
297         if ($own_haveshadow) {
298             push(@ownshadow,[ $lu, $newpwent[1], $cdays, 0,99999,7,'','' ]);
299             $newpwent[1]= 'x';
300             $modifiedshadow= 1;
301         }
302         push @ownpasswd,[ @newpwent ];
303         $modifiedpasswd= 1;
304     }
305 #print STDERR "syncuser($lu,$ru) exists $own_haveshadow\n";
306     if ($own_haveshadow && grep($_->[0] eq $lu, @ownshadow)) {
307 #print STDERR "syncuser($lu,$ru) shadow $rempasswd{$ru}->[1]\n";
308         copyfield('shadow',$lu,1, $rempasswd{$ru}->[1]);
309     } else {
310 #print STDERR "syncuser($lu,$ru) passwd $rempasswd{$ru}->[1]\n";
311         copyfield('passwd',$lu,1, $rempasswd{$ru}->[1]);
312     }
313     copyfield('passwd',$lu,4, $rempasswd{$ru}->[4]); # comment
314     copyfield('passwd',$lu,6, $rempasswd{$ru}->[6]); # shell
315     if ($opt_sameuid && checkuid($rempasswd{$ru}->[2],$lu)) {
316         for $e (@ownpasswd) {
317             next unless $e->[0] eq $lu;
318             $lid= $e->[2]; $rid= $rempasswd{$ru}->[2];
319             die "$diagstr: local uid $lid, remote uid $rid\n" if $lid ne $rid;
320             $lid= $e->[3]; $rid= $rempasswd{$ru}->[3];
321             die "$diagstr: local gid $lid, remote gid $rid\n" if $lid ne $rid;
322         }
323     }
324 }
325
326 sub banner () {
327     return if $bannerdone;
328     print "\n" or die $!; system 'date'; $? and die $?;
329     $bannerdone= 1;
330 }
331
332 sub finish () {
333     for $file (qw(passwd shadow group)) {
334         eval "\$modified= \$modified$file; \$data_ref= \\\@own$file;".
335             " \$fetched= \$own_fetched$file; 1;" or die $@;
336         next if !$modified;
337         die $file unless $fetched;
338         banner();
339         $newfile= $no_act ? "$file.new" : "/etc/$file.new";
340         open NF,"> $newfile";
341         for $e (@$data_ref) {
342             print NF join(':',@$e),"\n" or die $!;
343         }
344         close NF or die $!;
345         system "diff -U0 /etc/$file $newfile"; $?==256 or die $?;
346         if (!$no_act) {
347             chown 0,0, $newfile or die $!;
348             chmod 0644, $newfile or die $!;
349             rename $newfile, "/etc/$file" or die $!;
350         }
351     }
352     exit 0;
353 }
354
355 while (<CF>) {
356     chomp;
357     next if m/^\#/ || !m/\S/;
358     s/^\s*//; s/\s*$//;
359     finish() if m/^end$/;
360     if (m/^host\s+(\S+)$/) {
361         $ch_name= $1;
362         $ch_getpasswd= $ch_getgroup= $ch_getshadow= '';
363         $ch_fetchedpasswd= $ch_fetchedgroup;
364         $ch_doinghost= !@ARGV || grep($_ eq $ch_name, @ARGV);
365     } elsif (m/^(getpasswd|getshadow|getgroup)\s+(.*\S)$/) {
366         eval "\$ch_$1= \$2; 1;" or die $@;
367     } elsif (m/^(lockpasswd|lockgroup)\s+(\S+)$/) {
368         eval "\$ch_$1= \$2; 1;" or die $@;
369     } elsif (m,^(homebase)\s+(/\S+)$,) {
370         eval "\$ch_$1= \$2; 1;" or die $@;
371     } elsif (m/^(uidmin|uidmax)\s+(\d+)$/ && $2>0) {
372         eval "\$ch_$1= \$2; 1;" or die $@;
373     } elsif (m/^createuser$/) {
374         $opt_createuser= $def_createuser;
375     } elsif (m/^nocreateuser$/) {
376         $opt_createuser= '';
377     } elsif (m/^createuser\s+(\S+)$/) {
378         $opt_createuser= $1;
379     } elsif (m/^logfile\s+(.*\S)$/) {
380         if ($no_act) {
381             print "would log to $1\n" or die $!;
382         } else {
383             open STDOUT,">> $1" or die "$1: $!"; $|=1;
384         }
385     } elsif (m/^(no|)(sameuid)$/) {
386         eval "\$opt_$2= ".($1 eq 'no' ? 0 : 1)."; 1;" or die $@;
387     } elsif (m/^user\s+(\S+)$/) {
388         syncuser($1,$1);
389     } elsif (m/^groups\s+(.*\S)$/) {
390     } elsif (m/^user\s+(\S+)\s+remote\=(\S+)$/) {
391         syncuser($1,$2);
392     } elsif (m/^users\s+(\d+)\-(\d+)$/) {
393         $tmin= $1; $tmax= $2;
394         fetchpasswd();
395         for $k (keys %rempasswd) {
396             $tuid= $rempasswd{$k}->[2];
397             next if $tuid<$1 or $tuid>$2;
398             syncuser($k,$k);
399         }
400     } else {
401         die "$configfile:$.: unknown directive\n";
402     }
403 }
404
405 die "$configfile:$.: missing \`end', or read error\n";