New Mail template and more fixes for james
[mirror/userdir-ldap.git] / ud-useradd
1 #!/usr/bin/env python
2 # -*- mode: python -*-
3
4 import string, re, time, ldap, getopt, sys, os, pwd;
5 from userdir_ldap import *;
6 from userdir_gpg import *;
7
8 # This tries to search for a free UID. There are two possible ways to do
9 # this, one is to fetch all the entires and pick the highest, the other
10 # is to randomly guess uids until one is free. This uses the former.
11 # Regrettably ldap doesn't have an integer attribute comparision function
12 # so we can only cut the search down slightly 
13 def GetFreeID(l):
14    HighestUID = 1400;
15    Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,  
16                       "uidnumber>="+str(HighestUID),["uidnumber"]);
17    HighestUID = 0;
18    for I in Attrs:
19       ID = int(GetAttr(I,"uidnumber","0"));
20       if ID > HighestUID: 
21          HighestUID = ID;
22    return HighestUID + 1;
23
24 # Main starts here
25 AdminUser = pwd.getpwuid(os.getuid())[0];
26
27 # Process options
28 ForceMail = 0;
29 OldGPGKeyRings = GPGKeyRings;
30 userdir_gpg.GPGKeyRings = [];
31 (options, arguments) = getopt.getopt(sys.argv[1:], "u:ma")
32 for (switch, val) in options:
33    if (switch == '-u'):
34       AdminUser = val;
35    elif (switch == '-m'):
36       ForceMail = 1;
37    elif (switch == '-a'):
38       userdir_gpg.GPGKeyRings = OldGPGKeyRings;
39
40 print "Accessing LDAP directory as '" + AdminUser + "'";
41 Password = getpass(AdminUser + "'s password: ");
42
43 # Connect to the ldap server
44 l = ldap.open(LDAPServer);
45 UserDn = "uid=" + AdminUser + "," + BaseDn;
46 l.simple_bind_s(UserDn,Password);
47
48 # Locate the key of the user we are adding
49 GPGBasicOptions[0] = "--batch"           # Permit loading of the config file
50 while (1):
51    Foo = raw_input("Who are you going to add (for a GPG search)? ");
52    if Foo == "":
53       continue;
54
55    Keys = GPGKeySearch(Foo);
56
57    if len(Keys) == 0:
58       print "Sorry, that search did not turn up any keys";
59       continue;
60    if len(Keys) > 1:
61       print "Sorry, more than one key was found, please specify the key to use by\nfingerprint:";
62       for i in Keys:
63          GPGPrintKeyInfo(i);
64       continue;
65
66    print
67    print "A matching key was found:"
68    GPGPrintKeyInfo(Keys[0]);
69    break;
70    
71 # Crack up the email address from the key into a best guess 
72 # first/middle/last name
73 Addr = SplitEmail(Keys[0][2]);
74 (cn,mn,sn) = NameSplit(re.sub('["]','',Addr[0]))
75 email = Addr[1] + '@' + Addr[2];
76 account = Addr[1];
77
78 privsub = email;
79 gidnumber = str(DefaultGID);
80 uidnumber = 0;
81
82 # Decide if we should use IDEA encryption
83 UsePGP2 = 0;
84 while len(Keys[0][1]) < 40:
85    Res = raw_input("Use PGP2.x compatibility [no]? ");
86    if Res == "yes":
87       UsePGP2 = 1;
88       break;
89    if Res == "":
90       break;
91
92 # Try to get a uniq account name
93 Update=0
94 while 1:
95    Res = raw_input("Login account [" + account + "]? ");
96    if Res != "":
97       account = Res;
98    Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid=" + account);
99    if len(Attrs) == 0:
100       privsub = "%s@debian.org"%(account);
101       break;
102    Res = raw_input("That account already exists, update [no]? ");
103    if Res == "yes":
104       # Update mode, fetch the default values from the directory
105       Update = 1;
106       privsub = GetAttr(Attrs[0],"privatesub");
107       gidnumber = GetAttr(Attrs[0],"gidnumber");
108       uidnumber = GetAttr(Attrs[0],"uidnumber");
109       email = GetAttr(Attrs[0],"emailforward");
110       cn = GetAttr(Attrs[0],"cn");
111       sn = GetAttr(Attrs[0],"sn");
112       mn = GetAttr(Attrs[0],"mn");
113       if privsub == None or privsub == "":
114          privsub = " ";
115       break;
116
117 # Prompt for the first/last name and email address
118 Res = raw_input("First name [" + cn + "]? ");
119 if Res != "":
120    cn = Res;
121 Res = raw_input("Middle name [" + mn + "]? ");
122 if Res != "":
123    mn = Res;
124 Res = raw_input("Last name [" + sn + "]? ");
125 if Res != "":
126    sn = Res;
127 Res = raw_input("Email forwarding address [" + email + "]? ");
128 if Res != "":
129    email = Res;
130
131 # Debian-Private subscription
132 Res = raw_input("Subscribe to debian-private (space is none) [" + privsub + "]? ");
133 if Res != "":
134    privsub = Res;
135
136 # GID
137 Res = raw_input("Group ID Number [" + gidnumber + "]? ");
138 if Res != "":
139    gidnumber = Res;
140
141 # UID
142 if uidnumber == 0:
143    uidnumber = GetFreeID(l);
144
145 # Generate a random password
146 if Update == 0 or ForceMail == 1:
147    Password = raw_input("User's Password (Enter for random)? ");
148
149    if Password == "":
150       print "Randomizing and encrypting password"
151       Password = GenPass();
152       Pass = HashPass(Password);
153       print "PASS: ", Password;
154
155       # Use GPG to encrypt it, pass the fingerprint to ID it
156       CryptedPass = GPGEncrypt("Your new password is '" + Password + "'\n",\
157                                "0x"+Keys[0][1],UsePGP2);
158       Password = None;
159       if CryptedPass == None:
160         raise "Error","Password Encryption failed"
161    else:
162       Pass = HashPass(Password);
163       CryptedPass = "Your password has been set to the previously agreed value.";
164 else:
165    CryptedPass = "";
166    Pass = None;
167
168 # Now we have all the bits of information.
169 if mn != "": 
170    FullName = "%s %s %s" % (cn,mn,sn);
171 else:
172    FullName = "%s %s" % (cn,sn);
173 print "------------";
174 print "Final information collected:"
175 print " %s <%s@%s>:" % (FullName,account,EmailAppend);
176 print "   Assigned UID:",uidnumber," GID:", gidnumber;
177 print "   Email forwarded to:",email;
178 print "   Private Subscription:",privsub;
179 print "   GECOS Field: \"%s,,,,\"" % (FullName);
180 print "   Login Shell: /bin/bash";
181 print "   Key Fingerprint:",Keys[0][1];
182 Res = raw_input("Continue [no]? ");
183 if Res != "yes":
184    sys.exit(1);
185
186 # Initialize the substitution Map
187 Subst = {}
188 Subst["__REALNAME__"] = FullName;
189 Subst["__WHOAMI__"] = pwd.getpwuid(os.getuid())[0];
190 Subst["__DATE__"] = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()));
191 Subst["__LOGIN__"] = account;
192 Subst["__PRIVATE__"] = privsub;
193 Subst["__EMAIL__"] = email;
194 Subst["__PASSWORD__"] = CryptedPass;
195 Subst["__LISTPASS__"] = string.strip(open(pwd.getpwuid(os.getuid())[5]+"/.debian-lists_passwd","r").read());
196
197 # Generate the LDAP request
198 Rec = [(ldap.MOD_REPLACE,"uid",account),
199        (ldap.MOD_REPLACE,"uidNumber",str(uidnumber)),
200        (ldap.MOD_REPLACE,"gidNumber",str(gidnumber)),
201        (ldap.MOD_REPLACE,"gecos",FullName+",,,,"),
202        (ldap.MOD_REPLACE,"loginShell","/bin/bash"),
203        (ldap.MOD_REPLACE,"keyfingerprint",Keys[0][1]),
204        (ldap.MOD_REPLACE,"cn",cn),
205        (ldap.MOD_REPLACE,"mn",mn),
206        (ldap.MOD_REPLACE,"sn",sn),
207        (ldap.MOD_REPLACE,"emailforward",email),
208        (ldap.MOD_REPLACE,"shadowLastChange",str(int(time.time()/24/60/60))),
209        (ldap.MOD_REPLACE,"shadowMin","0"),
210        (ldap.MOD_REPLACE,"shadowMax","99999"),
211        (ldap.MOD_REPLACE,"shadowWarning","7"),
212        (ldap.MOD_REPLACE,"shadowInactive",""),
213        (ldap.MOD_REPLACE,"shadowExpire","")];
214 if privsub != " ":
215    Rec.append((ldap.MOD_REPLACE,"privatesub",privsub));
216 if Pass != None:
217    Rec.append((ldap.MOD_REPLACE,"userPassword","{crypt}"+Pass));
218
219 # Submit the modification request   
220 Dn = "uid=" + account + "," + BaseDn;
221 print "Updating LDAP directory..",
222 sys.stdout.flush();
223 try:
224    l.add_s(Dn,[("uid",account),
225                ("objectclass","top"),
226                ("objectclass","account"),
227                ("objectclass","posixAccount"),
228                ("objectclass","shadowAccount"),
229                ("objectclass","debiandeveloper")]);
230 except ldap.ALREADY_EXISTS:
231    pass;
232
233 # Send the modify request
234 l.modify_s(Dn,Rec);
235 print;
236
237 # Abort email sends for an update operation
238 if Update == 1 and ForceMail == 0:
239    print "Account is not new, Not sending mails"
240    sys.exit(0);
241    
242 # Do the subscription/welcome message
243 #if privsub != " ":
244 #   Sub = TemplateSubst(Subst,open(TemplatesDir+"/list-subscribe","r").read());
245 #   Child = os.popen("/usr/sbin/sendmail -t","w");
246 #   Child.write(Sub);
247 #   if Child.close() != None:
248 #       raise Error, "Sendmail gave a non-zero return code";
249    
250 # Send the Welcome message
251 print "Sending Welcome Email"
252 Reply = TemplateSubst(Subst,open(TemplatesDir+"/welcome-message-"+gidnumber,"r").read());
253 Child = os.popen("/usr/sbin/sendmail -t","w");
254 #Child = os.popen("cat","w");
255 Child.write(Reply);
256 if Child.close() != None:
257    raise Error, "Sendmail gave a non-zero return code";