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