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 # Try to get a uniq account name
95 Res = raw_input("Login account [" + account + "]? ");
98 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid=" + account);
100 privsub = "%s@debian.org"%(account);
102 Res = raw_input("That account already exists, update [no]? ");
104 # Update mode, fetch the default values from the directory
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 == "":
117 # Prompt for the first/last name and email address
118 Res = raw_input("First name [" + cn + "]? ");
121 Res = raw_input("Middle name [" + mn + "]? ");
124 Res = raw_input("Last name [" + sn + "]? ");
127 Res = raw_input("Email forwarding address [" + email + "]? ");
131 # Debian-Private subscription
132 Res = raw_input("Subscribe to debian-private (space is none) [" + privsub + "]? ");
137 Res = raw_input("Group ID Number [" + gidnumber + "]? ");
143 uidnumber = GetFreeID(l);
145 # Generate a random password
146 if Update == 0 or ForceMail == 1:
147 Password = raw_input("User's Password (Enter for random)? ");
150 print "Randomizing and encrypting password"
151 Password = GenPass();
152 Pass = HashPass(Password);
154 # Use GPG to encrypt it, pass the fingerprint to ID it
155 CryptedPass = GPGEncrypt("Your new password is '" + Password + "'\n",\
156 "0x"+Keys[0][1],UsePGP2);
158 if CryptedPass == None:
159 raise "Error","Password Encryption failed"
161 Pass = HashPass(Password);
162 CryptedPass = "Your password has been set to the previously agreed value.";
167 # Now we have all the bits of information.
169 FullName = "%s %s %s" % (cn,mn,sn);
171 FullName = "%s %s" % (cn,sn);
172 print "------------";
173 print "Final information collected:"
174 print " %s <%s@%s>:" % (FullName,account,EmailAppend);
175 print " Assigned UID:",uidnumber," GID:", gidnumber;
176 print " Email forwarded to:",email;
177 print " Private Subscription:",privsub;
178 print " GECOS Field: \"%s,,,,\"" % (FullName);
179 print " Login Shell: /bin/bash";
180 print " Key Fingerprint:",Keys[0][1];
181 Res = raw_input("Continue [no]? ");
185 # Initialize the substitution Map
187 Subst["__REALNAME__"] = FullName;
188 Subst["__WHOAMI__"] = pwd.getpwuid(os.getuid())[0];
189 Subst["__DATE__"] = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()));
190 Subst["__LOGIN__"] = account;
191 Subst["__PRIVATE__"] = privsub;
192 Subst["__EMAIL__"] = email;
193 Subst["__PASSWORD__"] = CryptedPass;
194 #Subst["__LISTPASS__"] = string.strip(open(pwd.getpwuid(os.getuid())[5]+"/.debian-lists_passwd","r").read());
196 # Generate the LDAP request
197 Rec = [(ldap.MOD_REPLACE,"uid",account),
198 (ldap.MOD_REPLACE,"uidNumber",str(uidnumber)),
199 (ldap.MOD_REPLACE,"gidNumber",str(gidnumber)),
200 (ldap.MOD_REPLACE,"gecos",FullName+",,,,"),
201 (ldap.MOD_REPLACE,"loginShell","/bin/bash"),
202 (ldap.MOD_REPLACE,"keyfingerprint",Keys[0][1]),
203 (ldap.MOD_REPLACE,"cn",cn),
204 (ldap.MOD_REPLACE,"mn",mn),
205 (ldap.MOD_REPLACE,"sn",sn),
206 (ldap.MOD_REPLACE,"emailforward",email),
207 (ldap.MOD_REPLACE,"shadowLastChange",str(int(time.time()/24/60/60))),
208 (ldap.MOD_REPLACE,"shadowMin","0"),
209 (ldap.MOD_REPLACE,"shadowMax","99999"),
210 (ldap.MOD_REPLACE,"shadowWarning","7"),
211 (ldap.MOD_REPLACE,"shadowInactive",""),
212 (ldap.MOD_REPLACE,"shadowExpire","")];
214 Rec.append((ldap.MOD_REPLACE,"privatesub",privsub));
216 Rec.append((ldap.MOD_REPLACE,"userPassword","{crypt}"+Pass));
218 # Submit the modification request
219 Dn = "uid=" + account + "," + BaseDn;
220 print "Updating LDAP directory..",
223 l.add_s(Dn,[("uid",account),
224 ("objectclass","top"),
225 ("objectclass","account"),
226 ("objectclass","posixAccount"),
227 ("objectclass","shadowAccount"),
228 ("objectclass","debiandeveloper")]);
229 except ldap.ALREADY_EXISTS:
232 # Send the modify request
236 # Abort email sends for an update operation
237 if Update == 1 and ForceMail == 0:
238 print "Account is not new, Not sending mails"
241 # Do the subscription/welcome message
243 # Sub = TemplateSubst(Subst,open(TemplatesDir+"/list-subscribe","r").read());
244 # Child = os.popen("/usr/sbin/sendmail -t","w");
246 # if Child.close() != None:
247 # raise Error, "Sendmail gave a non-zero return code";
249 # Send the Welcome message
250 print "Sending Welcome Email"
251 Reply = TemplateSubst(Subst,open(TemplatesDir+"/welcome-message-"+gidnumber,"r").read());
252 Child = os.popen("/usr/sbin/sendmail -t","w");
253 #Child = os.popen("cat","w");
255 if Child.close() != None:
256 raise Error, "Sendmail gave a non-zero return code";