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