summaryrefslogtreecommitdiffstats
path: root/adduser/adduser.perl
blob: 60e89e73c8924faf2c15f999b786ac2861c44058 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
#!/usr/bin/perl
#
# (c) Copyright 1995 Wolfram Schneider. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions and the following disclaimer in the
#    documentation and/or other materials provided with the distribution.
# 3. All advertising materials mentioning features or use of this software
#    must display the following acknowledgement:
#   This product includes software developed by Wolfram Schneider
# 4. The name of the author may not be used to endorse or promote products
#    derived from this software without specific prior written permission
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
# IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
# NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
# THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# /usr/sbin/adduser - add new user(s)
#
# Bugs: sure (my english!)
#   Email: Wolfram Schneider <wosch@cs.tu-berlin.de>
#
# $Id: adduser,v 1.17 1995/01/02 00:08:43 w Exp w $
#

sub variables {
    $verbose = 1;
    $batch = 0;                         # batch mode
    $defaultpasswd = 0;
    $dotdir = "/usr/share/skel";

    if (1) {
    $home = "/home";
    $shells = "/etc/shells";
    $passwd = "/etc/master.passwd";
    $group = "/etc/group";
    $pwd_mkdb = "pwd_mkdb -p";
    } else {
    $home = "/home/w/tmp/adduser/home";
    $shells = "./shells";
    $passwd = "./master.passwd";
    $group = "./group";
    $pwd_mkdb = "pwd_mkdb -p -d .";
    }

    @path = ('/bin', '/usr/bin', '/usr/local/bin');
    @shellpref = ('bash', 'tcsh', 'ksh', 'csh', 'sh');
    $uid_start = 1000;      # new users get this uid
    $uid_end   = 32000;

    # global variables
    $username = '';         # $username{username} = uid
    $uid = '';              # $uid{uid} = username
    $pwgid = '';            # $pwgid{pwgid} = username; gid from passwd db
    $groupname ='';         # $groupname{groupname} = gid
    $gid = '';              # $gid{gid} = groupname;    gid form group db
    $defaultshell = '';
    @passwd_backup = '';
}

# read shell database
# See also: shells(5)
sub shells_read {
    local($s, @dummy);
    open(S, $shells) || die "$shells:$!\n";
    while(<S>) {
        if (/^[ \t]*\//) {
            ($s, @dummy) = split;
            if (-x  $s) {
                $shell{&basename($s)} = $s;
            } else {
                warn "Shell: $s not executable!\n";
            }
        }
    }
}

# add new/local shells
sub shells_add {
    local($e,$dir,@list);
    foreach $e (@shellpref) {
        if (!$shell{$e}) {
            foreach $dir (@path) {
                if (-x "$dir/$e") {
                    push(@list, "$dir/$e") if
                    &confirm_yn("Found shell: $dir/$e. Add to $shells?", "yes");
                }
            }
        }
    }
    if ($#list >= 0) {
        foreach $e (@list) {
            $shell{&basename($e)} = $e;
            #print "$e\n";
        }
        &append_file($shells, @list);
    }
}

# choise your favourite shell
sub shells_pref {
    local($e,$i,$s);

    $i = 0;
    while($i < $#shellpref) {
        last if $shell{$shellpref[$i]};
        $i++;
    }
    $s = &confirm_list("Enter Your default shell:", 0,
                        $shellpref[$i], sort(keys %shell));
    print "Your default shell is: $s -> $shell{$s}\n" if $verbose;
    $defaultshell = $s;
}

# return default home partition
sub home_partition {
    local($h);

    $h = &confirm_list("Enter Your default HOME partition:", 1, $home, "");
    if (-e "$h") {
        if (!(-d _ || -l $h)) {
            warn "$h exist, but is it not a directory or symlink!\n";
            return &home_partition;
        }
        if (! -w _) {
            warn "$h is not writable!\n";
            return &home_partition;
        }
    } else {
        return &home_partition unless &mkdirhier($h);
    }
	
	$home = $h;
    return $h;
}

# check for valid passwddb
sub passwd_check {
    print "Check $passwd\n" if $verbose > 0;
    system("$pwd_mkdb $passwd");
    die "\nInvalid $passwd - cannot add any users!\n" if $?;
}

