2 # $Id: sync-accounts,v 1.11 1999-01-03 02:19:27 ian Exp $
3 # usage: sync-accounts [-n] [-C<config-file>] [<host> ...]
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
10 # The config file consists of directives, one per line. Leading and
11 # trailing whitespace, blank lines and lines starting # are ignored.
13 # Some config file directives apply globally and should appear first:
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 `/'. If set to /dev/null no locking is done.
22 # Append log messages to <filename> instead of stdout.
23 # Errors still go to stderr.
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
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>.
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'
49 # Specifies whether local accounts are supposed to have
50 # corresponding groups, or all be part of a particular group. If
51 # usergroups is set, when a new account is created, the
52 # corresponding per-user group will be created as well, and
53 # per-user groups are created for existing accounts if necessary
54 # (if account creation is enabled). If the gid or group name for
55 # a per-user group is already taken for a different group name or
56 # gid this will be logged, and processing of that account will be
57 # inhibited, but it is not a fatal error. If defaultgid is used,
58 # then newly-created accounts will be made a part of that group,
59 # and the groups of existing accounts will be left alone. If
60 # nousergroups is specified then no new accounts can be created,
61 # and existing accounts' groups will be left alone. The default
65 # createuser <commandname>
67 # Specifies whether accounts found on the remote host should be
68 # created if necessary, and what command to run to do the
69 # creation (eg, setup of home directory). The default is
70 # nocreateuser. If createuser is specified without a commandname
71 # then sync-accounts-createuser is used. The command is found on
72 # the PATH if necessary. Either sameuid, or both uidmin and
73 # uidmax, must be specified, if accounts are to be created.
75 # The command (which will be run with sh -c) must at least create
76 # the new account's home directory. The passwd and group entries
77 # will not have been set up. The following environment variables
78 # will be set, giving details about the account to be created:
79 # SYNCACCOUNT_CREATE_USER
80 # SYNCACCOUNT_CREATE_UID
81 # SYNCACCOUNT_CREATE_GID
82 # SYNCACCOUNT_CREATE_COMMENT
83 # SYNCACCOUNT_CREATE_HOME
84 # SYNCACCOUNT_CREATE_SHELL
85 # If it chooses, the script may modify the password entry which
86 # will be added to the system, by outputting a replacement
87 # password file entry. (The password field of that is ignored.)
88 # If the script outputs a line which does not contain a : then
89 # the account will not be created after all.
91 # group <glob-pattern>
92 # nogroup <glob-pattern>
93 # Specifies that the membership of the local groups specified
94 # should be adjusted or not adjusted whenever account data for a
95 # particular user is copied, so that the account will be a member
96 # of the affected group locally iff it is a member of the same
97 # group on the remote host. The most recently-encountered
98 # glob-pattern for a particular group takes effect. The default
101 # Some config file directives are per-host, and should appear before
102 # any directives which actually modify accounts:
104 # host <shorthostname>
105 # Starts a host's section. This resets the per-host parameters
106 # to the defaults. The shorthostname need not be the host's
107 # official name in any sense. If sync-accounts is invoked with
108 # host names on the command line they are compared with the
111 # getpasswd <command>
113 # Commands to run on the local host to get the passwd, shadow and
114 # group data for the host in question. getpasswd must be
115 # specified if user data is to be transferred; getgroup must be
116 # specified if group data is to be transferred.
118 # getshadow <command>
119 # Specifies that shadow file data is to be used (by default,
120 # password information is found from the output of getpasswd).
121 # The command should emit shadow data in the format specified by
122 # shadow(5) on Linux. getshadow should not be specified without
125 # Some configuration file directives specify that account data is to
126 # transferred from the current host. They should appear as the last
127 # thing(s) in a host section:
129 # user <username> [remote=<remoteusername>]
130 # Specifies that account data should be copied for local user
131 # <username> from the remote account <remoteusername> (assumed to
132 # be the same as <username> if not specified). The account
133 # password, comment field, and shell will be copied
134 # unconditionally. If sameuid is specified the uid will be
137 # users <ruidmin>-<ruidmax>
138 # Specifies that all remote users whose uid is in the given range
139 # are to be copied to corresponding local user accounts.
142 # Specifies that data for <username> is _not_ to be copied, even
143 # if subsequent user or users directives suggest that it should
146 # (A note is made when a `user', `users' or `nouser' directive is
147 # encountered for a particular account, and no subsequent directives
148 # for that account will take effect.)
151 # This directive has no effect on `sync-accounts'. However, it
152 # is used as a placeholder by `grab-account': new accounts for
153 # creation are inserted just before `addhere'.
155 # Finally, the config file must finish with:
161 $configfile= '/etc/sync-accounts';
162 $def_createuser= 'sync-accounts-createuser';
163 $ch_homebase= '/home';
164 $defaultgid= -1; # -1 => usergroups; -2 => nousergroups
165 @groupglobs= [ '.*', 0 ];
170 unlink $x or warn "unable to unlock by removing $x: $!\n";
175 $cdays= int(time/86400);
177 @envs_passwd= qw(USER x UID GID COMMENT HOME SHELL);
179 while ($ARGV[0] =~ m/^-/) {
191 die "unknown option $_\n";
195 for $h (@ARGV) { $wanthost{$h}= 1; }
197 open CF,"< $configfile" or die "$configfile: $!";
199 sub fetchfile (\%$) {
200 my ($ary_ref,$get_str) = @_;
203 open G,"$get_str" or die "$get_str: $!";
206 m/^([^:]+)\:/ or die "$ch_name: $get_str:$.: $_ ?\n";
207 $ary_ref->{$1}= [ split(/\:/,$_,-1) ];
209 close G; $? and die "$ch_name: $get_str: exit code $?\n";
212 sub fetchownfile (\@$$) {
213 my ($ary_ref,$fn_str,$lock_str) = @_;
214 die "$configfile:$.: lockfile name for $fn_str not".
215 " defined (use lockpasswd/lockgroup)\n" unless length $lock_str;
216 if ($lock_str ne '/dev/null' && !$no_act) {
217 $lock_str= "$fn_str$lock_str" unless $lock_str =~ m,^/,;
218 link $fn_str,$lock_str or die "cannot lock $fn_str by creating $lock_str: $!\n";
219 push @unlocks,$lock_str;
221 open O,"$fn_str" or die "$fn_str: $!";
224 push @$ary_ref, [ split(/\:/,$_,-1) ];
226 close O or die "$fn_str: $!";
230 print "$diagstr: $_[0]\n" or die $!;
233 sub regroupglobs () {
234 $nogroups= (@groupglobs == 1 &&
235 $groupglobs[0]->[0] eq '.*' &&
236 !$groupglobs[0]->[1]);
237 $ggfunc= "sub wantsyncgroup {\n \$_= \$_[0];\n return\n";
238 for $e (@groupglobs) { $ggfunc.= " m/^$e->[0]\$/ ? $e->[1] :\n"; }
239 $ggfunc.= " die;\n};\n1;\n";
240 #print STDERR "$ggfunc\n";
241 eval $ggfunc or die "$ggfunc // $@";
245 if (!$own_fetchedpasswd) {
246 fetchownfile(@ownpasswd,'/etc/passwd',$ch_lockpasswd);
247 if (defined stat('/etc/shadow')) {
249 $own_fetchedshadow= 1;
250 fetchownfile(@ownshadow,'/etc/shadow','/dev/null');
251 } elsif ($! == &ENOENT) {
254 die "unable to check for /etc/shadow: $!\n";
256 $own_fetchedpasswd= 1;
258 if (!$own_fetchedgroup) {
259 fetchownfile(@owngroup,'/etc/group',$ch_lockgroup);
260 $own_fetchedgroup= 1;
262 #print STDERR "fetchown() -> $#ownpasswd $#owngroup\n";
266 my ($useuid,$foruser) = @_;
267 for $e (@ownpasswd) {
268 if ($e->[0] ne $foruser && $e->[2] == $useuid) {
269 diag("uid clash with $e->[0] (uid $e->[2])");
276 sub copyfield ($$$$) {
277 my ($file,$entry,$field,$value) = @_;
278 eval "\$ary_ref= \\\@own$file; 1;" or die $@;
279 #print STDERR "copyfield($file,$entry,$field,$value)\n";
281 #print STDERR "copyfield($file,$entry,$field,$value) $e->[0] $e->[field] ".join(':',@$e)."\n";
282 next unless $e->[0] eq $entry;
283 next if $e->[$field] eq $value;
284 $e->[$field]= $value;
285 eval "\$modified$file= 1; 1;" or die $@;
290 return if $ch_fetchedpasswd;
291 die "$configfile:$.: getpasswd not specified for host $ch_name\n"
292 unless length $ch_getpasswd;
294 fetchfile(%rempasswd,"$ch_getpasswd |");
295 if (length $ch_getshadow) {
296 fetchfile(%remshadow,"$ch_getshadow |");
297 for $k (keys %rempasswd) {
298 $rempasswd{$k}->[1]= 'xx' unless length $rempasswd{$k}->[1];
300 for $k (keys %remshadow) {
301 next unless exists $rempasswd{$k};
302 $rempasswd{$k}->[1]= $remshadow{$k}->[1];
308 return if $ch_fetchedgroup;
309 die "$configfile:$.: getgroup not specified for host $ch_name\n"
310 unless length $ch_getgroup;
311 fetchfile(%remgroup,"$ch_getgroup |");
314 sub syncusergroup ($$) {
317 return 1 if $defaultgid != -1;
318 #print STDERR "syncusergroup($lu,$luid)\n";
322 $samename= $e->[0] eq $lu;
323 $sameid= $e->[2] eq $luid;
324 next unless $samename || $sameid;
325 if (!$samename || !$sameid) {
326 diag("local group $e->[0] ($e->[2]) mismatch vs. local user $lu ($luid)");
330 diag("per-user group $lu ($luid) duplicated");
336 return 1 if $ugfound;
338 if (!length $opt_createuser) {
339 diag("account creation not enabled, not creating per-user group");
342 push @owngroup, [ $lu,'x',$luid,'' ];
349 return if $hostheaddone eq $th;
350 print "\n\n" or die $! if length $hostheaddone;
351 print "==== $th ====\n" or die $!;
358 #print STDERR "syncuser($lu,$ru)\n";
359 next unless $ch_doinghost;
360 return if $doneuser{$lu}++;
361 return if !length $ru;
366 for $e (@ownpasswd) {
367 next unless $e->[0] eq $lu;
368 hosthead("from $ch_name");
369 print ($lu eq $ru ? " $lu" : " $lu($ru)") or die $!;
370 print "<DUPLICATE>" if $displaydone{$lu}++;
375 $diagstr= "user $lu from $ch_name!$ru";
377 #print STDERR "syncuser($lu,$ru) doing\n";
380 if (!$rempasswd{$ru}) { diag("no remote entry"); return; }
381 if (length $ch_getshadow && exists $remshadow{$ru} && length $remshadow{$ru}->[7]) {
382 diag("remote account disabled in shadow");
386 if (!grep($_->[0] eq $lu, @ownpasswd)) {
387 if (!length $opt_createuser) { diag("account creation not enabled"); return; }
388 if ($no_act) { diag("-n specified; not creating account"); return; }
391 $useuid= $rempasswd{$ru}->[2];
392 $usegid= $rempasswd{$ru}->[3];
394 die "nousergroups specified, cannot create users\n" if $defaultgid==-2;
395 length $ch_uidmin or die "no uidmin specified, cannot create users\n";
396 length $ch_uidmax or die "no uidmax specified, cannot create users\n";
397 $ch_uidmin<$ch_uidmax or die "uidmin>=uidmax, cannot create users\n";
400 for $e ($defaultgid==-1 ? (@ownpasswd, @owngroup) : (@ownpasswd)) {
401 $tuid= $e->[2]; next if $tuid<$useuid || $tuid>$ch_uidmax;
402 if ($tuid==$ch_uidmax) {
403 diag("uid (or gid?) $ch_uidmax used, cannot create users");
408 $usegid= $defaultgid==-1 ? $useuid : $defaultgid;
411 @newpwent= ($lu,'x',$useuid,$usegid,$rempasswd{$ru}->[4],
412 "$ch_homebase/$lu",$rempasswd{$ru}->[6]);
414 defined($c= open CU,"-|") or die $!;
417 defined($c2= open STDIN,"-|") or die $!;
419 print STDOUT join(':',@newpwent),"\n" or die $!;
422 for ($i=0; $i<@envs_passwd; $i++) {
423 next if $envs_passwd[$i] eq 'x';
424 $ENV{"SYNCUSER_CREATE_$envs_passwd[$i]"}= $newpwent[$i];
426 exec $opt_createuser; die "$configfile:$.: ($lu): $opt_createuser: $!\n";
429 close CU; $? and die "$configfile:$.: ($lu): $opt_createuser: code $?\n";
431 if (length $newpwent) {
432 if ($newpwent !~ m/\:/) { diag("creation script demurred"); return; }
433 @newpwent= split(/\:/,$newpwent,-1);
435 die "$opt_createuser: bad output: $_\n" if @newpwent!=7 or $newpwent[0] ne $lu;
436 checkuid($newpwent[2],$lu) or return;
437 if ($own_haveshadow) {
438 push(@ownshadow,[ $lu, $newpwent[1], $cdays, 0,99999,7,'','','' ]);
442 syncusergroup($lu,$newpwent[2]) or return;
443 push @ownpasswd,[ @newpwent ];
447 for $e (@ownpasswd) {
448 next unless $e->[0] eq $lu;
449 syncusergroup($lu,$e->[2]) or return;
452 $ruid= $rempasswd{$ru}->[2];
453 $rgid= $rempasswd{$ru}->[3];
454 if ($opt_sameuid && checkuid($ruid,$lu)) {
455 for $e (@ownpasswd) {
456 next unless $e->[0] eq $lu;
457 $luid= $e->[2]; $lgid= $e->[3];
458 die "$diagstr: local uid $luid, remote uid $ruid\n" if $luid ne $ruid;
459 die "$diagstr: local gid $lgid, remote gid $rgid\n" if $lgid ne $rgid;
463 #print STDERR "syncuser($lu,$ru) exists $own_haveshadow\n";
464 if ($own_haveshadow && grep($_->[0] eq $lu, @ownshadow)) {
465 #print STDERR "syncuser($lu,$ru) shadow $rempasswd{$ru}->[1]\n";
466 copyfield('shadow',$lu,1, $rempasswd{$ru}->[1]);
468 #print STDERR "syncuser($lu,$ru) passwd $rempasswd{$ru}->[1]\n";
469 copyfield('passwd',$lu,1, $rempasswd{$ru}->[1]);
471 copyfield('passwd',$lu,4, $rempasswd{$ru}->[4]); # comment
472 copyfield('passwd',$lu,6, $rempasswd{$ru}->[6]); # shell
477 #print STDERR "syncuser($lu,$ru) group $tgroup\n";
478 next unless &wantsyncgroup($tgroup);
479 #print STDERR "syncuser($lu,$ru) group $tgroup yes\n";
481 if (!exists $remgroup{$tgroup}) {
482 diag("group $tgroup: not on remote host");
485 $inremote= grep($_ eq $ru, split(/\,/,$remgroup{$tgroup}->[3]));
486 $cusers= $e->[3]; $inlocal= grep($_ eq $lu, split(/\,/,$cusers));
487 if ($inremote && !$inlocal) {
488 $cusers.= ',' if length $cusers;
490 } elsif ($inlocal && !$inremote) {
491 $cusers= join(',', grep($_ ne $lu, split(/\,/, $cusers)));
502 return if $bannerdone;
503 print "\n" or die $!; system 'date'; $? and die $?;
508 for $h (keys %wanthost) {
509 die "host $h not in config file\n" if $wanthost{$h};
514 #print STDERR "\n\nfinish display=$display pw=$pw\n\n";
515 for $e (@ownpasswd) {
517 next if $displaydone{$tu};
519 for $e2 (@ownshadow) {
520 next unless $e2->[0] eq $tu;
521 $tpw= $e2->[1]; last;
523 $tpw= length($tpw)==13 ? 1 : length($tpw) ? -1 : 0;
524 next unless $pw == $tpw;
525 hosthead($pw == 1 ? "unsynched normal account" :
526 $pw == 0 ? "unsynched, passwordless" :
527 "unsynched, no logins");
528 print " $e->[0]" or die $!;
531 print "\n\n" or die $! if $hostheaddone;
536 for $file (qw(passwd shadow group)) {
537 eval "\$modified= \$modified$file; \$data_ref= \\\@own$file;".
538 " \$fetched= \$own_fetched$file; 1;" or die $@;
540 die $file unless $fetched;
542 $newfile= $no_act ? "$file.new" : "/etc/$file.new";
543 open NF,"> $newfile";
544 for $e (@$data_ref) {
545 print NF join(':',@$e),"\n" or die $!;
548 system "diff -U0 /etc/$file $newfile"; $?==256 or die $?;
550 (@stats= stat "/etc/$file") or die "$file: $!";
551 chown $stats[4],$stats[5], $newfile or die $!;
552 chmod $stats[2] & 07777, $newfile or die $!;
553 rename $newfile, "/etc/$file" or die $!;
561 next if m/^\#/ || !m/\S/;
563 finish() if m/^end$/;
564 if (m/^host\s+(\S+)$/) {
566 $ch_getpasswd= $ch_getgroup= $ch_getshadow= '';
567 $ch_fetchedpasswd= $ch_fetchedgroup;
570 } elsif (exists $wanthost{$ch_name}) {
571 $wanthost{$ch_name}= 0;
576 } elsif (m/^(getpasswd|getshadow|getgroup)\s+(.*\S)$/) {
577 eval "\$ch_$1= \$2; 1;" or die $@;
578 } elsif (m/^(lockpasswd|lockgroup)\s+(\S+)$/) {
579 eval "\$ch_$1= \$2; 1;" or die $@;
580 } elsif (m,^(homebase)\s+(/\S+)$,) {
581 eval "\$ch_$1= \$2; 1;" or die $@;
582 } elsif (m/^(uidmin|uidmax)\s+(\d+)$/ && $2>0) {
583 eval "\$ch_$1= \$2; 1;" or die $@;
584 } elsif (m/^createuser$/) {
585 $opt_createuser= $def_createuser;
586 } elsif (m/^nocreateuser$/) {
588 } elsif (m/^createuser\s+(\S+)$/) {
590 } elsif (m/^logfile\s+(.*\S)$/) {
592 open STDOUT,">> $1" or die "$1: $!"; $|=1;
593 } elsif (!$display) {
594 print "would log to $1\n" or die $!;
596 } elsif (m/^(no|)(sameuid)$/) {
597 eval "\$opt_$2= ".($1 eq 'no' ? 0 : 1)."; 1;" or die $@;
598 } elsif (m/^usergroups$/) {
600 } elsif (m/^nousergroups$/) {
602 } elsif (m/^defaultgid\s+(\d+)$/) {
604 } elsif (m/^(no|)group\s+([-+.0-9a-zA-Z*?]+)$/) {
605 $yes= $1 eq 'no' ? 0 : 1;
607 @groupglobs=() if $_ eq '*';
611 unshift @groupglobs, [ $_, $yes ];
613 } elsif (m/^user\s+(\S+)$/) {
615 } elsif (m/^user\s+(\S+)\s+remote\=(\S+)$/) {
617 } elsif (m/^nouser\s+(\S+)$/) {
619 } elsif (m/^users\s+(\d+)\-(\d+)$/) {
620 $tmin= $1; $tmax= $2; $except= $3;
622 for $k (keys %rempasswd) {
623 $tuid= $rempasswd{$k}->[2];
624 next if $tuid<$1 or $tuid>$2;
627 } elsif (m/^addhere$/) {
629 die "$configfile:$.: unknown directive\n";
633 die "$configfile:$.: missing \`end', or read error\n";