Fixed a logic error that caused a problem later when the account name
[mirror/userdir-ldap.git] / ud-useradd
1 #!/usr/bin/env python
2 # -*- mode: python -*-
3
4 #   Copyright (c) 1999-2000  Jason Gunthorpe <jgg@debian.org>
5 #   Copyright (c) 2001-2003  James Troup <troup@debian.org>
6 #   Copyright (c) 2004  Joey Schulze <joey@infodrom.org>
7 #
8 #   This program is free software; you can redistribute it and/or modify
9 #   it under the terms of the GNU General Public License as published by
10 #   the Free Software Foundation; either version 2 of the License, or
11 #   (at your option) any later version.
12 #
13 #   This program is distributed in the hope that it will be useful,
14 #   but WITHOUT ANY WARRANTY; without even the implied warranty of
15 #   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 #   GNU General Public License for more details.
17 #
18 #   You should have received a copy of the GNU General Public License
19 #   along with this program; if not, write to the Free Software
20 #   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
21
22 import string, re, time, ldap, getopt, sys, os, pwd;
23 from userdir_ldap import *;
24 from userdir_gpg import *;
25
26 # This tries to search for a free UID. There are two possible ways to do
27 # this, one is to fetch all the entires and pick the highest, the other
28 # is to randomly guess uids until one is free. This uses the former.
29 # Regrettably ldap doesn't have an integer attribute comparision function
30 # so we can only cut the search down slightly
31
32 # [JT] This is broken with Woody LDAP and the Schema; for now just
33 #      search through all UIDs.
34 def GetFreeID(l):
35    Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,
36                       "uidNumber=*",["uidNumber"]);
37    HighestUID = 0;
38    for I in Attrs:
39       ID = int(GetAttr(I,"uidNumber","0"));
40       if ID > HighestUID:
41          HighestUID = ID;
42    return HighestUID + 1;
43
44 # Main starts here
45 AdminUser = pwd.getpwuid(os.getuid())[0];
46
47 # Process options
48 ForceMail = 0;
49 OldGPGKeyRings = GPGKeyRings;
50 userdir_gpg.GPGKeyRings = [];
51 (options, arguments) = getopt.getopt(sys.argv[1:], "u:ma")
52 for (switch, val) in options:
53    if (switch == '-u'):
54       AdminUser = val;
55    elif (switch == '-m'):
56       ForceMail = 1;
57    elif (switch == '-a'):
58       userdir_gpg.GPGKeyRings = OldGPGKeyRings;
59
60 print "Accessing LDAP directory as '" + AdminUser + "'";
61 while (1):
62    Password = getpass(AdminUser + "'s password: ");
63
64    if len(Password) == 0:
65       sys.exit(0)
66
67    l = ldap.open(LDAPServer);
68    UserDn = "uid=" + AdminUser + "," + BaseDn;
69
70    # Connect to the ldap server
71    try:
72       l.simple_bind_s(UserDn,Password);
73    except ldap.INVALID_CREDENTIALS:
74       continue
75    break
76
77 # Locate the key of the user we are adding
78 SetKeyrings(["/org/keyring.debian.org/keyrings/debian-keyring.gpg"])
79 while (1):
80    Foo = raw_input("Who are you going to add (for a GPG search)? ");
81    if Foo == "":
82       sys.exit(0);
83
84    Keys = GPGKeySearch(Foo);
85
86    if len(Keys) == 0:
87       print "Sorry, that search did not turn up any keys."
88       print "Has it been added to the Debian keyring already?"
89       continue;
90    if len(Keys) > 1:
91       print "Sorry, more than one key was found, please specify the key to use by\nfingerprint:";
92       for i in Keys:
93          GPGPrintKeyInfo(i);
94       continue;
95
96    print
97    print "A matching key was found:"
98    GPGPrintKeyInfo(Keys[0]);
99    break;
100
101 # Crack up the email address from the key into a best guess
102 # first/middle/last name
103 Addr = SplitEmail(Keys[0][2]);
104 (cn,mn,sn) = NameSplit(re.sub('["]','',Addr[0]))
105 email = Addr[1] + '@' + Addr[2];
106 account = Addr[1];
107
108 privsub = email;
109 gidNumber = str(DefaultGID);
110 uidNumber = 0;
111
112 # Decide if we should use IDEA encryption
113 UsePGP2 = 0;
114 while len(Keys[0][1]) < 40:
115    Res = raw_input("Use PGP2.x compatibility [no]? ");
116    if Res == "yes":
117       UsePGP2 = 1;
118       break;
119    if Res == "":
120       break;
121
122 Update = 0
123 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"keyFingerPrint=" + Keys[0][1]);
124 if len(Attrs) != 0:
125    print "*** This key already belongs to",GetAttr(Attrs[0],"uid");
126    account = GetAttr(Attrs[0],"uid");
127    Update = 1
128
129 # Try to get a uniq account name
130 while 1:
131    if Update == 0:
132       Res = raw_input("Login account [" + account + "]? ");
133       if Res != "":
134          account = Res;
135    Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid=" + account);
136    if len(Attrs) == 0:
137       privsub = "%s@debian.org"%(account);
138       break;
139    Res = raw_input("That account already exists, update [No/yes]? ");
140    if Res == "yes":
141       # Update mode, fetch the default values from the directory
142       Update = 1;
143       privsub = GetAttr(Attrs[0],"privateSub");
144       gidNumber = GetAttr(Attrs[0],"gidNumber");
145       uidNumber = GetAttr(Attrs[0],"uidNumber");
146       email = GetAttr(Attrs[0],"emailForward");
147       cn = GetAttr(Attrs[0],"cn");
148       sn = GetAttr(Attrs[0],"sn");
149       mn = GetAttr(Attrs[0],"mn");
150       if privsub == None or privsub == "":
151          privsub = " ";
152       break;
153    else:
154       sys.exit(1)
155
156 # Prompt for the first/last name and email address
157 Res = raw_input("First name [" + cn + "]? ");
158 if Res != "":
159    cn = Res;
160 Res = raw_input("Middle name [" + mn + "]? ");
161 if Res != "":
162    mn = Res;
163 Res = raw_input("Last name [" + sn + "]? ");
164 if Res != "":
165    sn = Res;
166 Res = raw_input("Email forwarding address [" + email + "]? ");
167 if Res != "":
168    email = Res;
169
170 # Debian-Private subscription
171 Res = raw_input("Subscribe to debian-private (space is none) [" + privsub + "]? ");
172 if Res != "":
173    privsub = Res;
174
175 # GID
176 Res = raw_input("Group ID Number [" + gidNumber + "]? ");
177 if Res != "":
178    gidNumber = Group2GID(Res);
179
180 # UID
181 if uidNumber == 0:
182    uidNumber = GetFreeID(l);
183
184 # Generate a random password
185 if Update == 0 or ForceMail == 1:
186    Password = raw_input("User's Password (Enter for random)? ");
187
188    if Password == "":
189       print "Randomizing and encrypting password"
190       Password = GenPass();
191       Pass = HashPass(Password);
192
193       # Use GPG to encrypt it, pass the fingerprint to ID it
194       CryptedPass = GPGEncrypt("Your new password is '" + Password + "'\n",\
195                                "0x"+Keys[0][1],UsePGP2);
196       Password = None;
197       if CryptedPass == None:
198         raise "Error","Password Encryption failed"
199    else:
200       Pass = HashPass(Password);
201       CryptedPass = "Your password has been set to the previously agreed value.";
202 else:
203    CryptedPass = "";
204    Pass = None;
205
206 # Now we have all the bits of information.
207 if mn != "":
208    FullName = "%s %s %s" % (cn,mn,sn);
209 else:
210    FullName = "%s %s" % (cn,sn);
211 print "------------";
212 print "Final information collected:"
213 print " %s <%s@%s>:" % (FullName,account,EmailAppend);
214 print "   Assigned UID:",uidNumber," GID:", gidNumber;
215 print "   Email forwarded to:",email;
216 print "   Private Subscription:",privsub;
217 print "   GECOS Field: \"%s,,,,\"" % (FullName);
218 print "   Login Shell: /bin/bash";
219 print "   Key Fingerprint:",Keys[0][1];
220 Res = raw_input("Continue [No/yes]? ");
221 if Res != "yes":
222    sys.exit(1);
223
224 # Initialize the substitution Map
225 Subst = {}
226 Subst["__REALNAME__"] = FullName;
227 Subst["__WHOAMI__"] = pwd.getpwuid(os.getuid())[0];
228 Subst["__DATE__"] = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()));
229 Subst["__LOGIN__"] = account;
230 Subst["__PRIVATE__"] = privsub;
231 Subst["__EMAIL__"] = email;
232 Subst["__PASSWORD__"] = CryptedPass;
233
234 # Submit the modification request
235 Dn = "uid=" + account + "," + BaseDn;
236 print "Updating LDAP directory..",
237 sys.stdout.flush();
238
239 if Update == 0:
240    # New account
241    Details = [("uid",account),
242               ("objectClass",
243                ("top","inetOrgPerson","debianAccount","shadowAccount","debianDeveloper")),
244               ("uidNumber",str(uidNumber)),
245               ("gidNumber",str(gidNumber)),
246               ("gecos",FullName+",,,,"),
247               ("loginShell","/bin/bash"),
248               ("keyFingerPrint",Keys[0][1]),
249               ("cn",cn),
250               ("sn",sn),
251               ("emailForward",email),
252               ("shadowLastChange",str(int(time.time()/24/60/60))),
253               ("shadowMin","0"),
254               ("shadowMax","99999"),
255               ("shadowWarning","7"),
256               ("userPassword","{crypt}"+Pass)];
257    if mn:
258       Details.append(("mn",mn));
259    if privsub != " ":
260       Details.append(("privateSub",privsub))
261    l.add_s(Dn,Details);
262 else:
263    # Modification
264    Rec = [(ldap.MOD_REPLACE,"uidNumber",str(uidNumber)),
265           (ldap.MOD_REPLACE,"gidNumber",str(gidNumber)),
266           (ldap.MOD_REPLACE,"gecos",FullName+",,,,"),
267           (ldap.MOD_REPLACE,"loginShell","/bin/bash"),
268           (ldap.MOD_REPLACE,"keyFingerPrint",Keys[0][1]),
269           (ldap.MOD_REPLACE,"cn",cn),
270           (ldap.MOD_REPLACE,"mn",mn),
271           (ldap.MOD_REPLACE,"sn",sn),
272           (ldap.MOD_REPLACE,"emailForward",email),
273           (ldap.MOD_REPLACE,"shadowLastChange",str(int(time.time()/24/60/60))),
274           (ldap.MOD_REPLACE,"shadowMin","0"),
275           (ldap.MOD_REPLACE,"shadowMax","99999"),
276           (ldap.MOD_REPLACE,"shadowWarning","7"),
277           (ldap.MOD_REPLACE,"shadowInactive",""),
278           (ldap.MOD_REPLACE,"shadowExpire","")];
279    if privsub != " ":
280       Rec.append((ldap.MOD_REPLACE,"privateSub",privsub));
281    if Pass != None:
282       Rec.append((ldap.MOD_REPLACE,"userPassword","{crypt}"+Pass));
283    # Do it
284    l.modify_s(Dn,Rec);
285
286 print;
287
288 # Abort email sends for an update operation
289 if Update == 1 and ForceMail == 0:
290    print "Account is not new, Not sending mails"
291    sys.exit(0);
292
293 # Send the Welcome message
294 print "Sending Welcome Email"
295 Reply = TemplateSubst(Subst,open(TemplatesDir+"/welcome-message-"+gidNumber,"r").read());
296 Child = os.popen("/usr/sbin/sendmail -t","w");
297 #Child = os.popen("cat","w");
298 Child.write(Reply);
299 if Child.close() != None:
300    raise Error, "Sendmail gave a non-zero return code";