source: trunk-3.0/examples/LDAP/smbldap-tools-0.9.2/smbldap-useradd@ 102

Last change on this file since 102 was 1, checked in by Paul Smedley, 18 years ago

Initial code import

File size: 20.5 KB
Line 
1#!/usr/bin/perl -w
2
3# $Id: smbldap-useradd,v 1.30 2006/01/02 17:01:19 jtournier Exp $
4#
5# This code was developped by IDEALX (http://IDEALX.org/) and
6# contributors (their names can be found in the CONTRIBUTORS file).
7#
8# Copyright (C) 2002 IDEALX
9#
10# This program is free software; you can redistribute it and/or
11# modify it under the terms of the GNU General Public License
12# as published by the Free Software Foundation; either version 2
13# of the License, or (at your option) any later version.
14#
15# This program is distributed in the hope that it will be useful,
16# but WITHOUT ANY WARRANTY; without even the implied warranty of
17# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18# GNU General Public License for more details.
19#
20# You should have received a copy of the GNU General Public License
21# along with this program; if not, write to the Free Software
22# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
23# USA.
24
25# Purpose of smbldap-useradd : user (posix,shadow,samba) add
26
27use strict;
28
29use FindBin;
30use FindBin qw($RealBin);
31use lib "$RealBin/";
32use smbldap_tools;
33use Crypt::SmbHash;
34#####################
35
36
37use Getopt::Std;
38my %Options;
39
40my $ok = getopts('o:abnmwiPG:u:g:d:s:c:k:t:A:B:C:D:E:F:H:M:N:S:T:?', \%Options);
41
42if ( (!$ok) || (@ARGV < 1) || ($Options{'?'}) ) {
43 print_banner;
44 print "Usage: $0 [-awmugdsckABCDEFGHMNPST?] username\n";
45 print " -o add the user in the organizational unit (relative to the user suffix)\n";
46 print " -a is a Windows User (otherwise, Posix stuff only)\n";
47 print " -b is a AIX User\n";
48 print " -w is a Windows Workstation (otherwise, Posix stuff only)\n";
49 print " -i is a trust account (Windows Workstation)\n";
50 print " -u uid\n";
51 print " -g gid\n";
52 print " -G supplementary comma-separated groups\n";
53 print " -n do not create a group\n";
54 print " -d home\n";
55 print " -s shell\n";
56 print " -c gecos\n";
57 print " -m creates home directory and copies /etc/skel\n";
58 print " -k skeleton dir (with -m)\n";
59 print " -t time. Wait 'time' seconds before exiting (when adding Windows Workstation)\n";
60 print " -P ends by invoking smbldap-passwd\n";
61 print " -A can change password ? 0 if no, 1 if yes\n";
62 print " -B must change password ? 0 if no, 1 if yes\n";
63 print " -C sambaHomePath (SMB home share, like '\\\\PDC-SRV\\homes')\n";
64 print " -D sambaHomeDrive (letter associated with home share, like 'H:')\n";
65 print " -E sambaLogonScript (DOS script to execute on login)\n";
66 print " -F sambaProfilePath (profile directory, like '\\\\PDC-SRV\\profiles\\foo')\n";
67 print " -H sambaAcctFlags (samba account control bits like '[NDHTUMWSLKI]')\n";
68 print " -N surname\n";
69 print " -S family name\n";
70 print " -M local mailAddress (comma seperated)\n";
71 print " -T mailToAddress (forward address) (comma seperated)\n";
72 print " -? show this help message\n";
73 exit (1);
74}
75
76my $ldap_master=connect_ldap_master();
77
78
79# cause problems when dealing with getpwuid because of the
80# negative ttl and ldap modification
81my $nscd_status = system "/etc/init.d/nscd status >/dev/null 2>&1";
82
83if ($nscd_status == 0) {
84 system "/etc/init.d/nscd stop > /dev/null 2>&1";
85}
86
87
88# Read only first @ARGV
89my $userName = $ARGV[0];
90
91# For computers account, add a trailing dollar if missing
92if (defined($Options{'w'})) {
93 if ($userName =~ /[^\$]$/s) {
94 $userName .= "\$";
95 }
96}
97
98# untaint $userName (can finish with one or two $)
99if ($userName =~ /^([\w -.]+\$?)$/) {
100 $userName = $1;
101} else {
102 print "$0: illegal username\n";
103 exit (1);
104}
105
106# user must not exist in LDAP (should it be nss-wide ?)
107my ($rc, $dn) = get_user_dn2($userName);
108if ($rc and defined($dn)) {
109 print "$0: user $userName exists\n";
110 exit (9);
111} elsif (!$rc) {
112 print "$0: error in get_user_dn2\n";
113 exit(10);
114}
115
116# Read options
117# we create the user in the specified ou (relative to the users suffix)
118my $user_ou=$Options{'o'};
119my $node;
120if (defined $user_ou) {
121 if (!($user_ou =~ m/^ou=(.*)/)) {
122 $node=$user_ou;
123 $user_ou="ou=$user_ou";
124 } else {
125 ($node)=($user_ou=~m/ou=(.*)/);
126 }
127 # $config{usersdn}="$user_ou,$config{usersdn}";
128 # if the ou does not exist, we create it
129 my $mesg = $ldap_master->search ( base => "$config{usersdn}",
130 scope => "one",
131 filter => "(&(objectClass=organizationalUnit)(ou=$node))"
132 );
133 $mesg->code && die $mesg->error;
134 if ($mesg->count eq 0) {
135 print "creating $user_ou first (as $user_ou,$config{usersdn})\n";
136 # add organizational unit
137 my $add = $ldap_master->add ("ou=$node,$config{usersdn}",
138 attr => [
139 'objectclass' => ['top','organizationalUnit'],
140 'ou' => "$node"
141 ]
142 );
143 $add->code && die "failed to add entry: ", $add->error ;
144 }
145 $config{usersdn}="$user_ou,$config{usersdn}";
146}
147
148my $userUidNumber = $Options{'u'};
149if (!defined($userUidNumber)) {
150 $userUidNumber=get_next_id($config{usersdn},"uidNumber");
151} elsif (getpwuid($userUidNumber)) {
152 die "Uid already exists.\n";
153}
154
155if ($nscd_status == 0) {
156 system "/etc/init.d/nscd start > /dev/null 2>&1";
157}
158
159my $createGroup = 0;
160my $userGidNumber = $Options{'g'};
161# gid not specified ?
162if (!defined($userGidNumber)) {
163 # windows machine => $config{defaultComputerGid}
164 if (defined($Options{'w'})) {
165 $userGidNumber = $config{defaultComputerGid};
166 # } elsif (!defined($Options{'n'})) {
167 # create new group (redhat style)
168 # find first unused gid starting from $config{GID_START}
169 # while (defined(getgrgid($config{GID_START}))) {
170 # $config{GID_START}++;
171 # }
172 # $userGidNumber = $config{GID_START};
173
174 # $createGroup = 1;
175
176 } else {
177 # user will have gid = $config{defaultUserGid}
178 $userGidNumber = $config{defaultUserGid};
179 }
180} else {
181 my $gid;
182 if (($gid = parse_group($userGidNumber)) < 0) {
183 print "$0: unknown group $userGidNumber\n";
184 exit (6);
185 }
186 $userGidNumber = $gid;
187}
188
189my $group_entry;
190my $userGroupSID;
191my $userRid;
192my $user_sid;
193if (defined $Options{'a'} or defined $Options{'i'}) {
194 # as grouprid we use the value of the sambaSID attribute for
195 # group of gidNumber=$userGidNumber
196 $group_entry = read_group_entry_gid($userGidNumber);
197 $userGroupSID = $group_entry->get_value('sambaSID');
198 unless ($userGroupSID) {
199 print "Error: SID not set for unix group $userGidNumber\n";
200 print "check if your unix group is mapped to an NT group\n";
201 exit (7);
202 }
203
204 # as rid we use 2 * uid + 1000
205 $userRid = 2 * $userUidNumber + 1000;
206 # let's test if this SID already exist
207 $user_sid="$config{SID}-$userRid";
208 my $test_exist_sid=does_sid_exist($user_sid,$config{usersdn});
209 if ($test_exist_sid->count == 1) {
210 print "User SID already owned by\n";
211 # there should not exist more than one entry, but ...
212 foreach my $entry ($test_exist_sid->all_entries) {
213 my $dn= $entry->dn;
214 chomp($dn);
215 print "$dn\n";
216 }
217 exit(7);
218 }
219}
220
221my $userHomeDirectory;
222my ($givenName,$userCN, $userSN);
223my @userMailLocal;
224my @userMailTo;
225my $tmp;
226if (!defined($userHomeDirectory = $Options{'d'})) {
227 $userHomeDirectory = &subst_user($config{userHome}, $userName);
228}
229# RFC 2256
230# sn: : nom (option S)
231# givenName: prenom (option N)
232# cn: person's full name
233$userHomeDirectory=~s/\/\//\//;
234$config{userLoginShell} = $tmp if (defined($tmp = $Options{'s'}));
235$config{userGecos} = $tmp if (defined($tmp = $Options{'c'}));
236$config{skeletonDir} = $tmp if (defined($tmp = $Options{'k'}));
237$givenName = (utf8Encode($Options{'N'}) || $userName);
238$userSN = (utf8Encode($Options{'S'}) || $userName);
239if ($Options{'N'} and $Options{'S'}) {
240 $userCN="$givenName"." $userSN";
241} else {
242 $userCN=$userName;
243}
244
245@userMailLocal = &split_arg_comma($Options{'M'});
246@userMailTo = &split_arg_comma($Options{'T'});
247
248########################
249
250# MACHINE ACCOUNT
251if (defined($Options{'w'}) or defined($Options{'i'})) {
252
253 # if Options{'i'} and username does not end with $ caracter => we add it
254 if ( $Options{'i'} and !($userName =~ m/\$$/) ) {
255 $userName.="\$";
256 }
257
258 if (!add_posix_machine ($userName,$userUidNumber,$userGidNumber,$Options{'t'})) {
259 die "$0: error while adding posix account\n";
260 }
261
262 if (defined($Options{'i'})) {
263 # For machine trust account
264 # Objectclass sambaSAMAccount must be added now !
265 my $pass;
266 my $pass2;
267
268 system "stty -echo";
269 print "New password : ";
270 chomp($pass=<STDIN>);
271 print "\n";
272 system "stty echo";
273
274 system "stty -echo";
275 print "Retype new password : ";
276 chomp($pass2=<STDIN>);
277 print "\n";
278 system "stty echo";
279
280 if ($pass ne $pass2) {
281 print "New passwords don't match!\n";
282 exit (10);
283 }
284 my ($lmpassword,$ntpassword) = ntlmgen $pass;
285 my $date=time;
286 my $modify = $ldap_master->modify ( "uid=$userName,$config{computersdn}",
287 changes => [
288 replace => [objectClass => ['top', 'person', 'organizationalPerson', 'inetOrgPerson', 'posixAccount', 'sambaSAMAccount']],
289 add => [sambaLogonTime => '0'],
290 add => [sambaLogoffTime => '2147483647'],
291 add => [sambaKickoffTime => '2147483647'],
292 add => [sambaPwdCanChange => '0'],
293 add => [sambaPwdMustChange => '2147483647'],
294 add => [sambaPwdLastSet => "$date"],
295 add => [sambaAcctFlags => '[I ]'],
296 add => [sambaLMPassword => "$lmpassword"],
297 add => [sambaNTPassword => "$ntpassword"],
298 add => [sambaSID => "$user_sid"],
299 add => [sambaPrimaryGroupSID => "$config{SID}-515"]
300 ]
301 );
302
303 $modify->code && die "failed to add entry: ", $modify->error ;
304 }
305
306 $ldap_master->unbind;
307 exit 0;
308}
309
310# USER ACCOUNT
311# add posix account first
312my $add;
313# if AIX account, inetOrgPerson obectclass can't be used
314if (defined($Options{'b'})) {
315 $add = $ldap_master->add ("uid=$userName,$config{usersdn}",
316 attr => [
317 'objectclass' => ['top','person', 'organizationalPerson', 'posixAccount','shadowAccount'],
318 'cn' => "$userCN",
319 'sn' => "$userSN",
320 'uid' => "$userName",
321 'uidNumber' => "$userUidNumber",
322 'gidNumber' => "$userGidNumber",
323 'homeDirectory' => "$userHomeDirectory",
324 'loginShell' => "$config{userLoginShell}",
325 'gecos' => "$config{userGecos}",
326 'userPassword' => "{crypt}x"
327 ]
328 );
329} else {
330 $add = $ldap_master->add ("uid=$userName,$config{usersdn}",
331 attr => [
332 'objectclass' => ['top','person', 'organizationalPerson', 'inetOrgPerson','posixAccount','shadowAccount'],
333 'cn' => "$userCN",
334 'sn' => "$userSN",
335 'givenName' => "$givenName",
336 'uid' => "$userName",
337 'uidNumber' => "$userUidNumber",
338 'gidNumber' => "$userGidNumber",
339 'homeDirectory' => "$userHomeDirectory",
340 'loginShell' => "$config{userLoginShell}",
341 'gecos' => "$config{userGecos}",
342 'userPassword' => "{crypt}x"
343 ]
344 );
345}
346$add->code && warn "failed to add entry: ", $add->error ;
347
348
349#if ($createGroup) {
350# group_add($userName, $userGidNumber);
351#}
352
353if ($userGidNumber != $config{defaultUserGid}) {
354 group_add_user($userGidNumber, $userName);
355}
356
357my $grouplist;
358# adds to supplementary groups
359if (defined($grouplist = $Options{'G'})) {
360 add_grouplist_user($grouplist, $userName);
361}
362
363# If user was created successfully then we should create his/her home dir
364if (defined($tmp = $Options{'m'})) {
365 unless ( $userName =~ /\$$/ ) {
366 if ( !(-e $userHomeDirectory) ) {
367 system "mkdir $userHomeDirectory 2>/dev/null";
368 system "cp -a $config{skeletonDir}/.[a-z,A-Z]* $config{skeletonDir}/* $userHomeDirectory 2>/dev/null";
369 system "chown -R $userUidNumber:$userGidNumber $userHomeDirectory 2>/dev/null";
370 if (defined $config{userHomeDirectoryMode}) {
371 system "chmod $config{userHomeDirectoryMode} $userHomeDirectory 2>/dev/null";
372 } else {
373 system "chmod 700 $userHomeDirectory 2>/dev/null";
374 }
375 }
376 }
377}
378
379# we start to defined mail adresses if option M or T is given in option
380my @adds;
381if (@userMailLocal) {
382 my @mail;
383 foreach my $m (@userMailLocal) {
384 my $domain = $config{mailDomain};
385 if ($m =~ /^(.+)@/) {
386 push (@mail, $m);
387 # mailLocalAddress contains only the first part
388 $m= $1;
389 } else {
390 push(@mail, $m.($domain ? '@'.$domain : ''));
391 }
392 }
393 push(@adds, 'mailLocalAddress' => [ @userMailLocal ]);
394 push(@adds, 'mail' => [ @mail ]);
395}
396if (@userMailTo) {
397 push(@adds, 'mailRoutingAddress' => [ @userMailTo ]);
398}
399if (@userMailLocal || @userMailTo) {
400 push(@adds, 'objectClass' => 'inetLocalMailRecipient');
401}
402
403# Add Samba user infos
404if (defined($Options{'a'})) {
405 if (!$config{with_smbpasswd}) {
406
407 my $winmagic = 2147483647;
408 my $valpwdcanchange = 0;
409 my $valpwdmustchange = $winmagic;
410 my $valpwdlastset = 0;
411 my $valacctflags = "[UX]";
412
413 if (defined($tmp = $Options{'A'})) {
414 if ($tmp != 0) {
415 $valpwdcanchange = "0";
416 } else {
417 $valpwdcanchange = "$winmagic";
418 }
419 }
420
421 if (defined($tmp = $Options{'B'})) {
422 if ($tmp != 0) {
423 $valpwdmustchange = "0";
424 # To force a user to change his password:
425 # . the attribut sambaPwdLastSet must be != 0
426 # . the attribut sambaAcctFlags must not match the 'X' flag
427 $valpwdlastset=$winmagic;
428 $valacctflags = "[U]";
429 } else {
430 $valpwdmustchange = "$winmagic";
431 }
432 }
433
434 if (defined($tmp = $Options{'H'})) {
435 $valacctflags = "$tmp";
436 }
437
438
439 my $modify = $ldap_master->modify ( "uid=$userName,$config{usersdn}",
440 changes => [
441 add => [objectClass => 'sambaSAMAccount'],
442 add => [sambaPwdLastSet => "$valpwdlastset"],
443 add => [sambaLogonTime => '0'],
444 add => [sambaLogoffTime => '2147483647'],
445 add => [sambaKickoffTime => '2147483647'],
446 add => [sambaPwdCanChange => "$valpwdcanchange"],
447 add => [sambaPwdMustChange => "$valpwdmustchange"],
448 add => [displayName => "$config{userGecos}"],
449 add => [sambaAcctFlags => "$valacctflags"],
450 add => [sambaSID => "$config{SID}-$userRid"]
451 ]
452 );
453
454 $modify->code && die "failed to add entry: ", $modify->error ;
455
456 } else {
457 my $FILE="|smbpasswd -s -a $userName >/dev/null" ;
458 open (FILE, $FILE) || die "$!\n";
459 print FILE <<EOF;
460x
461x
462EOF
463 ;
464 close FILE;
465 if ($?) {
466 print "$0: error adding samba account\n";
467 exit (10);
468 }
469 } # with_smbpasswd
470
471 $tmp = defined($Options{'E'}) ? $Options{'E'} : $config{userScript};
472 my $valscriptpath = &subst_user($tmp, $userName);
473
474 $tmp = defined($Options{'C'}) ? $Options{'C'} : $config{userSmbHome};
475 my $valsmbhome = &subst_user($tmp, $userName);
476
477 my $valhomedrive = defined($Options{'D'}) ? $Options{'D'} : $config{userHomeDrive};
478 # if the letter is given without the ":" symbol, we add it
479 $valhomedrive .= ':' if ($valhomedrive && $valhomedrive !~ /:$/);
480
481 $tmp = defined($Options{'F'}) ? $Options{'F'} : $config{userProfile};
482 my $valprofilepath = &subst_user($tmp, $userName);
483
484 if ($valhomedrive) {
485 push(@adds, 'sambaHomeDrive' => $valhomedrive);
486 }
487 if ($valsmbhome) {
488 push(@adds, 'sambaHomePath' => $valsmbhome);
489 }
490
491 if ($valprofilepath) {
492 push(@adds, 'sambaProfilePath' => $valprofilepath);
493 }
494 if ($valscriptpath) {
495 push(@adds, 'sambaLogonScript' => $valscriptpath);
496 }
497 if (!$config{with_smbpasswd}) {
498 push(@adds, 'sambaPrimaryGroupSID' => $userGroupSID);
499 push(@adds, 'sambaLMPassword' => "XXX");
500 push(@adds, 'sambaNTPassword' => "XXX");
501 }
502 my $modify = $ldap_master->modify ( "uid=$userName,$config{usersdn}",
503 add => {
504 @adds
505 }
506 );
507
508 $modify->code && die "failed to add entry: ", $modify->error ;
509}
510
511# add AIX user
512if (defined($Options{'b'})) {
513 my $modify = $ldap_master->modify ( "uid=$userName,$config{usersdn}",
514 changes => [
515 add => [objectClass => 'aixAuxAccount'],
516 add => [passwordChar => "!"],
517 add => [isAdministrator => "false"]
518 ]
519 );
520
521 $modify->code && die "failed to add entry: ", $modify->error ;
522}
523
524
525$ldap_master->unbind; # take down session
526
527
528if (defined($Options{'P'})) {
529 exec "$RealBin/smbldap-passwd \"$userName\""
530}
531
532exit 0;
533
534########################################
535
536=head1 NAME
537
538smbldap-useradd - Create a new user
539
540=head1 SYNOPSIS
541
542smbldap-useradd [-o user_ou] [-c comment] [-d home_dir] [-g initial_group] [-G group[,...]] [-m [-k skeleton_dir]] [-s shell] [-u uid [ -o]] [-P] [-A canchange] [-B mustchange] [-C smbhome] [-D homedrive] [-E scriptpath] [-F profilepath] [-H acctflags] login
543
544=head1 DESCRIPTION
545
546Creating New Users
547 The smbldap-useradd command creates a new user account using the values specified on the command line and the default values from the system and from the configuration files (in /etc/smbldap-tools directory).
548
549For Samba users, rid is '2*uidNumber+1000', and sambaPrimaryGroupSID is '$SID-2*gidNumber+1001', where $SID is the domain SID. Thus you may want to use :
550 $ smbldap-useradd -a -g "Domain Admins" -u 500 Administrator
551 to create an domain administrator account (admin rid is 0x1F4 = 500 and grouprid is 0x200 = 512).
552
553Without any option, the account created will be an Unix (Posix) account. The following options may be used to add information:
554
555-o
556The user's account will be created in the specified organazional unit. It is relative to the user suffix dn ($usersdn) defined in the configuration file.
557
558-a
559The user will have a Samba account (and Unix).
560
561-b
562The usrer is an AIX acount
563
564-w
565 Creates an account for a Samba machine (Workstation), so that it can join a sambaDomainName.
566
567-i
568 Creates an interdomain trust account (machine Workstation). A password will be asked for the trust account.
569
570-c "comment"
571 The new user's comment field (gecos).
572
573-d home_dir
574 The new user will be created using home_dir as the value for the user's login directory. The default is to append the login name to userHomePrefix (defined in the configuration file) and use that as the login directory name.
575
576-g initial_group
577 The group name or number of the user's initial login group. The group name must exist. A group number must refer to an already existing group. The default group number is defined in the configuration file (defaultUserGid="513").
578
579-G group,[...]
580 A list of supplementary groups which the user is also a member of. Each group is separated to the next by a comma, with no intervening whitespace. The groups are subject to the same restrictions as the group given with the -g option. The default is for the user to belong only to the initial group.
581
582-m
583The user's home directory will be created if it does not exist. The files contained in skeletonDir will be copied to the home directory if the -k option is used, otherwise the files contained in /etc/skel will be used instead. Any directories contained in skeletonDir or /etc/skel will be created in the user's home directory as well. The -k option is only valid in conjunction with the -m option. The default is to not create the directory and to not copy any files.
584
585-s shell
586 The name of the user's login shell. The default is to leave this field blank, which causes the system to select the default login shell.
587
588-t time
589 Wait <time> seconds before exiting script when adding computer's account. This is useful when Master/PDC and Slaves/BDCs are connected through the internet (replication is not real time)
590
591-u uid
592 The numerical value of the user's ID. This value must be unique, unless the -o option is used. The value must be nonnegative. The default is to use the smallest ID value greater than 1000 and greater than every other user.
593
594-P
595 ends by invoking smbldap-passwd
596
597-A
598 can change password ? 0 if no, 1 if yes
599
600-B
601 must change password ? 0 if no, 1 if yes
602
603-C sambaHomePath
604 SMB home share, like '\\\\PDC-SRV\\homes'
605
606-D sambaHomeDrive
607 letter associated with home share, like 'H:'
608
609-E sambaLogonScript
610 relative to the [netlogon] share (DOS script to execute on login, like 'foo.bat'
611
612-F sambaProfilePath
613 profile directory, like '\\\\PDC-SRV\\profiles\\foo'
614
615-H sambaAcctFlags
616 spaces and trailing bracket are ignored (samba account control bits like '[NDHTUMWSLKI]'
617
618-M local mail aliases (multiple addresses are seperated by spaces)
619
620-N canonical name
621 defaults to gecos or username, if gecos not set
622
623-S surname
624 defaults to username
625
626-T mailToAddress (forward address) (multiple addresses are seperated by spaces)
627
628-n do not print banner message
629
630=head1 SEE ALSO
631
632 useradd(1)
633
634=cut
635
636#'
Note: See TracBrowser for help on using the repository browser.