Add VoIP fiels to the LDAP shema and teach ud-info and ud-mailgate about it. [zobel]
[mirror/userdir-ldap.git] / ud-info
1 #!/usr/bin/env python
2 # -*- mode: python -*-
3 # This script is an interactive way to manipulate fields in the LDAP directory.
4 # When run it connects to the directory using the current users ID and fetches
5 # all the attributes for that user. It then formats them nicely and allows
6 # the user to change them.
7 # It is possible to authenticate as someone differnt than you are viewing/changing
8 # this allows administrative functions and also allows users to view 
9 # restricted information about others, such as phone numbers and addresses.
10 #
11 #  Usage: userinfo -a <user> -u <user> -c <user> -r
12 #    -a    Set the authentication user (the user whose password you are 
13 #          going to enter)
14 #    -u    Set the user to display
15 #    -c    Set both -a and -u, use this if your login uid is not in the 
16 #          database
17 #    -r    Enable 'root' functions, do this if your uid has access to
18 #          restricted variables.
19
20 import time, os, pwd, sys, getopt, ldap, crypt, readline, copy;
21 from userdir_ldap import *;
22
23 RootMode = 0;
24 AttrInfo = {"cn": ["First Name", 101],
25             "mn": ["Middle Name", 102],
26             "sn": ["Surname", 103],
27             "c": ["Country Code",1],
28             "l": ["Locality",2],
29             "ou": ["Membership",0],
30             "facsimileTelephoneNumber": ["Fax Phone Number",3],
31             "telephoneNumber": ["Phone Number",4],
32             "postalAddress": ["Mailing Address",5],
33             "postalCode": ["Postal Code",6],
34             "uid": ["Unix User ID",0],
35             "loginShell": ["Unix Shell",7],
36             "supplementaryGid": ["Unix Groups",0],
37             "allowedHost": ["Host ACL",0],
38             "member": ["LDAP Group",0],
39             "emailForward": ["Email Forwarding",8],
40             "ircNick": ["IRC Nickname",9],
41             "onVacation": ["Vacation Message",10],
42             "labeledURI": ["Home Page",11],
43             "latitude": ["Latitude",12],
44             "longitude": ["Longitude",13],
45             "icqUin": ["ICQ UIN",14],
46             "jabberJID": ["Jabber ID",15],
47             "privateSub": ["Debian-Private",16],
48             "gender": ["Gender",17],
49             "birthDate": ["Date of Birth",18],
50             "mailDisableMessage": ["Mail Disabled",19],
51             "mailGreylisting": ["Mail Greylisting",20],
52             "mailCallout": ["Mail Callouts",21],
53             "mailRBL": ["Mail RBLs",22],
54             "mailRHSBL": ["Mail RHSBLs",23],
55             "mailWhitelist": ["Mail Whitelist",24],
56             "comment": ["Comment",116],
57             "userPassword": ["Crypted Password",117],
58             "dnsZoneEntry": ["d.net Entry",118],
59             "VoIP": ["VoIP Address",119]}; 
60
61 AttrPrompt = {"cn": ["Common name or first name"],
62               "mn": ["Middle name (or initial if it ends in a dot)"],
63               "sn": ["Surname or last name"],
64               "c": ["ISO 2 letter country code, such as US, DE, etc"],
65               "l": ["City name, State/Provice (Locality)\n e.g. Dallas, Texas"],
66               "facsimileTelephoneNumber": ["Fax phone number, with area code and country code"],
67               "telephoneNumber": ["Voice phone number"],
68               "postalAddress": ["Complete mailing address including postal codes and country designations\nSeperate lines using a $ character"],
69               "postalCode": ["Postal Code or Zip Code"],
70               "loginShell": ["Login shell with full path (no check is done for validity)"],
71               "emailForward": ["EMail address to send all mail to or blank to disable"],
72               "ircNick": ["IRC nickname if you use IRC"],
73               "onVacation": ["A message if on vaction, indicating the time of departure and return"],
74               "userPassword": ["The users Crypt'd password"],
75               "comment": ["Admin Comment about the account"],
76               "supplementaryGid": ["Groups the user is in"],
77               "allowedHost": ["Grant access to certain hosts"],
78               "privateSub": ["Debian-Private mailing list subscription"],
79               "gender": ["ISO5218 Gender code (1=male,2=female,9=unspecified)"],
80               "birthDate": ["Date of Birth (YYYYMMDD)"],
81               "mailDisableMessage": ["Error message to return via SMTP"],
82               "mailGreylisting": ["SMTP Greylisting (TRUE/FALSE)"],
83               "mailCallout": ["SMTP Callouts (TRUE/FALSE)"],
84               "mailRBL": ["SMTP time RBL lists"],
85               "mailRHSBL": ["SMTP time RHSBL lists"],
86               "mailWhitelist": ["SMTP time whitelist from other checks"],
87               "member": ["LDAP Group Member for slapd ACLs"],
88               "latitude": ["XEarth latitude in ISO 6709 format - see /usr/share/zoneinfo/zone.tab or etak.com"],
89               "longitude": ["XEarth latitude in ISO 6709 format - see /usr/share/zoneinfo/zone.tab or etak.com"],
90               "dnsZoneEntry": ["DNS Zone fragment associated this this user"],
91               "labeledURI": ["Web home page"],
92               "jabberJID": ["Jabber ID"],
93               "icqUin": ["ICQ UIN Number"],
94               "VoIP": ["VoIP Address"]};
95
96 # Create a map of IDs to desc,value,attr
97 OrderedIndex = {};
98 for at in AttrInfo.keys():
99    if (AttrInfo[at][1] != 0):
100       OrderedIndex[AttrInfo[at][1]] = [AttrInfo[at][0], "", at];
101 OrigOrderedIndex = copy.deepcopy(OrderedIndex);
102
103 # Show shadow information
104 def PrintShadow(Attrs):
105    Changed = int(GetAttr(Attrs,"shadowLastChange","0"));
106    MinDays = int(GetAttr(Attrs,"shadowMin","0"));
107    MaxDays = int(GetAttr(Attrs,"shadowMax","0"));
108    WarnDays = int(GetAttr(Attrs,"shadowWarning","0"));
109    InactDays = int(GetAttr(Attrs,"shadowinactive","0"));
110    Expire = int(GetAttr(Attrs,"shadowexpire","0"));
111
112    print "%-24s:" % ("Password last changed"),
113    print time.strftime("%a %d/%m/%Y %Z",time.localtime(Changed*24*60*60));
114    if (Expire > 0):
115       print "%-24s:" % ("Account expires on"),
116       print time.strftime("%a %d/%m/%Y %Z",time.localtime(Expire*24*60*60));
117    if (InactDays >= 0 and MaxDays < 99999):
118       print "Account aging is active, you must change your password every", MaxDays, "days."
119
120 # Print out the automatic time stamp information
121 def PrintModTime(Attrs):
122    Stamp = GetAttr(Attrs,"modifyTimestamp","");
123    if len(Stamp) >= 13:
124       Time = (int(Stamp[0:4]),int(Stamp[4:6]),int(Stamp[6:8]),
125               int(Stamp[8:10]),int(Stamp[10:12]),int(Stamp[12:14]),0,0,-1);
126       print "%-24s:" % ("Record last modified on"), time.strftime("%a %d/%m/%Y %X UTC",Time),
127       print "by",ldap.explode_dn(GetAttr(Attrs,"modifiersName"),1)[0];
128
129    Stamp = GetAttr(Attrs,"createTimestamp","");
130    if len(Stamp) >= 13:
131       Time = (int(Stamp[0:4]),int(Stamp[4:6]),int(Stamp[6:8]),
132               int(Stamp[8:10]),int(Stamp[10:12]),int(Stamp[12:14]),0,0,-1);
133       print "%-24s:" % ("Record created on"), time.strftime("%a %d/%m/%Y %X UTC",Time);
134
135 # Print the PGP key for a user
136 def PrintKeys(Attrs):
137    if Attrs[1].has_key("keyFingerPrint") == 0:
138       return;
139    First = 0;
140    for x in Attrs[1]["keyFingerPrint"]:
141       if First == 0:
142          print "%-24s:" % ("PGP/GPG Key Fingerprints"),
143          First = 1;
144       else:
145          print "%-24s:" % (""),
146       print FormatPGPKey(x);
147
148 # Print the SSH RSA Authentication keys for a user
149 def PrintSshRSAKeys(Attrs):
150    if Attrs[1].has_key("sshRSAAuthKey") == 0:
151       return;
152    First = 0;
153    for x in Attrs[1]["sshRSAAuthKey"]:
154       if First == 0:
155          print "%-24s:" % ("SSH Auth Keys"),
156          First = 1;
157       else:
158          print "%-24s:" % (""),
159
160       print FormatSSHAuth(x);
161       
162 # Display all of the attributes in a numbered list
163 def ShowAttrs(Attrs):
164    print;
165    print EmailAddress(Attrs);   
166    PrintModTime(Attrs);
167    PrintShadow(Attrs);
168    PrintKeys(Attrs);
169    PrintSshRSAKeys(Attrs);
170
171    for at in Attrs[1].keys():
172       if AttrInfo.has_key(at):
173          if AttrInfo[at][1] == 0:
174             print "      %-18s:" % (AttrInfo[at][0]),
175             for x in Attrs[1][at]:
176                print "'%s'" % (x),
177             if at == "uid":
178                print "(id=%s, gid=%s)" % (GetAttr(Attrs,"uidNumber","-1"),GetAttr(Attrs,"gidNumber","-1")),
179             print;
180          else:
181             OrderedIndex[AttrInfo[at][1]][1] = Attrs[1][at];
182                                        
183    Keys = OrderedIndex.keys();
184    Keys.sort();
185    for at in Keys:
186       if at < 100 or RootMode != 0:
187          print " %3u) %-18s: " % (at,OrderedIndex[at][0]),
188          for x in OrderedIndex[at][1]:
189             print "'%s'" % (re.sub('[\n\r]','?',x)),
190          print;
191
192 # Change a single attribute
193 def ChangeAttr(Attrs,Attr):
194    if (Attr == "supplementaryGid" or Attr == "allowedHost" or \
195        Attr == "member" or Attr == "dnsZoneEntry" or Attr == "mailWhitelist" or \
196        Attr == "mailRBL" or Attr == "mailRHSBL"):
197       return MultiChangeAttr(Attrs,Attr);
198
199    print "Old value: '%s'" % (GetAttr(Attrs,Attr,""));
200    print "Press enter to leave unchanged and a single space to set to empty";
201    NewValue = raw_input("New? ");
202   
203    # Empty string
204    if (NewValue == ""):
205       print "Leaving unchanged.";
206       return;
207
208    # Single space designates delete, trap the delete error
209    if (NewValue == " "):
210       print "Deleting.",;
211       try:
212          l.modify_s(UserDn,[(ldap.MOD_DELETE,Attr,None)]);
213       except ldap.NO_SUCH_ATTRIBUTE:
214          pass;
215
216       print;
217       Attrs[1][Attr] = [""];
218       return;
219
220    # Set a new value
221    print "Setting.",;
222    l.modify_s(UserDn,[(ldap.MOD_REPLACE,Attr,NewValue)]);
223    Attrs[1][Attr] = [NewValue];
224    print;
225
226 def MultiChangeAttr(Attrs,Attr):
227    # Make sure that we have an entry
228    if not Attrs[1].has_key(Attr):
229       Attrs[1][Attr] = [];
230
231    Attrs[1][Attr].sort();
232    print "Old values: ",Attrs[1][Attr];
233
234    Mode = raw_input("[D]elete or [A]dd? ").upper()
235    if (Mode != 'D' and Mode != 'A'):
236       return;
237
238    NewValue = raw_input("Value? ");
239    # Empty string
240    if (NewValue == ""):
241       print "Leaving unchanged.";
242       return;
243    
244    # Delete   
245    if (Mode == "D"):
246       print "Deleting.",;
247       try:
248          l.modify_s(UserDn,[(ldap.MOD_DELETE,Attr,NewValue)]);
249       except ldap.NO_SUCH_ATTRIBUTE:
250          print "Failed";
251
252       print;
253       Attrs[1][Attr].remove(NewValue);
254       return;
255
256    # Set a new value
257    print "Setting.",;
258    l.modify_s(UserDn,[(ldap.MOD_ADD,Attr,NewValue)]);
259    Attrs[1][Attr].append(NewValue);
260    print;
261
262 # Main program starts here
263 User = pwd.getpwuid(os.getuid())[0];
264 BindUser = User;
265 # Process options
266 try:
267    (options, arguments) = getopt.getopt(sys.argv[1:], "nu:c:a:r")
268 except getopt.GetoptError, data:
269    print data
270    sys.exit(1)
271
272 for (switch, val) in options:
273    if (switch == '-u'):
274       User = val;
275    elif (switch == '-a'):
276       BindUser = val;
277    elif (switch == '-c'):
278       BindUser = val;
279       User = val;
280    elif (switch == '-r'):
281       RootMode = 1;
282    elif (switch == '-n'):
283       BindUser = "";
284
285 if (BindUser != ""):
286    print "Accessing LDAP entry for '" + User + "'",
287 if (BindUser != User):
288    if (BindUser != ""):
289       print "as '" + BindUser + "'";
290 else:
291    print;
292 if (BindUser != ""):
293    Password = getpass(BindUser + "'s password: ");
294
295 # Connect to the ldap server
296 l = ldap.open(LDAPServer);
297 UserDn = "uid=" + BindUser + "," + BaseDn;
298 if (BindUser != ""):
299    l.simple_bind_s(UserDn,Password);
300 else:
301    l.simple_bind_s("","");
302 UserDn = "uid=" + User + "," + BaseDn;
303
304 # Enable changing of supplementary gid's
305 if (RootMode == 1):
306    # Items that root can edit
307    list = ["supplementaryGid","allowedHost","member"];
308    Count = 0;
309    for x in list:
310       AttrInfo[x][1] = 200 + Count;
311       OrderedIndex[AttrInfo[x][1]] = [AttrInfo[x][0], "",x];
312       OrigOrderedIndex[AttrInfo[x][1]] = [AttrInfo[x][0], "",x];
313       Count = Count + 1;
314
315 # Query the server for all of the attributes
316 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid=" + User);
317 if len(Attrs) == 0:
318    print "User",User,"was not found.";
319    sys.exit(0); 
320
321 # repeatedly show the account configuration
322 while(1):
323    ShowAttrs(Attrs[0]);
324    if (BindUser == ""):
325       sys.exit(0);
326
327    if RootMode == 1:
328       print "   a) Arbitary Change";
329       print "   R) Randomize Password";
330    print "   p) Change Password";
331    print "   u) Switch Users";
332    print "   x) Exit";
333    
334    # Prompt
335    Response = raw_input("Change? ");
336    if (Response == "x" or Response == "X" or Response == "q" or 
337        Response == "quit" or Response == "exit"):
338       break;
339
340    # Change who we are looking at
341    if (Response == 'u' or Response == 'U'):
342       NewUser = raw_input("User? ");
343       if NewUser == "":
344          continue;
345       NAttrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid=" + NewUser);
346       if len(NAttrs) == 0:
347          print "User",NewUser,"was not found.";
348          continue;
349       Attrs = NAttrs;
350       User = NewUser;
351       UserDn = "uid=" + User + "," + BaseDn;
352       OrderedIndex = copy.deepcopy(OrigOrderedIndex);
353       continue;
354
355    # Handle changing the password
356    if (Response == "p"):
357       print "Please enter a new password. Your password can be of unlimited length,";
358       print "contain spaces and other special characters. No checking is done on the";
359       print "strength of the passwords so pick good ones please!";
360
361       Pass1 = getpass(User + "'s new password: ");
362       Pass2 = getpass(User + "'s new password again: ");
363       if Pass1 != Pass2:
364          print "Passwords did not match";
365          raw_input("Press a key");
366          continue;
367
368       try:
369          Pass = HashPass(Pass1);
370       except:
371          print "%s: %s\n" %(sys.exc_type,sys.exc_value);
372          raw_input("Press a key");
373          continue;
374
375       print "Setting password..";
376       Pass = "{crypt}" + Pass;
377       l.modify_s(UserDn,[(ldap.MOD_REPLACE,"userPassword",Pass)]);
378       Attrs[0][1]["userPassword"] = [Pass];
379       continue;
380
381    # Randomize password
382    if Response == 'R' and RootMode == 1:
383       Resp = raw_input("Randomize Users Password? [no/yes]");
384       if Resp != "yes":
385          continue;
386          
387       # Generate a random password
388       try:
389          Password = GenPass();
390          Pass = HashPass(Password);
391       except:
392          print "%s: %s\n" %(sys.exc_type,sys.exc_value);
393          raw_input("Press a key");
394          continue;
395          
396       print "Setting password..";
397       Pass = "{crypt}" + Pass;
398       l.modify_s(UserDn,[(ldap.MOD_REPLACE,"userPassword",Pass)]);
399       Attrs[0][1]["userPassword"] = [Pass];
400       continue;
401
402    # Handle changing an arbitary value
403    if (Response == "a"):
404       Attr = raw_input("Attr? ");
405       ChangeAttr(Attrs[0],Attr);
406       continue;
407
408    # Convert the integer response
409    try:
410       ID = int(Response);
411       if (not OrderedIndex.has_key(ID) or (ID > 100 and RootMode == 0)):
412          raise ValueError;
413    except ValueError:
414       print "Invalid";
415       continue;
416
417    # Print the what to do prompt
418    print "Changing LDAP entry '%s' (%s)" % (OrderedIndex[ID][0],OrderedIndex[ID][2]);
419    print AttrPrompt[OrderedIndex[ID][2]][0];
420    ChangeAttr(Attrs[0],OrderedIndex[ID][2]);