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