Use RFC 2047 header encoding when name contains non ascii characters.
[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
24 import email.base64mime
25 import email.quoprimime
26
27 from userdir_ldap import *;
28 from userdir_gpg import *;
29
30 # This tries to search for a free UID. There are two possible ways to do
31 # this, one is to fetch all the entires and pick the highest, the other
32 # is to randomly guess uids until one is free. This uses the former.
33 # Regrettably ldap doesn't have an integer attribute comparision function
34 # so we can only cut the search down slightly
35
36 # [JT] This is broken with Woody LDAP and the Schema; for now just
37 #      search through all UIDs.
38 def GetFreeID(l):
39    Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,
40                       "uidNumber=*",["uidNumber", "gidNumber"]);
41    HighestUID = 0;
42    gids = [];
43    for I in Attrs:
44       ID = int(GetAttr(I,"uidNumber","0"));
45       gids.append(int(GetAttr(I, "gidNumber","0")))
46       if ID > HighestUID:
47          HighestUID = ID;
48
49    resGID = HighestUID + 1;
50    while resGID in gids:
51       resGID += 1
52
53    return (HighestUID + 1, resGID);
54
55 # Main starts here
56 AdminUser = pwd.getpwuid(os.getuid())[0];
57
58 # Process options
59 ForceMail = 0;
60 NoAutomaticIDs = 0;
61 OldGPGKeyRings = GPGKeyRings;
62 userdir_gpg.GPGKeyRings = [];
63 (options, arguments) = getopt.getopt(sys.argv[1:], "u:man")
64 for (switch, val) in options:
65    if (switch == '-u'):
66       AdminUser = val;
67    elif (switch == '-m'):
68       ForceMail = 1;
69    elif (switch == '-a'):
70       userdir_gpg.GPGKeyRings = OldGPGKeyRings;
71    elif (switch == '-n'):
72       NoAutomaticIDs = 1;
73
74 l = passwdAccessLDAP(BaseDn, AdminUser)
75
76 # Locate the key of the user we are adding
77 SetKeyrings(ConfModule.add_keyrings.split(":"))
78 while (1):
79    Foo = raw_input("Who are you going to add (for a GPG search)? ");
80    if Foo == "":
81       sys.exit(0);
82
83    Keys = GPGKeySearch(Foo);
84
85    if len(Keys) == 0:
86       print "Sorry, that search did not turn up any keys."
87       print "Has it been added to the Debian keyring already?"
88       continue;
89    if len(Keys) > 1:
90       print "Sorry, more than one key was found, please specify the key to use by\nfingerprint:";
91       for i in Keys:
92          GPGPrintKeyInfo(i);
93       continue;
94
95    print
96    print "A matching key was found:"
97    GPGPrintKeyInfo(Keys[0]);
98    break;
99
100 # Crack up the email address from the key into a best guess
101 # first/middle/last name
102 Addr = SplitEmail(Keys[0][2]);
103 (cn,mn,sn) = NameSplit(re.sub('["]','',Addr[0]))
104 emailaddr = Addr[1] + '@' + Addr[2];
105 account = Addr[1];
106
107 privsub = emailaddr
108 gidNumber = 0;
109 uidNumber = 0;
110
111 # Decide if we should use IDEA encryption
112 UsePGP2 = 0;
113 while len(Keys[0][1]) < 40:
114    Res = raw_input("Use PGP2.x compatibility [No/yes]? ");
115    if Res == "yes":
116       UsePGP2 = 1;
117       break;
118    if Res == "":
119       break;
120
121 Update = 0
122 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"keyFingerPrint=" + Keys[0][1]);
123 if len(Attrs) != 0:
124    print "*** This key already belongs to",GetAttr(Attrs[0],"uid");
125    account = GetAttr(Attrs[0],"uid");
126    Update = 1
127
128 # Try to get a uniq account name
129 while 1:
130    if Update == 0:
131       Res = raw_input("Login account [" + account + "]? ");
132       if Res != "":
133          account = Res;
134    Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid=" + account);
135    if len(Attrs) == 0:
136       privsub = "%s@debian.org"%(account);
137       break;
138    Res = raw_input("That account already exists, update [No/yes]? ");
139    if Res == "yes":
140       # Update mode, fetch the default values from the directory
141       Update = 1;
142       privsub = GetAttr(Attrs[0],"privateSub");
143       gidNumber = GetAttr(Attrs[0],"gidNumber");
144       uidNumber = GetAttr(Attrs[0],"uidNumber");
145       emailaddr = GetAttr(Attrs[0],"emailForward");
146       cn = GetAttr(Attrs[0],"cn");
147       sn = GetAttr(Attrs[0],"sn");
148       mn = GetAttr(Attrs[0],"mn");
149       if privsub == None or privsub == "":
150          privsub = " ";
151       break;
152    else:
153       sys.exit(1)
154
155 # Prompt for the first/last name and email address
156 Res = raw_input("First name [" + cn + "]? ");
157 if Res != "":
158    cn = Res;
159 Res = raw_input("Middle name [" + mn + "]? ");
160 if 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 emailstring = FullName + " " + emailaddr
241 encto = ''
242 try:
243   encto = emailstring.encode('us-ascii')
244 except UnicodeDecodeError:
245   if email.base64mime.base64_len(emailstring) < email.quoprimime.header_quopri_len(emailstring):
246     encto = email.base64mime.header_encode(emailstring, 'us-ascii')
247   else:
248     encto = email.quoprimime.header_encode(emailstring, 'us-ascii')
249
250 subjstring = "New Debian Maintainer " + FullName
251 encsubj = ''
252 try:
253   encsubj = subjstring.encode('us-ascii')
254 except UnicodeDecodeError:
255   if email.base64mime.base64_len(subjstring) < email.quoprimime.header_quopri_len(subjstring):
256     encsubj = email.base64mime.header_encode(subjstring, 'us-ascii')
257   else:
258     encsubj = email.quoprimime.header_encode(subjstring, 'us-ascii')
259
260 Subst["__HEADER_SUBJ__"] = encsubj
261 Subst["__HEADER_EMAIL"] = encto
262 Subst["__REALNAME__"] = FullName;
263 Subst["__WHOAMI__"] = pwd.getpwuid(os.getuid())[0];
264 Subst["__DATE__"] = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()));
265 Subst["__LOGIN__"] = account;
266 Subst["__PRIVATE__"] = privsub;
267 Subst["__EMAIL__"] = emailaddr
268 Subst["__PASSWORD__"] = CryptedPass;
269
270 # Submit the modification request
271 Dn = "uid=" + account + "," + BaseDn;
272 print "Updating LDAP directory..",
273 sys.stdout.flush();
274
275 if Update == 0:
276    # New account
277    Details = [("uid",account),
278               ("objectClass", UserObjectClasses),
279               ("uidNumber",str(uidNumber)),
280               ("gidNumber",str(gidNumber)),
281               ("gecos",FullName+",,,,"),
282               ("loginShell","/bin/bash"),
283               ("keyFingerPrint",Keys[0][1]),
284               ("cn",cn),
285               ("sn",sn),
286               ("emailForward",emailaddr),
287               ("shadowLastChange",str(int(time.time()/24/60/60))),
288               ("shadowMin","0"),
289               ("shadowMax","99999"),
290               ("shadowWarning","7"),
291               ("userPassword","{crypt}"+Pass)];
292    if mn:
293       Details.append(("mn",mn));
294    if privsub != " ":
295       Details.append(("privateSub",privsub))
296
297    #Add user group if needed, then the actual user:
298    if UserGroup == 1:
299       Dn = "gid=" + account + "," + BaseDn;
300       l.add_s(Dn,[("gid",account), ("gidNumber",str(gidNumber)), ("objectClass", GroupObjectClasses)])
301
302    l.add_s(Dn,Details);
303 else:
304    # Modification
305    Rec = [(ldap.MOD_REPLACE,"uidNumber",str(uidNumber)),
306           (ldap.MOD_REPLACE,"gidNumber",str(gidNumber)),
307           (ldap.MOD_REPLACE,"gecos",FullName+",,,,"),
308           (ldap.MOD_REPLACE,"loginShell","/bin/bash"),
309           (ldap.MOD_REPLACE,"keyFingerPrint",Keys[0][1]),
310           (ldap.MOD_REPLACE,"cn",cn),
311           (ldap.MOD_REPLACE,"mn",mn),
312           (ldap.MOD_REPLACE,"sn",sn),
313           (ldap.MOD_REPLACE,"emailForward",emailaddr),
314           (ldap.MOD_REPLACE,"shadowLastChange",str(int(time.time()/24/60/60))),
315           (ldap.MOD_REPLACE,"shadowMin","0"),
316           (ldap.MOD_REPLACE,"shadowMax","99999"),
317           (ldap.MOD_REPLACE,"shadowWarning","7"),
318           (ldap.MOD_REPLACE,"shadowInactive",""),
319           (ldap.MOD_REPLACE,"shadowExpire","")];
320    if privsub != " ":
321       Rec.append((ldap.MOD_REPLACE,"privateSub",privsub));
322    if Pass != None:
323       Rec.append((ldap.MOD_REPLACE,"userPassword","{crypt}"+Pass));
324    # Do it
325    l.modify_s(Dn,Rec);
326
327 print;
328
329 # Abort email sends for an update operation
330 if Update == 1 and ForceMail == 0:
331    print "Account is not new, Not sending mails"
332    sys.exit(0);
333
334 # Send the Welcome message
335 print "Sending Welcome Email"
336 Reply = TemplateSubst(Subst,open(TemplatesDir + "/welcome-message-%d" % gidNumber, "r").read())
337 Child = os.popen("/usr/sbin/sendmail -t","w");
338 #Child = os.popen("cat","w");
339 Child.write(Reply);
340 if Child.close() != None:
341    raise Error, "Sendmail gave a non-zero return code";