Added host ACL
[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             "allowedhosts": ["Host ACL",0],
40             "member": ["LDAP Group",0],
41             "emailforward": ["Email Forwarding",8],
42             "ircnick": ["IRC Nickname",9],
43             "onvacation": ["Vacation Message",10],
44             "labeledurl": ["Home Page",11],
45             "latitude": ["Latitude",12],
46             "longitude": ["Longitude",13],
47             "comment": ["Comment",114],
48             "userpassword": ["Crypted Password",115]};
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               "labeledurl": ["Web home page"]};
71
72 # Create a map of IDs to desc,value,attr
73 OrderedIndex = {};
74 for at in AttrInfo.keys():
75    if (AttrInfo[at][1] != 0):
76       OrderedIndex[AttrInfo[at][1]] = [AttrInfo[at][0], "", at];
77 OrigOrderedIndex = copy.deepcopy(OrderedIndex);
78
79 # Show shadow information
80 def PrintShadow(Attrs):
81    Changed = int(GetAttr(Attrs,"shadowlastchange","0"));
82    MinDays = int(GetAttr(Attrs,"shadowmin","0"));
83    MaxDays = int(GetAttr(Attrs,"shadowmax","0"));
84    WarnDays = int(GetAttr(Attrs,"shadowwarning","0"));
85    InactDays = int(GetAttr(Attrs,"shadowinactive","0"));
86    Expire = int(GetAttr(Attrs,"shadowexpire","0"));
87
88    print "%-24s:" % ("Password last changed"),
89    print time.strftime("%a %d/%m/%Y %Z",time.localtime(Changed*24*60*60));
90    if (Expire > 0):
91       print "%-24s:" % ("Account expires on"),
92       print time.strftime("%a %d/%m/%Y %Z",time.localtime(Expire*24*60*60));
93    if (InactDays >= 0 and MaxDays < 99999):
94       print "Account aging is active, you must change your password every", MaxDays, "days."
95
96 # Print out the automatic time stamp information
97 def PrintModTime(Attrs):
98    Stamp = GetAttr(Attrs,"modifytimestamp","");
99    if len(Stamp) >= 13:
100       Time = (int(Stamp[0:4]),int(Stamp[4:6]),int(Stamp[6:8]),
101               int(Stamp[8:10]),int(Stamp[10:12]),int(Stamp[12:14]),0,0,-1);
102       print "%-24s:" % ("Record last modified on"), time.strftime("%a %d/%m/%Y %X UTC",Time),
103       print "by",ldap.explode_dn(GetAttr(Attrs,"modifiersname"),1)[0];
104
105    Stamp = GetAttr(Attrs,"createtimestamp","");
106    if len(Stamp) >= 13:
107       Time = (int(Stamp[0:4]),int(Stamp[4:6]),int(Stamp[6:8]),
108               int(Stamp[8:10]),int(Stamp[10:12]),int(Stamp[12:14]),0,0,-1);
109       print "%-24s:" % ("Record created on"), time.strftime("%a %d/%m/%Y %X UTC",Time);
110
111 # Print the PGP key for a user
112 def PrintKeys(Attrs):
113    if Attrs[1].has_key("keyfingerprint") == 0:
114       return;
115    First = 0;
116    for x in Attrs[1]["keyfingerprint"]:
117       if First == 0:
118          print "%-24s:" % ("PGP/GPG Key Fingerprints"),
119          First = 1;
120       else:
121          print "%-24s:" % (""),
122
123       # PGP Print
124       if (len(x) == 32):
125          I = 0;
126          while (I < len(x)):
127             print x[I]+x[I+1],
128             I = I + 2;
129             if I == 32/2:
130                print "",
131       elif (len(x) == 40):
132          # GPG Print
133          I = 0;
134          while (I < len(x)):
135             print x[I]+x[I+1]+x[I+2]+x[I+3],
136             I = I + 4;
137             if I == 40/2:
138                print "",
139       else:
140          print x,
141       print;
142
143 # Display all of the attributes in a numbered list
144 def ShowAttrs(Attrs):
145    print;
146    print EmailAddress(Attrs);   
147    PrintModTime(Attrs);
148    PrintShadow(Attrs);
149    PrintKeys(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 == "allowedhosts" or Attr == "member"):
175       return MultiChangeAttr(Attrs,Attr);
176
177    print "Old value: '%s'" % (GetAttr(Attrs,Attr,""));
178    print "Press enter to leave unchanged and a single space to set to empty";
179    NewValue = raw_input("New? ");
180   
181    # Empty string
182    if (NewValue == ""):
183       print "Leaving unchanged.";
184       return;
185
186    # Single space designates delete, trap the delete error
187    if (NewValue == " "):
188       print "Deleting.",;
189       try:
190          l.modify_s(UserDn,[(ldap.MOD_DELETE,Attr,None)]);
191       except ldap.NO_SUCH_ATTRIBUTE:
192          pass;
193
194       print;
195       Attrs[1][Attr] = [""];
196       return;
197
198    # Set a new value
199    print "Setting.",;
200    l.modify_s(UserDn,[(ldap.MOD_REPLACE,Attr,NewValue)]);
201    Attrs[1][Attr] = [NewValue];
202    print;
203
204 def MultiChangeAttr(Attrs,Attr):
205    # Make sure that we have an entry
206    if not Attrs[1].has_key(Attr):
207       Attrs[1][Attr] = [];
208
209    Attrs[1][Attr].sort();
210    print "Old values: ",Attrs[1][Attr];
211
212    Mode = string.upper(raw_input("[D]elete or [A]dd? "));
213    if (Mode != 'D' and Mode != 'A'):
214       return;
215
216    NewValue = raw_input("Value? ");
217    # Empty string
218    if (NewValue == ""):
219       print "Leaving unchanged.";
220       return;
221    
222    # Delete   
223    if (Mode == "D"):
224       print "Deleting.",;
225       try:
226          l.modify_s(UserDn,[(ldap.MOD_DELETE,Attr,NewValue)]);
227       except ldap.NO_SUCH_ATTRIBUTE:
228          print "Failed";
229
230       print;
231       Attrs[1][Attr].remove(NewValue);
232       return;
233
234    # Set a new value
235    print "Setting.",;
236    l.modify_s(UserDn,[(ldap.MOD_ADD,Attr,NewValue)]);
237    Attrs[1][Attr].append(NewValue);
238    print;
239
240 # Main program starts here
241 User = pwd.getpwuid(posix.getuid())[0];
242 BindUser = User;
243 # Process options
244 (options, arguments) = getopt.getopt(sys.argv[1:], "nu:c:a:r")
245 for (switch, val) in options:
246    if (switch == '-u'):
247       User = val;
248    elif (switch == '-a'):
249       BindUser = val;
250    elif (switch == '-c'):
251       BindUser = val;
252       User = val;
253    elif (switch == '-r'):
254       RootMode = 1;
255    elif (switch == '-n'):
256       BindUser = "";
257
258 if (BindUser != ""):
259    print "Accessing LDAP entry for '" + User + "'",
260 if (BindUser != User):
261    if (BindUser != ""):
262       print "as '" + BindUser + "'";
263 else:
264    print;
265 if (BindUser != ""):
266    Password = getpass(BindUser + "'s password: ");
267
268 # Connect to the ldap server
269 l = ldap.open(LDAPServer);
270 UserDn = "uid=" + BindUser + "," + BaseDn;
271 if (BindUser != ""):
272    l.simple_bind_s(UserDn,Password);
273 else:
274    l.simple_bind_s("","");
275 UserDn = "uid=" + User + "," + BaseDn;
276
277 # Enable changing of supplementary gid's
278 if (RootMode == 1):
279    # Items that root can edit
280    list = ["supplementarygid","allowedhosts","member"];
281    Count = 0;
282    for x in list:
283       AttrInfo[x][1] = 200 + Count;
284       OrderedIndex[AttrInfo[x][1]] = [AttrInfo[x][0], "",x];
285       OrigOrderedIndex[AttrInfo[x][1]] = [AttrInfo[x][0], "",x];
286       Count = Count + 1;
287
288 # Query the server for all of the attributes
289 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid=" + User);
290
291 # repeatedly show the account configuration
292 while(1):
293    ShowAttrs(Attrs[0]);
294    if (BindUser == ""):
295       sys.exit(0);
296
297    if RootMode == 1:
298       print "   a) Arbitary Change";
299    print "   p) Change Password";
300    print "   u) Switch Users";
301    print "   x) Exit";
302    
303    # Prompt
304    Response = raw_input("Change? ");
305    if (Response == "x" or Response == "X" or Response == "q" or 
306        Response == "quit" or Response == "exit"):
307       break;
308
309    # Change who we are looking at
310    if (Response == 'u' or Response == 'U'):
311       NewUser = raw_input("User? ");
312       if NewUser == "":
313          continue;
314       User = NewUser;
315       UserDn = "uid=" + User + "," + BaseDn;
316       Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid=" + User);
317       OrderedIndex = copy.deepcopy(OrigOrderedIndex);
318       continue;
319
320    # Handle changing the password
321    if (Response == "p"):
322       print "Please enter a new password. Your password can be of unlimited length,";
323       print "contain spaces and other special characters. No checking is done on the";
324       print "strength of the passwords so pick good ones please!";
325
326       Pass1 = getpass(User + "'s new password: ");
327       Pass2 = getpass(User + "'s new password again: ");
328       if Pass1 != Pass2:
329          print "Passwords did not match";
330          raw_input("Press a key");
331          continue;
332
333       # Hash it telling glibc to use the MD5 algorithm - if you dont have
334       # glibc then just change Salt = "$1$" to Salt = "";
335       SaltVals = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/.";
336       Salt  = "$1$";
337       for x in range(0,10):
338          Salt = Salt + SaltVals[whrandom.randint(0,len(SaltVals)-1)];
339       Pass = crypt.crypt(Pass1,Salt);
340       if len(Pass) < 14:
341          print "Caution! MD5 Password hashing failed, not changing password!";
342          raw_input("Press a key");
343          continue;
344
345       print "Setting password..";
346       Pass = "{crypt}" + Pass;
347       l.modify_s(UserDn,[(ldap.MOD_REPLACE,"userpassword",Pass)]);
348       continue;
349
350    # Handle changing an arbitary value
351    if (Response == "a"):
352       Attr = raw_input("Attr? ");
353       ChangeAttr(Attrs[0],Attr);
354       continue;
355
356    # Convert the integer response
357    try:
358       ID = int(Response);
359       if (not OrderedIndex.has_key(ID) or (ID > 100 and RootMode == 0)):
360          raise ValueError;
361    except ValueError:
362       print "Invalid";
363       continue;
364
365    # Print the what to do prompt
366    print "Changing LDAP entry '%s' (%s)" % (OrderedIndex[ID][0],OrderedIndex[ID][2]);
367    print AttrPrompt[OrderedIndex[ID][2]][0];
368    ChangeAttr(Attrs[0],OrderedIndex[ID][2]);