# read /etc/passwd
sub passwd_read {
    local($un, $pw, $ui, $gi);

    open(P, "$passwd") || die "$passwd: $!\n";
    while(<P>) {
        chop;
        push(@passwd_backup, $_);
        ($un, $pw, $ui, $gi) = (split(/:/, $_))[0..3];
        print "$un already exist with uid: $username{$un}!\n"
            if $username{$un};
        $username{$un} = $ui;
        print "User $un: uid $ui exist twice: $uid{$ui}\n"
            if $uid{$ui} && $verbose;
        $uid{$ui} = $un;
        $pwgid{$gi} = $un;
    }
    close P;
}

# read /etc/group
sub group_read {
    local($gn,$pw,$gi);

    open(G, "$group") || die "$group: $!\n";
    while(<G>) {
        ($gn, $pw, $gi) = (split(/:/, $_))[0..2];
        warn "Groupname exist twice: $gn:$gi -> $gn:$groupname{$gn}\n"
            if $groupname{$gn};
        $groupname{$gn} = $gi;
        warn "Groupid exist twice:   $gn:$gi -> $gid{$gi}:$gi\n"
            if $gid{$gi};
        $gid{$gi} = $gn;
    }
    close G;
}

# check gids /etc/passwd <-> /etc/group
sub group_check {
    local($e, $user, @list);

    foreach $e (keys %pwgid) {
        if (!$gid{$e}) {
            $user = $pwgid{$e};
            warn "Gid $e is defined in $passwd for user ``$user''\n";
            warn "but not in $group!\n";
            if ($groupname{$user}) {
                warn <<EOF;
I'm confused! Maybe the gids ($e <-> $groupname{$user}) for user ``$user''
in $passwd & $group are wrong.
See $passwd ``$user:*:$username{$user}:$e''
See $group ``$user:*:$groupname{$user}''
EOF
            } else {
                push(@list, "$user:*:$e:$user")
                if (&confirm_yn("Add group``$user'' gid $e to $group?", "y"));
            }
        }
    }
    &append_file($group, @list) if $#list >= 0;
}

sub new_users {
    local(@userlist) = @_;
    local($name);
    local($defaultname) = "a-z0-9";

    print "\nOk, let's go.\n";
    print "Don't worry about mistakes. I ask You later for " .
          "correct input.\n" if $verbose;

    while(1) {
        $name = &confirm_list("Enter username", 1, $defaultname, "");
        if ($name !~ /^[a-z0-9]+$/) {
            warn "Wrong username. " .
                "Please use only lowercase characters or digits\n";
        } elsif ($username{$name}) {
            warn "Username ``$name'' already exists!\n";
        } else {
            last;
        }
    }
    local($fullname);
    while(($fullname = &confirm_list("Enter full name", 1, "", "")) =~ /:/) {
        warn "``:'' is not allowed!\n";
    }
    $fullname = $name unless $fullname;
    local($sh) = &confirm_list("Enter shell", 0, $defaultshell, keys %shell);
    $sh = $shell{$sh};
    local($u_id, $g_id) = &next_id($name);
    print <<EOF;

Name:     $name
Passwd:   none, is empty
Fullname: $fullname
Uid:      $u_id
Gid:      $g_id
HOME:     $home/$name
Shell:    $sh
EOF
    if (&confirm_yn("Ok?", "yes")) {
        local($new_entry) =
            "$name::$u_id:$g_id::0:0:$fullname:$home/$name:$sh";

        &append_file($passwd, $new_entry);

        system("$pwd_mkdb $passwd");
        if ($?) {
            local($crash) = "$passwd.crash$$";
            warn "$pwd_mkdb failed, try to restore ...\n";

            open(R, "> $crash") || die "Sorry, give up\n";
            $j = join("\n", @passwd_backup);
            $j =~ s/\n//;
            print R $j . "\n";
            close R;

            system("$pwd_mkdb $crash");
            die "Sorry, give up\n" if $?;
            die "Successfully restore $passwd. Exit.\n";
        }
        # Add new group
        &append_file($group, "$name:*:$g_id:$name")
            unless $groupname{$name};

        # update passwd/group variables
        push(@passwd_backup, $new_entry);
        $username{$name} = $u_id;
        $uid{$u_id} = $name;
        $pwgid{$g_id} = $name;
        $groupname{$name} = $g_id;
        $gid{$g_id} = $name;

        print "Added user ``$name''\n";
        local($a) = &confirm_yn("Change password", $defaultpasswd);
        if (($a && $defaultpasswd) || (!$a && !$defaultpasswd)) {
            while(1) {
                system("passwd $name");
                last unless $?;
                last unless
                    &confirm_yn("Passwd $name failed. Try again?", "yes");
            }
        }
    	&home_create($name);
	}
   	if (&confirm_yn("Continue with next user?", "yes")) {
       	&new_users;
    } else {
        print "Good by.\n" if $verbose;
    }
}

