4 import string, re, time, ldap, getopt, sys, os, pwd;
5 from userdir_ldap import *;
6 from userdir_gpg import *;
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
15 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,
16 "uidnumber>="+str(HighestUID),["uidnumber"]);
19 ID = int(GetAttr(I,"uidnumber","0"));
22 return HighestUID + 1;
25 AdminUser = pwd.getpwuid(os.getuid())[0];
29 OldGPGKeyRings = GPGKeyRings;
30 userdir_gpg.GPGKeyRings = [];
31 (options, arguments) = getopt.getopt(sys.argv[1:], "u:ma")
32 for (switch, val) in options:
35 elif (switch == '-m'):
37 elif (switch == '-a'):
38 userdir_gpg.GPGKeyRings = OldGPGKeyRings;
40 print "Accessing LDAP directory as '" + AdminUser + "'";
41 Password = getpass(AdminUser + "'s password: ");
43 # Connect to the ldap server
44 l = ldap.open(LDAPServer);
45 UserDn = "uid=" + AdminUser + "," + BaseDn;
46 l.simple_bind_s(UserDn,Password);
48 # Locate the key of the user we are adding
49 GPGBasicOptions[0] = "--batch" # Permit loading of the config file
51 Foo = raw_input("Who are you going to add (for a GPG search)? ");
55 Keys = GPGKeySearch(Foo);
58 print "Sorry, that search did not turn up any keys";
61 print "Sorry, more than one key was found, please specify the key to use by\nfingerprint:";
67 print "A matching key was found:"
68 GPGPrintKeyInfo(Keys[0]);
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];
79 gidnumber = str(DefaultGID);
82 # Decide if we should use IDEA encryption
84 while len(Keys[0][1]) < 40:
85 Res = raw_input("Use PGP2.x compatibility [no]? ");
92 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"keyfingerprint=" + Keys[0][1]);
94 print "*** This key already belongs to",GetAttr(Attrs[0],"uid");
95 account = GetAttr(Attrs[0],"uid");
97 # Try to get a uniq account name
100 Res = raw_input("Login account [" + account + "]? ");
103 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid=" + account);
105 privsub = "%s@debian.org"%(account);
107 Res = raw_input("That account already exists, update [no]? ");
109 # Update mode, fetch the default values from the directory
111 privsub = GetAttr(Attrs[0],"privatesub");
112 gidnumber = GetAttr(Attrs[0],"gidnumber");
113 uidnumber = GetAttr(Attrs[0],"uidnumber");
114 email = GetAttr(Attrs[0],"emailforward");
115 cn = GetAttr(Attrs[0],"cn");
116 sn = GetAttr(Attrs[0],"sn");
117 mn = GetAttr(Attrs[0],"mn");
118 if privsub == None or privsub == "":
122 # Prompt for the first/last name and email address
123 Res = raw_input("First name [" + cn + "]? ");
126 Res = raw_input("Middle name [" + mn + "]? ");
129 Res = raw_input("Last name [" + sn + "]? ");
132 Res = raw_input("Email forwarding address [" + email + "]? ");
136 # Debian-Private subscription
137 Res = raw_input("Subscribe to debian-private (space is none) [" + privsub + "]? ");
142 Res = raw_input("Group ID Number [" + gidnumber + "]? ");
148 uidnumber = GetFreeID(l);
150 # Generate a random password
151 if Update == 0 or ForceMail == 1:
152 Password = raw_input("User's Password (Enter for random)? ");
155 print "Randomizing and encrypting password"
156 Password = GenPass();
157 Pass = HashPass(Password);
159 # Use GPG to encrypt it, pass the fingerprint to ID it
160 CryptedPass = GPGEncrypt("Your new password is '" + Password + "'\n",\
161 "0x"+Keys[0][1],UsePGP2);
163 if CryptedPass == None:
164 raise "Error","Password Encryption failed"
166 Pass = HashPass(Password);
167 CryptedPass = "Your password has been set to the previously agreed value.";
172 # Now we have all the bits of information.
174 FullName = "%s %s %s" % (cn,mn,sn);
176 FullName = "%s %s" % (cn,sn);
177 print "------------";
178 print "Final information collected:"
179 print " %s <%s@%s>:" % (FullName,account,EmailAppend);
180 print " Assigned UID:",uidnumber," GID:", gidnumber;
181 print " Email forwarded to:",email;
182 print " Private Subscription:",privsub;
183 print " GECOS Field: \"%s,,,,\"" % (FullName);
184 print " Login Shell: /bin/bash";
185 print " Key Fingerprint:",Keys[0][1];
186 Res = raw_input("Continue [no]? ");
190 # Initialize the substitution Map
192 Subst["__REALNAME__"] = FullName;
193 Subst["__WHOAMI__"] = pwd.getpwuid(os.getuid())[0];
194 Subst["__DATE__"] = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()));
195 Subst["__LOGIN__"] = account;
196 Subst["__PRIVATE__"] = privsub;
197 Subst["__EMAIL__"] = email;
198 Subst["__PASSWORD__"] = CryptedPass;
199 #Subst["__LISTPASS__"] = string.strip(open(pwd.getpwuid(os.getuid())[5]+"/.debian-lists_passwd","r").read());
201 # Generate the LDAP request
202 Rec = [(ldap.MOD_REPLACE,"uid",account),
203 (ldap.MOD_REPLACE,"uidNumber",str(uidnumber)),
204 (ldap.MOD_REPLACE,"gidNumber",str(gidnumber)),
205 (ldap.MOD_REPLACE,"gecos",FullName+",,,,"),
206 (ldap.MOD_REPLACE,"loginShell","/bin/bash"),
207 (ldap.MOD_REPLACE,"keyfingerprint",Keys[0][1]),
208 (ldap.MOD_REPLACE,"cn",cn),
209 (ldap.MOD_REPLACE,"mn",mn),
210 (ldap.MOD_REPLACE,"sn",sn),
211 (ldap.MOD_REPLACE,"emailforward",email),
212 (ldap.MOD_REPLACE,"shadowLastChange",str(int(time.time()/24/60/60))),
213 (ldap.MOD_REPLACE,"shadowMin","0"),
214 (ldap.MOD_REPLACE,"shadowMax","99999"),
215 (ldap.MOD_REPLACE,"shadowWarning","7"),
216 (ldap.MOD_REPLACE,"shadowInactive",""),
217 (ldap.MOD_REPLACE,"shadowExpire","")];
219 Rec.append((ldap.MOD_REPLACE,"privatesub",privsub));
221 Rec.append((ldap.MOD_REPLACE,"userPassword","{crypt}"+Pass));
223 # Submit the modification request
224 Dn = "uid=" + account + "," + BaseDn;
225 print "Updating LDAP directory..",
228 l.add_s(Dn,[("uid",account),
229 ("objectclass","top"),
230 ("objectclass","account"),
231 ("objectclass","posixAccount"),
232 ("objectclass","shadowAccount"),
233 ("objectclass","debiandeveloper")]);
234 except ldap.ALREADY_EXISTS:
237 # Send the modify request
241 # Abort email sends for an update operation
242 if Update == 1 and ForceMail == 0:
243 print "Account is not new, Not sending mails"
246 # Do the subscription/welcome message
248 # Sub = TemplateSubst(Subst,open(TemplatesDir+"/list-subscribe","r").read());
249 # Child = os.popen("/usr/sbin/sendmail -t","w");
251 # if Child.close() != None:
252 # raise Error, "Sendmail gave a non-zero return code";
254 # Send the Welcome message
255 print "Sending Welcome Email"
256 Reply = TemplateSubst(Subst,open(TemplatesDir+"/welcome-message-"+gidnumber,"r").read());
257 Child = os.popen("/usr/sbin/sendmail -t","w");
258 #Child = os.popen("cat","w");
260 if Child.close() != None:
261 raise Error, "Sendmail gave a non-zero return code";