]> git.cameronkatri.com Git - pw-darwin.git/blob - adduser/adduser.perl
Do not accept empty user names.
[pw-darwin.git] / adduser / adduser.perl
1 #!/usr/bin/perl
2 #
3 # Copyright (c) 1995-1996 Wolfram Schneider <wosch@FreeBSD.org>. Berlin.
4 # All rights reserved.
5 #
6 # Redistribution and use in source and binary forms, with or without
7 # modification, are permitted provided that the following conditions
8 # are met:
9 # 1. Redistributions of source code must retain the above copyright
10 # notice, this list of conditions and the following disclaimer.
11 # 2. Redistributions in binary form must reproduce the above copyright
12 # notice, this list of conditions and the following disclaimer in the
13 # documentation and/or other materials provided with the distribution.
14 #
15 # THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16 # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17 # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18 # ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19 # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20 # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21 # OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22 # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23 # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24 # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25 # SUCH DAMAGE.
26 #
27 # $Id: adduser.perl,v 1.35 1997/08/26 22:47:51 wosch Exp $
28
29
30 # read variables
31 sub variables {
32 $verbose = 1; # verbose = [0-2]
33 $defaultpasswd = "yes"; # use password for new users
34 $dotdir = "/usr/share/skel"; # copy dotfiles from this dir
35 $dotdir_bak = $dotdir;
36 $send_message = "/etc/adduser.message"; # send message to new user
37 $send_message_bak = '/etc/adduser.message';
38 $config = "/etc/adduser.conf"; # config file for adduser
39 $config_read = 1; # read config file
40 $logfile = "/var/log/adduser"; # logfile
41 $home = "/home"; # default HOME
42 $etc_shells = "/etc/shells";
43 $etc_passwd = "/etc/master.passwd";
44 $group = "/etc/group";
45 $pwd_mkdb = "pwd_mkdb -p"; # program for building passwd database
46
47
48 # List of directories where shells located
49 @path = ('/bin', '/usr/bin', '/usr/local/bin');
50 # common shells, first element has higher priority
51 @shellpref = ('csh', 'sh', 'bash', 'tcsh', 'ksh');
52
53 $defaultshell = 'sh'; # defaultshell if not empty
54 $group_uniq = 'USER';
55 $defaultgroup = $group_uniq;# login groupname, $group_uniq means username
56 $defaultclass = '';
57
58 $uid_start = 1000; # new users get this uid
59 $uid_end = 32000; # max. uid
60
61 # global variables
62 # passwd
63 $username = ''; # $username{username} = uid
64 $uid = ''; # $uid{uid} = username
65 $pwgid = ''; # $pwgid{pwgid} = username; gid from passwd db
66
67 $password = ''; # password for new users
68
69 # group
70 $groupname =''; # $groupname{groupname} = gid
71 $groupmembers = ''; # $groupmembers{gid} = members of group/kommalist
72 $gid = ''; # $gid{gid} = groupname; gid form group db
73
74 # shell
75 $shell = ''; # $shell{`basename sh`} = sh
76
77 umask 022; # don't give login group write access
78
79 $ENV{'PATH'} = "/sbin:/bin:/usr/sbin:/usr/bin";
80 @passwd_backup = '';
81 @group_backup = '';
82 @message_buffer = '';
83 @user_variable_list = ''; # user variables in /etc/adduser.conf
84 $do_not_delete = '## DO NOT DELETE THIS LINE!';
85 }
86
87 # read shell database, see also: shells(5)
88 sub shells_read {
89 local($sh);
90 local($err) = 0;
91
92 print "Check $etc_shells\n" if $verbose;
93 open(S, $etc_shells) || die "$etc_shells:$!\n";
94
95 while(<S>) {
96 if (/^\s*\//) {
97 s/^\s*//; s/\s+.*//; # chop
98 $sh = $_;
99 if (-x $sh) {
100 $shell{&basename($sh)} = $sh;
101 } else {
102 warn "Shell: $sh not executable!\n";
103 $err++;
104 }
105 }
106 }
107
108 # Allow /nonexistent and /bin/date as a valid shell for system utils
109 push(@list, "/nonexistent");
110 push(@shellpref, "no") if !grep(/^no$/, @shellpref);
111 $shell{"no"} = "/nonexistent";
112
113 push(@list, "/bin/date");
114 push(@shellpref, "date") if !grep(/^date$/, @shellpref);
115 $shell{"date"} = "/bin/date";
116
117 return $err;
118 }
119
120 # add new shells if possible
121 sub shells_add {
122 local($sh,$dir,@list);
123
124 return 1 unless $verbose;
125
126 foreach $sh (@shellpref) {
127 # all known shells
128 if (!$shell{$sh}) {
129 # shell $sh is not defined as login shell
130 foreach $dir (@path) {
131 if (-x "$dir/$sh") {
132 # found shell
133 if (&confirm_yn("Found shell: $dir/$sh. Add to $etc_shells?", "yes")) {
134 push(@list, "$dir/$sh");
135 push(@shellpref, "$sh");
136 $shell{&basename("$dir/$sh")} = "$dir/$sh";
137 $changes++;
138 }
139 }
140 }
141 }
142 }
143 &append_file($etc_shells, @list) if $#list >= 0;
144 }
145
146 # choose your favourite shell and return the shell
147 sub shell_default {
148 local($e,$i,$new_shell);
149 local($sh);
150
151 $sh = &shell_default_valid($defaultshell);
152 return $sh unless $verbose;
153
154 $new_shell = &confirm_list("Enter your default shell:", 0,
155 $sh, sort(keys %shell));
156 print "Your default shell is: $new_shell -> $shell{$new_shell}\n";
157 $changes++ if $new_shell ne $sh;
158 return $new_shell;
159 }
160
161 sub shell_default_valid {
162 local($sh) = @_;
163 local($s,$e);
164
165 return $sh if $shell{$sh};
166
167 foreach $e (@shellpref) {
168 $s = $e;
169 last if defined($shell{$s});
170 }
171 $s = "sh" unless $s;
172 warn "Shell ``$sh'' is undefined, use ``$s''\n";
173 return $s;
174 }
175
176 # return default home partition (f.e. "/home")
177 # create base directory if nesseccary
178 sub home_partition {
179 local($home) = @_;
180 $home = &stripdir($home);
181 local($h) = $home;
182
183 return $h if !$verbose && $h eq &home_partition_valid($h);
184
185 while(1) {
186 $h = &confirm_list("Enter your default HOME partition:", 1, $home, "");
187 $h = &stripdir($h);
188 last if $h eq &home_partition_valid($h);
189 }
190
191 $changes++ if $h ne $home;
192 return $h;
193 }
194
195 sub home_partition_valid {
196 local($h) = @_;
197
198 $h = &stripdir($h);
199 # all right (I hope)
200 return $h if $h =~ "^/" && -e $h && -w $h && (-d $h || -l $h);
201
202 # Errors or todo
203 if ($h !~ "^/") {
204 warn "Please use absolute path for home: ``$h''.\a\n";
205 return 0;
206 }
207
208 if (-e $h) {
209 warn "$h exists, but is not a directory or symlink!\n"
210 unless -d $h || -l $h;
211 warn "$h is not writable!\n"
212 unless -w $h;
213 return 0;
214 } else {
215 # create home partition
216 return $h if &mkdir_home($h);
217 }
218 return 0;
219 }
220
221 # check for valid passwddb
222 sub passwd_check {
223 system("$pwd_mkdb -c $etc_passwd");
224 die "\nInvalid $etc_passwd - cannot add any users!\n" if $?;
225 }
226
227 # read /etc/passwd
228 sub passwd_read {
229 local($p_username, $pw, $p_uid, $p_gid, $sh, %shlist);
230
231 print "Check $etc_passwd\n" if $verbose;
232 open(P, "$etc_passwd") || die "$passwd: $!\n";
233
234 while(<P>) {
235 chop;
236 push(@passwd_backup, $_);
237 # ignore comments
238 next if /^\s*$/;
239 next if /^\s*#/;
240
241 ($p_username, $pw, $p_uid, $p_gid, $sh) = (split(/:/, $_))[0..3,9];
242
243 print "$p_username already exists with uid: $username{$p_username}!\n"
244 if $username{$p_username} && $verbose;
245 $username{$p_username} = $p_uid;
246 print "User $p_username: uid $p_uid exists twice: $uid{$p_uid}\n"
247 if $uid{$p_uid} && $verbose && $p_uid; # don't warn for uid 0
248 print "User $p_username: illegal shell: ``$sh''\n"
249 if ($verbose && $sh &&
250 !$shell{&basename($sh)} &&
251 $p_username !~ /^(news|xten|bin|nobody|uucp)$/ &&
252 $sh !~ /\/(pppd|sliplogin|nologin)$/);
253 $uid{$p_uid} = $p_username;
254 $pwgid{$p_gid} = $p_username;
255 }
256 close P;
257 }
258
259 # read /etc/group
260 sub group_read {
261 local($g_groupname,$pw,$g_gid, $memb);
262
263 print "Check $group\n" if $verbose;
264 open(G, "$group") || die "$group: $!\n";
265 while(<G>) {
266 chop;
267 push(@group_backup, $_);
268 # ignore comments
269 next if /^\s*$/;
270 next if /^\s*#/;
271
272 ($g_groupname, $pw, $g_gid, $memb) = (split(/:/, $_))[0..3];
273
274 $groupmembers{$g_gid} = $memb;
275 warn "Groupname exists twice: $g_groupname:$g_gid -> $g_groupname:$groupname{$g_groupname}\n"
276 if $groupname{$g_groupname} && $verbose;
277 $groupname{$g_groupname} = $g_gid;
278 warn "Groupid exists twice: $g_groupname:$g_gid -> $gid{$g_gid}:$g_gid\n"
279 if $gid{$g_gid} && $verbose;
280 $gid{$g_gid} = $g_groupname;
281 }
282 close G;
283 }
284
285 # check gids /etc/passwd <-> /etc/group
286 sub group_check {
287 local($c_gid, $c_username, @list);
288
289 foreach $c_gid (keys %pwgid) {
290 if (!$gid{$c_gid}) {
291 $c_username = $pwgid{$c_gid};
292 warn "User ``$c_username'' has gid $c_gid but a group with this " .
293 "gid does not exist.\n" if $verbose;
294 }
295 }
296 }
297
298 #
299 # main loop for creating new users
300 #
301
302 # return username
303 sub new_users_name {
304 local($name);
305
306 while(1) {
307 $name = &confirm_list("Enter username", 1, "a-z0-9_-", "");
308 if (length($name) > 16) {
309 warn "Username is longer than 16 chars\a\n";
310 next;
311 }
312 last if (&new_users_name_valid($name) eq $name);
313 }
314 return $name;
315 }
316
317 sub new_users_name_valid {
318 local($name) = @_;
319
320 if ($name !~ /^[a-z0-9_][a-z0-9_\-]*$/ || $name eq "a-z0-9_-") {
321 warn "Wrong username. " .
322 "Please use only lowercase characters or digits\a\n";
323 return 0;
324 } elsif ($username{$name}) {
325 warn "Username ``$name'' already exists!\a\n"; return 0;
326 }
327 return $name;
328 }
329
330 # return full name
331 sub new_users_fullname {
332 local($name) = @_;
333 local($fullname);
334
335 while(1) {
336 $fullname = &confirm_list("Enter full name", 1, "", "");
337 last if $fullname eq &new_users_fullname_valid($fullname);
338 }
339 $fullname = $name unless $fullname;
340 return $fullname;
341 }
342
343 sub new_users_fullname_valid {
344 local($fullname) = @_;
345
346 return $fullname if $fullname !~ /:/;
347
348 warn "``:'' is not allowed!\a\n";
349 return 0;
350 }
351
352 # return shell (full path) for user
353 sub new_users_shell {
354 local($sh);
355
356 $sh = &confirm_list("Enter shell", 0, $defaultshell, keys %shell);
357 return $shell{$sh};
358 }
359
360 # return free uid and gid
361 sub new_users_id {
362 local($name) = @_;
363 local($u_id, $g_id) = &next_id($name);
364 local($u_id_tmp, $e);
365
366 while(1) {
367 $u_id_tmp = &confirm_list("Uid", 1, $u_id, "");
368 last if $u_id_tmp =~ /^[0-9]+$/ && $u_id_tmp <= $uid_end &&
369 ! $uid{$u_id_tmp};
370 if ($uid{$u_id_tmp}) {
371 warn "Uid ``$u_id_tmp'' in use!\a\n";
372 } else {
373 warn "Wrong uid.\a\n";
374 }
375 }
376 # use calculated uid
377 return ($u_id_tmp, $g_id) if $u_id_tmp eq $u_id;
378 # recalculate gid
379 $uid_start = $u_id_tmp;
380 return &next_id($name);
381 }
382
383 # return login class for user
384 sub new_users_class {
385 local($def) = @_;
386 local($class);
387
388 $class = &confirm_list("Enter login class:", 1, $def, ($def, "default"));
389 $class = "" if $class eq "default";
390 return $class;
391 }
392
393 # add user to group
394 sub add_group {
395 local($gid, $name) = @_;
396
397 return 0 if
398 $groupmembers{$gid} =~ /^(.+,)?$name(,.+)?$/;
399
400 $groupmembers_bak{$gid} = $groupmembers{$gid};
401 $groupmembers{$gid} .= "," if $groupmembers{$gid};
402 $groupmembers{$gid} .= "$name";
403
404 return $name;
405 }
406
407
408 # return login group
409 sub new_users_grplogin {
410 local($name, $defaultgroup, $new_users_ok) = @_;
411 local($group_login, $group);
412
413 $group = $name;
414 $group = $defaultgroup if $defaultgroup ne $group_uniq;
415
416 if ($new_users_ok) {
417 # clean up backup
418 foreach $e (keys %groupmembers_bak) { delete $groupmembers_bak{$e}; }
419 } else {
420 # restore old groupmembers, user was not accept
421 foreach $e (keys %groupmembers_bak) {
422 $groupmembers{$e} = $groupmembers_bak{$e};
423 }
424 }
425
426 while(1) {
427 $group_login = &confirm_list("Login group", 1, $group,
428 ($name, $group));
429 last if $group_login eq $group;
430 last if $group_login eq $name;
431 last if defined $groupname{$group_login};
432 if ($group_login eq $group_uniq) {
433 $group_login = $name; last;
434 }
435
436 if (defined $gid{$group_login}) {
437 # convert numeric groupname (gid) to groupname
438 $group_login = $gid{$group_login};
439 last;
440 }
441 warn "Group does not exist!\a\n";
442 }
443
444 #if (defined($groupname{$group_login})) {
445 # &add_group($groupname{$group_login}, $name);
446 #}
447
448 return ($group_login, $group_uniq) if $group_login eq $name;
449 return ($group_login, $group_login);
450 }
451
452 # return login group
453 sub new_users_grplogin_batch {
454 local($name, $defaultgroup) = @_;
455 local($group_login, $group);
456
457 $group_login = $name;
458 $group_login = $defaultgroup if $defaultgroup ne $group_uniq;
459
460 if (defined $gid{$group_login}) {
461 # convert numeric groupname (gid) to groupname
462 $group_login = $gid{$group_login};
463 }
464
465 # if (defined($groupname{$group_login})) {
466 # &add_group($groupname{$group_login}, $name);
467 # }
468
469 return $group_login
470 if defined($groupname{$group_login}) || $group_login eq $name;
471 warn "Group ``$group_login'' does not exist\a\n";
472 return 0;
473 }
474
475 # return other groups (string)
476 sub new_users_groups {
477 local($name, $other_groups) = @_;
478 local($string) =
479 "Login group is ``$group_login''. Invite $name into other groups:";
480 local($e, $flag);
481 local($new_groups,$groups);
482
483 $other_groups = "no" unless $other_groups;
484
485 while(1) {
486 $groups = &confirm_list($string, 1, $other_groups,
487 ("no", $other_groups, "guest"));
488 # no other groups
489 return "" if $groups eq "no";
490
491 ($flag, $new_groups) = &new_users_groups_valid($groups);
492 last unless $flag;
493 }
494 $new_groups =~ s/\s*$//;
495 return $new_groups;
496 }
497
498 sub new_users_groups_valid {
499 local($groups) = @_;
500 local($e, $new_groups);
501 local($flag) = 0;
502
503 foreach $e (split(/[,\s]+/, $groups)) {
504 # convert numbers to groupname
505 if ($e =~ /^[0-9]+$/ && $gid{$e}) {
506 $e = $gid{$e};
507 }
508 if (defined($groupname{$e})) {
509 if ($e eq $group_login) {
510 # do not add user to a group if this group
511 # is also the login group.
512 } elsif (&add_group($groupname{$e}, $name)) {
513 $new_groups .= "$e ";
514 } else {
515 warn "$name is already member of group ``$e''\n";
516 }
517 } else {
518 warn "Group ``$e'' does not exist\a\n"; $flag++;
519 }
520 }
521 return ($flag, $new_groups);
522 }
523
524 # your last change
525 sub new_users_ok {
526
527 print <<EOF;
528
529 Name: $name
530 Password: ****
531 Fullname: $fullname
532 Uid: $u_id
533 Gid: $g_id ($group_login)
534 Class: $class
535 Groups: $group_login $new_groups
536 HOME: $home/$name
537 Shell: $sh
538 EOF
539
540 return &confirm_yn("OK?", "yes");
541 }
542
543 # make password database
544 sub new_users_pwdmkdb {
545 local($last) = @_;
546
547 system("$pwd_mkdb $etc_passwd");
548 if ($?) {
549 warn "$last\n";
550 warn "``$pwd_mkdb'' failed\n";
551 exit($? >> 8);
552 }
553 }
554
555 # update group database
556 sub new_users_group_update {
557 local($e, @a);
558
559 # Add *new* group
560 if (!defined($groupname{$group_login}) &&
561 !defined($gid{$groupname{$group_login}})) {
562 push(@group_backup, "$group_login:*:$g_id:");
563 $groupname{$group_login} = $g_id;
564 $gid{$g_id} = $group_login;
565 # $groupmembers{$g_id} = $group_login;
566 }
567
568 if ($new_groups || defined($groupname{$group_login}) ||
569 defined($gid{$groupname{$group_login}}) &&
570 $gid{$groupname{$group_login}} ne "+") {
571 # new user is member of some groups
572 # new login group is already in name space
573 rename($group, "$group.bak");
574 #warn "$group_login $groupname{$group_login} $groupmembers{$groupname{$group_login}}\n";
575 foreach $e (sort {$a <=> $b} (keys %gid)) {
576 push(@a, "$gid{$e}:*:$e:$groupmembers{$e}");
577 }
578 &append_file($group, @a);
579 } else {
580 &append_file($group, "$group_login:*:$g_id:");
581 }
582
583 }
584
585 sub new_users_passwd_update {
586 # update passwd/group variables
587 push(@passwd_backup, $new_entry);
588 $username{$name} = $u_id;
589 $uid{$u_id} = $name;
590 $pwgid{$g_id} = $name;
591 }
592
593 # send message to new user
594 sub new_users_sendmessage {
595 return 1 if $send_message eq "no";
596
597 local($cc) =
598 &confirm_list("Send message to ``$name'' and:",
599 1, "no", ("root", "second_mail_address", "no"));
600 local($e);
601 $cc = "" if $cc eq "no";
602
603 foreach $e (@message_buffer) {
604 print eval "\"$e\"";
605 }
606 print "\n";
607
608 local(@message_buffer_append) = ();
609 if (!&confirm_yn("Add anything to default message", "no")) {
610 print "Use ``.'' or ^D alone on a line to finish your message.\n";
611 push(@message_buffer_append, "\n");
612 while($read = <STDIN>) {
613 last if $read eq "\.\n";
614 push(@message_buffer_append, $read);
615 }
616 }
617
618 &sendmessage("$name $cc", (@message_buffer, @message_buffer_append))
619 if (&confirm_yn("Send message", "yes"));
620 }
621
622 sub sendmessage {
623 local($to, @message) = @_;
624 local($e);
625
626 if (!open(M, "| mail -s Welcome $to")) {
627 warn "Cannot send mail to: $to!\n";
628 return 0;
629 } else {
630 foreach $e (@message) {
631 print M eval "\"$e\"";
632 }
633 close M;
634 }
635 }
636
637
638 sub new_users_password {
639
640 # empty password
641 return "" if $defaultpasswd ne "yes";
642
643 local($password);
644
645 while(1) {
646 system("stty -echo");
647 $password = &confirm_list("Enter password", 1, "", "");
648 system("stty echo");
649 print "\n";
650 if ($password ne "") {
651 system("stty -echo");
652 $newpass = &confirm_list("Enter password again", 1, "", "");
653 system("stty echo");
654 print "\n";
655 last if $password eq $newpass;
656 print "They didn't match, please try again\n";
657 }
658 elsif (&confirm_yn("Use an empty password?", "yes")) {
659 last;
660 }
661 }
662
663 return $password;
664 }
665
666
667 sub new_users {
668
669 print "\n" if $verbose;
670 print "Ok, let's go.\n" .
671 "Don't worry about mistakes. I will give you the chance later to " .
672 "correct any input.\n" if $verbose;
673
674 # name: Username
675 # fullname: Full name
676 # sh: shell
677 # u_id: user id
678 # g_id: group id
679 # class: login class
680 # group_login: groupname of g_id
681 # new_groups: some other groups
682 local($name, $group_login, $fullname, $sh, $u_id, $g_id, $class, $new_groups);
683 local($groupmembers_bak, $cryptpwd);
684 local($new_users_ok) = 1;
685
686
687 $new_groups = "no";
688 $new_groups = "no" unless $groupname{$new_groups};
689
690 while(1) {
691 $name = &new_users_name;
692 $fullname = &new_users_fullname($name);
693 $sh = &new_users_shell;
694 ($u_id, $g_id) = &new_users_id($name);
695 $class = &new_users_class($defaultclass);
696 ($group_login, $defaultgroup) =
697 &new_users_grplogin($name, $defaultgroup, $new_users_ok);
698 # do not use uniq username and login group
699 $g_id = $groupname{$group_login} if (defined($groupname{$group_login}));
700
701 $new_groups = &new_users_groups($name, $new_groups);
702 $password = &new_users_password;
703
704
705 if (&new_users_ok) {
706 $new_users_ok = 1;
707
708 $cryptpwd = "";
709 $cryptpwd = crypt($password, &salt) if $password ne "";
710 # obscure perl bug
711 $new_entry = "$name\:" . "$cryptpwd" .
712 "\:$u_id\:$g_id\:$class\:0:0:$fullname:$home/$name:$sh";
713 &append_file($etc_passwd, "$new_entry");
714 &new_users_pwdmkdb("$new_entry");
715 &new_users_group_update;
716 &new_users_passwd_update; print "Added user ``$name''\n";
717 &new_users_sendmessage;
718 &adduser_log("$name:*:$u_id:$g_id($group_login):$fullname");
719 &home_create($name, $group_login);
720 } else {
721 $new_users_ok = 0;
722 }
723 if (!&confirm_yn("Add another user?", "yes")) {
724 print "Goodbye!\n" if $verbose;
725 last;
726 }
727 print "\n" if !$verbose;
728 }
729 }
730
731 sub batch {
732 local($name, $groups, $class, $fullname, $password) = @_;
733 local($sh);
734
735 $defaultshell = &shell_default_valid($defaultshell);
736 return 0 unless $home = &home_partition_valid($home);
737 return 0 if $dotdir ne &dotdir_default_valid($dotdir);
738 $send_message = &message_default;
739
740 return 0 if $name ne &new_users_name_valid($name);
741 $sh = $shell{$defaultshell};
742 ($u_id, $g_id) = &next_id($name);
743 $group_login = &new_users_grplogin_batch($name, $defaultgroup);
744 return 0 unless $group_login;
745 $g_id = $groupname{$group_login} if (defined($groupname{$group_login}));
746 ($flag, $new_groups) = &new_users_groups_valid($groups);
747 return 0 if $flag;
748
749 $class = $defaultclass if $class eq "";
750 $cryptpwd = "";
751 $cryptpwd = crypt($password, &salt) if $password ne "";
752 # obscure perl bug
753 $new_entry = "$name\:" . "$cryptpwd" .
754 "\:$u_id\:$g_id\:$class\:0:0:$fullname:$home/$name:$sh";
755 &append_file($etc_passwd, "$new_entry");
756 &new_users_pwdmkdb("$new_entry");
757 &new_users_group_update;
758 &new_users_passwd_update; print "Added user ``$name''\n";
759 &sendmessage($name, @message_buffer) if $send_message ne "no";
760 &adduser_log("$name:*:$u_id:$g_id($group_login):$fullname");
761 &home_create($name, $group_login);
762 }
763
764 # ask for password usage
765 sub password_default {
766 local($p) = $defaultpasswd;
767 if ($verbose) {
768 $p = &confirm_yn("Use passwords", $defaultpasswd);
769 $changes++ unless $p;
770 }
771 return "yes" if (($defaultpasswd eq "yes" && $p) ||
772 ($defaultpasswd eq "no" && !$p));
773 return "no"; # otherwise
774 }
775
776 # misc
777 sub check_root {
778 die "You are not root!\n" if $< && !$test;
779 }
780
781 sub usage {
782 warn <<USAGE;
783 usage: adduser
784 [-batch username [group[,group]...] [class] [fullname] [password]]
785 [-check_only]
786 [-class login_class]
787 [-config_create]
788 [-dotdir dotdir]
789 [-group login_group]
790 [-h|-help]
791 [-home home]
792 [-message message_file]
793 [-noconfig]
794 [-shell shell]
795 [-s|-silent|-q|-quiet]
796 [-uid uid_start]
797 [-v|-verbose]
798
799 home=$home shell=$defaultshell dotdir=$dotdir login_group=$defaultgroup
800 login_class=$defaultclass message_file=$send_message uid_start=$uid_start
801 USAGE
802 exit 1;
803 }
804
805 # uniq(1)
806 sub uniq {
807 local(@list) = @_;
808 local($e, $last, @array);
809
810 foreach $e (sort @list) {
811 push(@array, $e) unless $e eq $last;
812 $last = $e;
813 }
814 return @array;
815 }
816
817 # see /usr/src/usr.bin/passwd/local_passwd.c or librcypt, crypt(3)
818 sub salt {
819 local($salt); # initialization
820 local($i, $rand);
821 local(@itoa64) = ( 0 .. 9, a .. z, A .. Z ); # 0 .. 63
822
823 warn "calculate salt\n" if $verbose > 1;
824 # to64
825 for ($i = 0; $i < 8; $i++) {
826 srand(time + $rand + $$);
827 $rand = rand(25*29*17 + $rand);
828 $salt .= $itoa64[$rand & $#itoa64];
829 }
830 warn "Salt is: $salt\n" if $verbose > 1;
831
832 return $salt;
833 }
834
835
836 # print banner
837 sub copyright {
838 return;
839 }
840
841 # hints
842 sub hints {
843 if ($verbose) {
844 print "Use option ``-silent'' if you don't want see " .
845 "all warnings & questions.\n\n";
846 } else {
847 print "Use option ``-verbose'' if you want see more warnings & " .
848 "questions \nor try to repair bugs.\n\n";
849 }
850 }
851
852 #
853 sub parse_arguments {
854 local(@argv) = @_;
855
856 while ($_ = $argv[0], /^-/) {
857 shift @argv;
858 last if /^--$/;
859 if (/^--?(v|verbose)$/) { $verbose = 1 }
860 elsif (/^--?(s|silent|q|quiet)$/) { $verbose = 0 }
861 elsif (/^--?(debug)$/) { $verbose = 2 }
862 elsif (/^--?(h|help|\?)$/) { &usage }
863 elsif (/^--?(home)$/) { $home = $argv[0]; shift @argv }
864 elsif (/^--?(shell)$/) { $defaultshell = $argv[0]; shift @argv }
865 elsif (/^--?(dotdir)$/) { $dotdir = $argv[0]; shift @argv }
866 elsif (/^--?(uid)$/) { $uid_start = $argv[0]; shift @argv }
867 elsif (/^--?(class)$/) { $defaultclass = $argv[0]; shift @argv }
868 elsif (/^--?(group)$/) { $defaultgroup = $argv[0]; shift @argv }
869 elsif (/^--?(check_only)$/) { $check_only = 1 }
870 elsif (/^--?(message)$/) { $send_message = $argv[0]; shift @argv;
871 $sendmessage = 1; }
872 elsif (/^--?(batch)$/) {
873 @batch = splice(@argv, 0, 5); $verbose = 0;
874 die "batch: too few arguments\n" if $#batch < 0;
875 }
876 # see &config_read
877 elsif (/^--?(config_create)$/) { &create_conf; }
878 elsif (/^--?(noconfig)$/) { $config_read = 0; }
879 else { &usage }
880 }
881 #&usage if $#argv < 0;
882 }
883
884 sub basename {
885 local($name) = @_;
886 $name =~ s|/+$||;
887 $name =~ s|.*/+||;
888 return $name;
889 }
890
891 sub dirname {
892 local($name) = @_;
893 $name = &stripdir($name);
894 $name =~ s|/+[^/]+$||;
895 $name = "/" unless $name; # dirname of / is /
896 return $name;
897 }
898
899 # return 1 if $file is a readable file or link
900 sub filetest {
901 local($file, $verb) = @_;
902
903 if (-e $file) {
904 if (-f $file || -l $file) {
905 return 1 if -r _;
906 warn "$file unreadable\n" if $verbose;
907 } else {
908 warn "$file is not a plain file or link\n" if $verbose;
909 }
910 }
911 return 0;
912 }
913
914 # create configuration files and exit
915 sub create_conf {
916 $create_conf = 1;
917 if ($send_message ne 'no') {
918 &message_create($send_message);
919 } else {
920 &message_create($send_message_bak);
921 }
922 &config_write(1);
923 exit(0);
924 }
925
926 # log for new user in /var/log/adduser
927 sub adduser_log {
928 local($string) = @_;
929 local($e);
930
931 return 1 if $logfile eq "no";
932
933 local($sec, $min, $hour, $mday, $mon, $year) = localtime;
934 $mon++;
935
936 foreach $e ('sec', 'min', 'hour', 'mday', 'mon', 'year') {
937 # '7' -> '07'
938 eval "\$$e = 0 . \$$e" if (eval "\$$e" < 10);
939 }
940
941 &append_file($logfile, "$year/$mon/$mday $hour:$min:$sec $string");
942 }
943
944 # create HOME directory, copy dotfiles from $dotdir to $HOME
945 sub home_create {
946 local($name, $group) = @_;
947 local($homedir) = "$home/$name";
948
949 if (-e "$homedir") {
950 warn "HOME Directory ``$homedir'' already exist\a\n";
951 return 0;
952 }
953
954 if ($dotdir eq 'no') {
955 if (!mkdir("$homedir",0755)) {
956 warn "mkdir $homedir: $!\n"; return 0;
957 }
958 system 'chown', "$name:$group", $homedir;
959 return !$?;
960 }
961
962 # copy files from $dotdir to $homedir
963 # rename 'dot.foo' files to '.foo'
964 print "Copy files from $dotdir to $homedir\n" if $verbose;
965 system("cp -R $dotdir $homedir");
966 system("chmod -R u+wrX,go-w $homedir");
967 system("chown -R $name:$group $homedir");
968
969 # security
970 opendir(D, $homedir);
971 foreach $file (readdir(D)) {
972 if ($file =~ /^dot\./ && -f "$homedir/$file") {
973 $file =~ s/^dot\././;
974 rename("$homedir/dot$file", "$homedir/$file");
975 }
976 chmod(0600, "$homedir/$file")
977 if ($file =~ /^\.(rhosts|Xauthority|kermrc|netrc)$/);
978 chmod(0700, "$homedir/$file")
979 if ($file =~ /^(Mail|prv|\.(iscreen|term))$/);
980 }
981 closedir D;
982 return 1;
983 }
984
985 # makes a directory hierarchy
986 sub mkdir_home {
987 local($dir) = @_;
988 $dir = &stripdir($dir);
989 local($user_partition) = "/usr";
990 local($dirname) = &dirname($dir);
991
992
993 -e $dirname || &mkdirhier($dirname);
994
995 if (((stat($dirname))[0]) == ((stat("/"))[0])){
996 # home partition is on root partition
997 # create home partition on $user_partition and make
998 # a symlink from $dir to $user_partition/`basename $dir`
999 # For instance: /home -> /usr/home
1000
1001 local($basename) = &basename($dir);
1002 local($d) = "$user_partition/$basename";
1003
1004
1005 if (-d $d) {
1006 warn "Oops, $d already exist\n" if $verbose;
1007 } else {
1008 print "Create $d\n" if $verbose;
1009 if (!mkdir("$d", 0755)) {
1010 warn "$d: $!\a\n"; return 0;
1011 }
1012 }
1013
1014 unlink($dir); # symlink to nonexist file
1015 print "Create symlink: $dir -> $d\n" if $verbose;
1016 if (!symlink("$d", $dir)) {
1017 warn "Symlink $d: $!\a\n"; return 0;
1018 }
1019 } else {
1020 print "Create $dir\n" if $verbose;
1021 if (!mkdir("$dir", 0755)) {
1022 warn "Directory ``$dir'': $!\a\n"; return 0;
1023 }
1024 }
1025 return 1;
1026 }
1027
1028 sub mkdirhier {
1029 local($dir) = @_;
1030 local($d,$p);
1031
1032 $dir = &stripdir($dir);
1033
1034 foreach $d (split('/', $dir)) {
1035 $dir = "$p/$d";
1036 $dir =~ s|^//|/|;
1037 if (! -e "$dir") {
1038 print "Create $dir\n" if $verbose;
1039 if (!mkdir("$dir", 0755)) {
1040 warn "$dir: $!\n"; return 0;
1041 }
1042 }
1043 $p .= "/$d";
1044 }
1045 return 1;
1046 }
1047
1048 # stript unused '/'
1049 # F.i.: //usr///home// -> /usr/home
1050 sub stripdir {
1051 local($dir) = @_;
1052
1053 $dir =~ s|/+|/|g; # delete double '/'
1054 $dir =~ s|/$||; # delete '/' at end
1055 return $dir if $dir ne "";
1056 return '/';
1057 }
1058
1059 # Read one of the elements from @list. $confirm is default.
1060 # If !$allow accept only elements from @list.
1061 sub confirm_list {
1062 local($message, $allow, $confirm, @list) = @_;
1063 local($read, $c, $print);
1064
1065 $print = "$message" if $message;
1066 $print .= " " unless $message =~ /\n$/ || $#list == 0;
1067
1068 $print .= join($", &uniq(@list)); #"
1069 $print .= " " unless $message =~ /\n$/ && $#list == 0;
1070 print "$print";
1071 print "\n" if (length($print) + length($confirm)) > 60;
1072 print "[$confirm]: ";
1073
1074 chop($read = <STDIN>);
1075 $read =~ s/^\s*//;
1076 $read =~ s/\s*$//;
1077 return $confirm if $read eq "";
1078 return "$read" if $allow;
1079
1080 foreach $c (@list) {
1081 return $read if $c eq $read;
1082 }
1083 warn "$read: is not allowed!\a\n";
1084 return &confirm_list($message, $allow, $confirm, @list);
1085 }
1086
1087 # YES or NO question
1088 # return 1 if &confirm("message", "yes") and answer is yes
1089 # or if &confirm("message", "no") an answer is no
1090 # otherwise 0
1091 sub confirm_yn {
1092 local($message, $confirm) = @_;
1093 local($yes) = '^(yes|YES|y|Y)$';
1094 local($no) = '^(no|NO|n|N)$';
1095 local($read, $c);
1096
1097 if ($confirm && ($confirm =~ "$yes" || $confirm == 1)) {
1098 $confirm = "y";
1099 } else {
1100 $confirm = "n";
1101 }
1102 print "$message (y/n) [$confirm]: ";
1103 chop($read = <STDIN>);
1104 $read =~ s/^\s*//;
1105 $read =~ s/\s*$//;
1106 return 1 unless $read;
1107
1108 if (($confirm eq "y" && $read =~ "$yes") ||
1109 ($confirm eq "n" && $read =~ "$no")) {
1110 return 1;
1111 }
1112
1113 if ($read !~ "$yes" && $read !~ "$no") {
1114 warn "Wrong value. Enter again!\a\n";
1115 return &confirm_yn($message, $confirm);
1116 }
1117 return 0;
1118 }
1119
1120 # test if $dotdir exist
1121 # return "no" if $dotdir not exist or dotfiles should not copied
1122 sub dotdir_default {
1123 local($dir) = $dotdir;
1124
1125 return &dotdir_default_valid($dir) unless $verbose;
1126 while($verbose) {
1127 $dir = &confirm_list("Copy dotfiles from:", 1,
1128 $dir, ("no", $dotdir_bak, $dir));
1129 last if $dir eq &dotdir_default_valid($dir);
1130 }
1131 warn "Do not copy dotfiles.\n" if $verbose && $dir eq "no";
1132
1133 $changes++ if $dir ne $dotdir;
1134 return $dir;
1135 }
1136
1137 sub dotdir_default_valid {
1138 local($dir) = @_;
1139
1140 return $dir if (-e $dir && -r _ && (-d _ || -l $dir) && $dir =~ "^/");
1141 return $dir if $dir eq "no";
1142 warn "Dotdir ``$dir'' is not a directory\a\n";
1143 return "no";
1144 }
1145
1146 # ask for messages to new users
1147 sub message_default {
1148 local($file) = $send_message;
1149 local(@d) = ($file, $send_message_bak, "no");
1150
1151 while($verbose) {
1152 $file = &confirm_list("Send message from file:", 1, $file, @d);
1153 last if $file eq "no";
1154 last if &filetest($file, 1);
1155
1156 # maybe create message file
1157 &message_create($file) if &confirm_yn("Create ``$file''?", "yes");
1158 last if &filetest($file, 0);
1159 last if !&confirm_yn("File ``$file'' does not exist, try again?",
1160 "yes");
1161 }
1162
1163 if ($file eq "no" || !&filetest($file, 0)) {
1164 warn "Do not send message\n" if $verbose;
1165 $file = "no";
1166 } else {
1167 &message_read($file);
1168 }
1169
1170 $changes++ if $file ne $send_message && $verbose;
1171 return $file;
1172 }
1173
1174 # create message file
1175 sub message_create {
1176 local($file) = @_;
1177
1178 rename($file, "$file.bak");
1179 if (!open(M, "> $file")) {
1180 warn "Messagefile ``$file'': $!\n"; return 0;
1181 }
1182 print M <<EOF;
1183 #
1184 # Message file for adduser(8)
1185 # comment: ``#''
1186 # default variables: \$name, \$fullname, \$password
1187 # other variables: see /etc/adduser.conf after
1188 # line ``$do_not_delete''
1189 #
1190
1191 \$fullname,
1192
1193 your account ``\$name'' was created.
1194 Have fun!
1195
1196 See also chpass(1), finger(1), passwd(1)
1197 EOF
1198 close M;
1199 return 1;
1200 }
1201
1202 # read message file into buffer
1203 sub message_read {
1204 local($file) = @_;
1205 @message_buffer = '';
1206
1207 if (!open(R, "$file")) {
1208 warn "File ``$file'':$!\n"; return 0;
1209 }
1210 while(<R>) {
1211 push(@message_buffer, $_) unless /^\s*#/;
1212 }
1213 close R;
1214 }
1215
1216 # write @list to $file with file-locking
1217 sub append_file {
1218 local($file,@list) = @_;
1219 local($e);
1220 local($LOCK_EX) = 2;
1221 local($LOCK_NB) = 4;
1222 local($LOCK_UN) = 8;
1223
1224 open(F, ">> $file") || die "$file: $!\n";
1225 print "Lock $file.\n" if $verbose > 1;
1226 while(!flock(F, $LOCK_EX | $LOCK_NB)) {
1227 warn "Cannot lock file: $file\a\n";
1228 die "Sorry, give up\n"
1229 unless &confirm_yn("Try again?", "yes");
1230 }
1231 print F join("\n", @list) . "\n";
1232 close F;
1233 print "Unlock $file.\n" if $verbose > 1;
1234 flock(F, $LOCK_UN);
1235 }
1236
1237 # return free uid+gid
1238 # uid == gid if possible
1239 sub next_id {
1240 local($group) = @_;
1241
1242 $uid_start = 1000 if ($uid_start <= 0 || $uid_start >= $uid_end);
1243 # looking for next free uid
1244 while($uid{$uid_start}) {
1245 $uid_start++;
1246 $uid_start = 1000 if $uid_start >= $uid_end;
1247 print "$uid_start\n" if $verbose > 1;
1248 }
1249
1250 local($gid_start) = $uid_start;
1251 # group for user (username==groupname) already exist
1252 if ($groupname{$group}) {
1253 $gid_start = $groupname{$group};
1254 }
1255 # gid is in use, looking for another gid.
1256 # Note: uid an gid are not equal
1257 elsif ($gid{$uid_start}) {
1258 while($gid{$gid_start} || $uid{$gid_start}) {
1259 $gid_start--;
1260 $gid_start = $uid_end if $gid_start < 100;
1261 }
1262 }
1263 return ($uid_start, $gid_start);
1264 }
1265
1266 # read config file
1267 sub config_read {
1268 local($opt) = @_;
1269 local($user_flag) = 0;
1270
1271 # don't read config file
1272 return 1 if $opt =~ /-(noconfig|config_create)/ || !$config_read;
1273
1274 if(!open(C, "$config")) {
1275 warn "$config: $!\n"; return 0;
1276 }
1277
1278 while(<C>) {
1279 # user defined variables
1280 /^$do_not_delete/ && $user_flag++;
1281 # found @array or $variable
1282 if (s/^(\w+\s*=\s*\()/\@$1/ || s/^(\w+\s*=)/\$$1/) {
1283 eval $_;
1284 #warn "$_";
1285 }
1286 # lines with '^##' are not saved
1287 push(@user_variable_list, $_)
1288 if $user_flag && !/^##/ && (s/^[\$\@]// || /^[#\s]/);
1289 }
1290 #warn "X @user_variable_list X\n";
1291 close C;
1292 }
1293
1294
1295 # write config file
1296 sub config_write {
1297 local($silent) = @_;
1298
1299 # nothing to do
1300 return 1 unless ($changes || ! -e $config || !$config_read || $silent);
1301
1302 if (!$silent) {
1303 if (-e $config) {
1304 return 1 if &confirm_yn("\nWrite your changes to $config?", "no");
1305 } else {
1306 return 1 unless
1307 &confirm_yn("\nWrite your configuration to $config?", "yes");
1308 }
1309 }
1310
1311 rename($config, "$config.bak");
1312 open(C, "> $config") || die "$config: $!\n";
1313
1314 # prepare some variables
1315 $send_message = "no" unless $send_message;
1316 $defaultpasswd = "no" unless $defaultpasswd;
1317 local($shpref) = "'" . join("', '", @shellpref) . "'";
1318 local($shpath) = "'" . join("', '", @path) . "'";
1319 local($user_var) = join('', @user_variable_list);
1320
1321 print C <<EOF;
1322 #
1323 # $config - automatic generated by adduser(8)
1324 #
1325 # Note: adduser read *and* write this file.
1326 # You may change values, but don't add new things befor the
1327 # line ``$do_not_delete''
1328 #
1329
1330 # verbose = [0-2]
1331 verbose = $verbose
1332
1333 # use password for new users
1334 # defaultpasswd = yes | no
1335 defaultpasswd = $defaultpasswd
1336
1337 # copy dotfiles from this dir ("/usr/share/skel" or "no")
1338 dotdir = "$dotdir"
1339
1340 # send this file to new user ("/etc/adduser.message" or "no")
1341 send_message = "$send_message"
1342
1343 # config file for adduser ("/etc/adduser.conf")
1344 config = "$config"
1345
1346 # logfile ("/var/log/adduser" or "no")
1347 logfile = "$logfile"
1348
1349 # default HOME directory ("/home")
1350 home = "$home"
1351
1352 # List of directories where shells located
1353 # path = ('/bin', '/usr/bin', '/usr/local/bin')
1354 path = ($shpath)
1355
1356 # common shell list, first element has higher priority
1357 # shellpref = ('bash', 'tcsh', 'ksh', 'csh', 'sh')
1358 shellpref = ($shpref)
1359
1360 # defaultshell if not empty ("bash")
1361 defaultshell = "$defaultshell"
1362
1363 # defaultgroup ('USER' for same as username or any other valid group)
1364 defaultgroup = $defaultgroup
1365
1366 # defaultclass if not empty
1367 defaultclass = "$defaultclass"
1368
1369 # new users get this uid (1000)
1370 uid_start = 1000
1371
1372 $do_not_delete
1373 ## your own variables, see /etc/adduser.message
1374 $user_var
1375
1376 ## end
1377 EOF
1378 close C;
1379 }
1380
1381 ################
1382 # main
1383 #
1384 $test = 0; # test mode, only for development
1385 $check_only = 0;
1386
1387 &check_root; # you must be root to run this script!
1388 &variables; # initialize variables
1389 &config_read(@ARGV); # read variables form config-file
1390 &parse_arguments(@ARGV); # parse arguments
1391
1392 if (!$check_only && $#batch < 0) {
1393 &copyright; &hints;
1394 }
1395
1396 # check
1397 $changes = 0;
1398 &passwd_check; # check for valid passwdb
1399 &shells_read; # read /etc/shells
1400 &passwd_read; # read /etc/master.passwd
1401 &group_read; # read /etc/group
1402 &group_check; # check for incon*
1403 exit 0 if $check_only; # only check consistence and exit
1404
1405 exit(!&batch(@batch)) if $#batch >= 0; # batch mode
1406
1407 # interactive
1408 # some questions
1409 &shells_add; # maybe add some new shells
1410 $defaultshell = &shell_default; # enter default shell
1411 $home = &home_partition($home); # find HOME partition
1412 $dotdir = &dotdir_default; # check $dotdir
1413 $send_message = &message_default; # send message to new user
1414 $defaultpasswd = &password_default; # maybe use password
1415 &config_write(!$verbose); # write variables in file
1416
1417 # main loop for creating new users
1418 &new_users; # add new users
1419
1420 #end