#
sub password_pref {
    $defaultpasswd = !&confirm_yn("Use empty passwords", "yes");
}

# misc
sub check_root {
    die "You are not root!\n" if $<;
}

sub usage {
    warn <<USAGE;

usage: adduser [options]

OPTIONS:
-help                   this help
-silent                 opposite of verbose
-verbose                verbose
-home home              default HOME partition [$home]
-shell shell            default SHELL
-dotdir dir             copy files from dir, default $dotdir
USAGE
    exit 1;
}

#
sub parse_arguments {
    local(@argv) = @_;

    while ($_ = $argv[0], /^-/) {
        shift @argv;
        last if /^--$/;
        if    (/^--?(debug|verbose)$/)  { $verbose = 1 }
        elsif (/^--?(silent|guru|wizard)$/) { $verbose = 0 }
        elsif (/^--?(verbose)$/)        { $verbose = 1 }
        elsif (/^--?(h|help|\?)$/)      { &usage }
        elsif (/^--?(home)$/)           { $home = $argv[0]; shift @argv }
        elsif (/^--?(shell)$/)          { $shell = $argv[0]; shift @argv }
        elsif (/^--?(dotdir)$/)         { $dotdir = $argv[0]; shift @argv }
        elsif (/^--?(batch)$/)          { $batch = 1; }
        else                            { &usage }
    }
    #&usage if $#argv < 0;
}

sub basename {
    local($name) = @_;
    $name =~ s|.*/||;
    return $name;
}

#
sub home_create {
    local($name) = @_;
    local(@list);
    local($e,$from, $to);

    print "Create HOME directory\n";
    if(!mkdir("$home/$name", 0755)) {
        warn "Cannot create HOME directory for $name: $!\n";
        return 0;
    }
    push(@list, "$home/$name");
    if ($dotdir) {
        opendir(D, "$dotdir") || warn "$dotdir: $!\n";
        foreach $from (readdir(D)) {
            if ($from !~ /^(\.|\.\.)$/) {
                $to = $from;
                $to =~ s/^dot\././;
                $to = "$home/$name/$to";
                push(@list, $to);
                &cp("$dotdir/$from", "$to", 1);
            }
        }
        closedir D;
    }
	#warn "Chown: $name, $name, @list\n";
	#chown in perl does not work 
    system("chown $name:$name @list") || warn "$!\n" && return 0;
    return 1;
}

# makes a directory hierarchy
sub mkdirhier {
    local($dir) = @_;

    if ($dir =~ "^/[^/]+$") {
        print "Create /usr/$dir\n" if $verbose;
        if (!mkdir("/usr$dir", 0755)) {
            warn "/usr/$dir: $!\n"; return 0;
        }
        print "Create symlink: /usr$dir -> $dir\n" if $verbose;
        if (!symlink("/usr$dir", $dir)) {
            warn "$dir: $!\n"; return 0;
        }
    } else {
        local($d,$p);
        foreach $d (split('/', $dir)) {
            $dir = "$p/$d";
            $dir =~ s|^//|/|;
            if (! -e "$dir") {
                print "Create $dir\n" if $verbose;
                if (!mkdir("$dir", 0755)) {
                    warn "$dir: $!\n"; return 0;
                }
            }
            $p .= "/$d";
        }
    }
    return 1;
}


