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