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