# Read one of the elements from @list. $confirm is default.
# If !$allow accept only elements from @list.
sub confirm_list {
    local($message, $allow, $confirm, @list) = @_;
    local($read, $c);

    print "$message " if $message;
    print "@list [$confirm]: ";
    chop($read = <STDIN>);
    $read =~ s/^[ \t]*//;
    $read =~ s/[ \t\n]*$//;
    return $confirm unless $read;
    return $read if $allow;

    foreach $c (@list) {
        return $read if $c eq $read;
    }
    warn "$read: is not allowed!\n";
    return &confirm_list($message, $allow, $confirm, @list);
}

# YES or NO question
# $confirm => 'y' or 'n'. Return true if answer 'y' (or 'n')
sub confirm_yn {
    local($message, $confirm) = @_;
    local($yes) = "^(yes|YES|y|Y)$";
    local($no) = "^(no|NO|n|N)$";
    local($read, $c);

    if ($confirm && ($confirm =~ "$yes" || $confirm == 1)) {
        $confirm = "y";
    } else {
        $confirm = "n";
    }
    print "$message (y/n) [$confirm]: ";
    chop($read = <STDIN>);
    $read =~ s/^[ \t]*//;
    $read =~ s/[ \t\n]*$//;
    return 1 unless $read;

    if (($confirm eq "y" && $read =~ "$yes") ||
        ($confirm eq "n" && $read =~ "$no")) {
        return 1;
    }

    if ($read !~ "$yes" && $read !~ "$no") {
        warn "Wrong value. Enter again!\a\n";
        return &confirm_yn($message, $confirm);
    }
    return 0;
}

# test if $dotdir exist
sub dotdir_check {
    return 1 if -e $dotdir && -r _ && (-d _ || -l $dotdir);
    warn "Directory: $dotdir does not exist or unreadable. " .
         "Cannot copy dotfiles!\n";
    $dotdir = '';
    return 0;
}

# write @list to $file with file-locking
sub append_file {
    local($file,@list) = @_;
    local($e);
    local($LOCK_EX) = 2;
    local($LOCK_UN) = 8;

    open(F, ">> $file") || die "$file: $!\n";
    print "Lock $file.\n" if $verbose > 1;
    flock(F, $LOCK_EX);
    print F join("\n", @list) . "\n";
    close F;
    print "Unlock $file.\n" if $verbose > 1;
    flock(F, $LOCK_UN);
}

# return free uid+gid
# uid == gid if possible
sub next_id {
    local($group) = @_;

    # looking for next free uid
    while($uid{$uid_start}) {
        $uid_start++;
        print "$uid_start\n" if $verbose > 1;
    }

    local($gid_start) = $uid_start;
    # group for user (username==groupname) already exist
    if ($groupname{$group}) {
        $gid_start = $groupname{$group};
    }
    # gid is in use, looking for another gid.
    # Note: uid an gid are not equal
    elsif ($gid{$uid_start}) {
        while($gid{$gid_start} || $uid{$gid_start}) {
            $gid_start--;
            $gid_start = $uid_end if $gid_start < 100;
        }
    }
    return ($uid_start, $gid_start);
}

sub cp {
    local($from, $to, $tilde) = @_;

    if (-e "$to") {
        warn "cp: ``$to'' already exist, do not overwrite\n"; return 0;
    } elsif (!(-f $from || -l $from)) {
        warn "$from is not a file or symlink!\n"; return 0;
    } elsif (!open(F, "$from")) {
        warn "$from: $!\n"; return 0;
    } elsif (!open(T, "> $to")) {
        warn "$to: $!\n"; return 0;
    }

    if ($tilde) {
        $tilde = $to;
        $tilde =~ s|.*/([^/]+/[^/]+)$|~$1|;
    } else {
        $tilde = $to;
    }
    print "copy $from to $tilde\n" if $verbose;
    while(<F>) {
        print T $_;
    }

    close F;
    close T;
    return 1;
}

################
# main
#
&check_root;            # You must be root to run this script!
&variables;             # initialize variables
&parse_arguments(@ARGV);    # parse arguments

&passwd_check;          # check for valid passwdb
&passwd_read;           # read /etc/master.passwd
&group_read;            # read /etc/group
&group_check;           # check for incon*
&dotdir_check;          # check $dotdir
print "\n";
&home_partition;        # find HOME partition
&shells_read;           # read /etc/shells
&shells_add;            # maybe add some new shells
&shells_pref;           # enter default shell
&password_pref;         # maybe use password

&new_users;             # add new users

#end