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