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