cast objects to strings (rt #1717)
[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 re, time, ldap, getopt, sys, os, pwd;
23 import email.Header
24
25 from userdir_ldap import *;
26 from userdir_gpg import *;
27
28 # This tries to search for a free UID. There are two possible ways to do
29 # this, one is to fetch all the entires and pick the highest, the other
30 # is to randomly guess uids until one is free. This uses the former.
31 # Regrettably ldap doesn't have an integer attribute comparision function
32 # so we can only cut the search down slightly
33
34 # [JT] This is broken with Woody LDAP and the Schema; for now just
35 #      search through all UIDs.
36 def GetFreeID(l):
37    Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,
38                       "uidNumber=*",["uidNumber", "gidNumber"]);
39    HighestUID = 0;
40    gids = [];
41    for I in Attrs:
42       ID = int(GetAttr(I,"uidNumber","0"));
43       gids.append(int(GetAttr(I, "gidNumber","0")))
44       if ID > HighestUID:
45          HighestUID = ID;
46
47    resGID = HighestUID + 1;
48    while resGID in gids:
49       resGID += 1
50
51    return (HighestUID + 1, resGID);
52
53 # Main starts here
54 AdminUser = pwd.getpwuid(os.getuid())[0];
55
56 # Process options
57 ForceMail = 0;
58 NoAutomaticIDs = 0;
59 OldGPGKeyRings = GPGKeyRings;
60 userdir_gpg.GPGKeyRings = [];
61 (options, arguments) = getopt.getopt(sys.argv[1:], "u:man")
62 for (switch, val) in options:
63    if (switch == '-u'):
64       AdminUser = val;
65    elif (switch == '-m'):
66       ForceMail = 1;
67    elif (switch == '-a'):
68       userdir_gpg.GPGKeyRings = OldGPGKeyRings;
69    elif (switch == '-n'):
70       NoAutomaticIDs = 1;
71
72 l = passwdAccessLDAP(BaseDn, AdminUser)
73
74 # Locate the key of the user we are adding
75 SetKeyrings(ConfModule.add_keyrings.split(":"))
76 while (1):
77    Foo = raw_input("Who are you going to add (for a GPG search)? ");
78    if Foo == "":
79       sys.exit(0);
80
81    Keys = GPGKeySearch(Foo);
82
83    if len(Keys) == 0:
84       print "Sorry, that search did not turn up any keys."
85       print "Has it been added to the Debian keyring already?"
86       continue;
87    if len(Keys) > 1:
88       print "Sorry, more than one key was found, please specify the key to use by\nfingerprint:";
89       for i in Keys:
90          GPGPrintKeyInfo(i);
91       continue;
92
93    print
94    print "A matching key was found:"
95    GPGPrintKeyInfo(Keys[0]);
96    break;
97
98 # Crack up the email address from the key into a best guess
99 # first/middle/last name
100 Addr = SplitEmail(Keys[0][2]);
101 (cn,mn,sn) = NameSplit(re.sub('["]','',Addr[0]))
102 emailaddr = Addr[1] + '@' + Addr[2];
103 account = Addr[1];
104
105 privsub = emailaddr
106 gidNumber = 0;
107 uidNumber = 0;
108
109 # Decide if we should use IDEA encryption
110 UsePGP2 = 0;
111 while len(Keys[0][1]) < 40:
112    Res = raw_input("Use PGP2.x compatibility [No/yes]? ");
113    if Res == "yes":
114       UsePGP2 = 1;
115       break;
116    if Res == "":
117       break;
118
119 Update = 0
120 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"keyFingerPrint=" + Keys[0][1]);
121 if len(Attrs) != 0:
122    print "*** This key already belongs to",GetAttr(Attrs[0],"uid");
123    account = GetAttr(Attrs[0],"uid");
124    Update = 1
125
126 # Try to get a uniq account name
127 while 1:
128    if Update == 0:
129       Res = raw_input("Login account [" + account + "]? ");
130       if Res != "":
131          account = Res;
132    Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid=" + account);
133    if len(Attrs) == 0:
134       privsub = "%s@debian.org"%(account);
135       break;
136    Res = raw_input("That account already exists, update [No/yes]? ");
137    if Res == "yes":
138       # Update mode, fetch the default values from the directory
139       Update = 1;
140       privsub = GetAttr(Attrs[0],"privateSub");
141       gidNumber = GetAttr(Attrs[0],"gidNumber");
142       uidNumber = GetAttr(Attrs[0],"uidNumber");
143       emailaddr = GetAttr(Attrs[0],"emailForward");
144       cn = GetAttr(Attrs[0],"cn");
145       sn = GetAttr(Attrs[0],"sn");
146       mn = GetAttr(Attrs[0],"mn");
147       if privsub == None or privsub == "":
148          privsub = " ";
149       break;
150    else:
151       sys.exit(1)
152
153 # Prompt for the first/last name and email address
154 Res = raw_input("First name [" + cn + "]? ");
155 if Res != "":
156    cn = Res;
157 Res = raw_input("Middle name [" + mn + "]? ");
158 if Res == " ":
159    mn = ""
160 elif Res != "":
161    mn = Res;
162 Res = raw_input("Last name [" + sn + "]? ");
163 if Res != "":
164    sn = Res;
165 Res = raw_input("Email forwarding address [" + emailaddr + "]? ");
166 if Res != "":
167    emailaddr = Res;
168
169 # Debian-Private subscription
170 Res = raw_input("Subscribe to debian-private (space is none) [" + privsub + "]? ");
171 if Res != "":
172    privsub = Res;
173
174 (uidNumber, generatedGID) = GetFreeID(l)
175 if not gidNumber:
176    gidNumber = DefaultGID
177 UserGroup = 0
178
179 if NoAutomaticIDs:
180    # UID
181    if not Update:
182       Res = raw_input("User ID Number [%s]? " % (uidNumber));
183       if Res != "":
184          uidNumber = Res;
185    
186    # GID
187    Res = raw_input("Group ID Number (default group is %s, new usergroup %s) [%s]" % (DefaultGID, generatedGID, gidNumber));
188    if Res != "":
189       if Res.isdigit():
190          gidNumber = Res;
191       else:
192          gidNumber = Group2GID(l, Res);
193    
194    if gidNumber == generatedGID:
195       UserGroup = 1
196
197 # Generate a random password
198 if Update == 0 or ForceMail == 1:
199    Password = raw_input("User's Password (Enter for random)? ");
200
201    if Password == "":
202       print "Randomizing and encrypting password"
203       Password = GenPass();
204       Pass = HashPass(Password);
205
206       # Use GPG to encrypt it, pass the fingerprint to ID it
207       CryptedPass = GPGEncrypt("Your new password is '" + Password + "'\n",\
208                                "0x"+Keys[0][1],UsePGP2);
209       Password = None;
210       if CryptedPass == None:
211         raise "Error","Password Encryption failed"
212    else:
213       Pass = HashPass(Password);
214       CryptedPass = "Your password has been set to the previously agreed value.";
215 else:
216    CryptedPass = "";
217    Pass = None;
218
219 # Now we have all the bits of information.
220 if mn != "":
221    FullName = "%s %s %s" % (cn,mn,sn);
222 else:
223    FullName = "%s %s" % (cn,sn);
224 print "------------";
225 print "Final information collected:"
226 print " %s <%s@%s>:" % (FullName,account,EmailAppend);
227 print "   Assigned UID:",uidNumber," GID:", gidNumber;
228 print "   Email forwarded to:",emailaddr
229 print "   Private Subscription:",privsub;
230 print "   GECOS Field: \"%s,,,,\"" % (FullName);
231 print "   Login Shell: /bin/bash";
232 print "   Key Fingerprint:",Keys[0][1];
233 Res = raw_input("Continue [No/yes]? ");
234 if Res != "yes":
235    sys.exit(1);
236
237 # Initialize the substitution Map
238 Subst = {}
239
240 encto = ''
241 try:
242   encto = FullName.decode('us-ascii')
243 except UnicodeError:
244   encto = str(email.Header.Header(FullName, 'utf-8', 200)) + " " + emailaddr
245
246 subjstring = "New Debian Maintainer " + FullName
247 encsubj = ''
248 try:
249   encsubj = subjstring.decode('us-ascii')
250 except UnicodeError:
251   encsubj = str(email.Header.Header(subjstring, 'utf-8', 200))
252
253 Subst["__HEADER_SUBJ__"] = encsubj
254 Subst["__HEADER_EMAIL"] = encto
255 Subst["__REALNAME__"] = FullName;
256 Subst["__WHOAMI__"] = pwd.getpwuid(os.getuid())[0];
257 Subst["__DATE__"] = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()));
258 Subst["__LOGIN__"] = account;
259 Subst["__PRIVATE__"] = privsub;
260 Subst["__EMAIL__"] = emailaddr
261 Subst["__PASSWORD__"] = CryptedPass;
262
263 # Submit the modification request
264 Dn = "uid=" + account + "," + BaseDn;
265 print "Updating LDAP directory..",
266 sys.stdout.flush();
267
268 if Update == 0:
269    # New account
270    Details = [("uid",account),
271               ("objectClass", UserObjectClasses),
272               ("uidNumber",str(uidNumber)),
273               ("gidNumber",str(gidNumber)),
274               ("gecos",FullName+",,,,"),
275               ("loginShell","/bin/bash"),
276               ("keyFingerPrint",Keys[0][1]),
277               ("cn",cn),
278               ("sn",sn),
279               ("emailForward",emailaddr),
280               ("shadowLastChange",str(int(time.time()/24/60/60))),
281               ("shadowMin","0"),
282               ("shadowMax","99999"),
283               ("shadowWarning","7"),
284               ("userPassword","{crypt}"+Pass)];
285    if mn:
286       Details.append(("mn",mn));
287    if privsub != " ":
288       Details.append(("privateSub",privsub))
289
290    #Add user group if needed, then the actual user:
291    if UserGroup == 1:
292       Dn = "gid=" + account + "," + BaseDn;
293       l.add_s(Dn,[("gid",account), ("gidNumber",str(gidNumber)), ("objectClass", GroupObjectClasses)])
294
295    l.add_s(Dn,Details);
296 else:
297    # Modification
298    Rec = [(ldap.MOD_REPLACE,"uidNumber",str(uidNumber)),
299           (ldap.MOD_REPLACE,"gidNumber",str(gidNumber)),
300           (ldap.MOD_REPLACE,"gecos",FullName+",,,,"),
301           (ldap.MOD_REPLACE,"loginShell","/bin/bash"),
302           (ldap.MOD_REPLACE,"keyFingerPrint",Keys[0][1]),
303           (ldap.MOD_REPLACE,"cn",cn),
304           (ldap.MOD_REPLACE,"mn",mn),
305           (ldap.MOD_REPLACE,"sn",sn),
306           (ldap.MOD_REPLACE,"emailForward",emailaddr),
307           (ldap.MOD_REPLACE,"shadowLastChange",str(int(time.time()/24/60/60))),
308           (ldap.MOD_REPLACE,"shadowMin","0"),
309           (ldap.MOD_REPLACE,"shadowMax","99999"),
310           (ldap.MOD_REPLACE,"shadowWarning","7"),
311           (ldap.MOD_REPLACE,"shadowInactive",""),
312           (ldap.MOD_REPLACE,"shadowExpire","")];
313    if privsub != " ":
314       Rec.append((ldap.MOD_REPLACE,"privateSub",privsub));
315    if Pass != None:
316       Rec.append((ldap.MOD_REPLACE,"userPassword","{crypt}"+Pass));
317    # Do it
318    l.modify_s(Dn,Rec);
319
320 print;
321
322 # Abort email sends for an update operation
323 if Update == 1 and ForceMail == 0:
324    print "Account is not new, Not sending mails"
325    sys.exit(0);
326
327 # Send the Welcome message
328 print "Sending Welcome Email"
329 Reply = TemplateSubst(Subst,open(TemplatesDir + "/welcome-message-%d" % gidNumber, "r").read())
330 Child = os.popen("/usr/sbin/sendmail -t","w");
331 #Child = os.popen("cat","w");
332 Child.write(Reply);
333 if Child.close() != None:
334    raise Error, "Sendmail gave a non-zero return code";