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