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