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