ce06934113e36dacd334bc82bd0b635e74eb6410
[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, posix, 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             "comment": ["Comment",114],
46             "userpassword": ["Crypted Password",115],
47             "dnszoneentry": ["d.net Entry",116]};
48
49 AttrPrompt = {"cn": ["Common name or first name"],
50               "mn": ["Middle name (or initial if it ends in a dot)"],
51               "sn": ["Surname or last name"],
52               "c": ["ISO 2 letter country code, such as US, DE, etc"],
53               "l": ["City name, State/Provice (Locality)\n e.g. Dallas, Texas"],
54               "facsimiletelephonenumber": ["Fax phone number, with area code and country code"],
55               "telephonenumber": ["Voice phone number"],
56               "postaladdress": ["Complete mailing address including postal codes and country designations\nSeperate lines using a $ character"],
57               "postalcode": ["Postal Code or Zip Code"],
58               "loginshell": ["Login shell with full path (no check is done for validity)"],
59               "emailforward": ["EMail address to send all mail to or blank to disable"],
60               "ircnick": ["IRC nickname if you use IRC"],
61               "onvacation": ["A message if on vaction, indicating the time of departure and return"],
62               "userpassword": ["The users Crypt'd password"],
63               "comment": ["Admin Comment about the account"],
64               "supplementarygid": ["Groups the user is in"],
65               "allowedhosts": ["Grant access to certain hosts"],
66               "member": ["LDAP Group Member for slapd ACLs"],
67               "latitude": ["XEarth latitude in ISO 6709 format - see /usr/share/zoneinfo/zone.tab or etak.com"],
68               "longitude": ["XEarth latitude in ISO 6709 format - see /usr/share/zoneinfo/zone.tab or etak.com"],
69               "dnszoneentry": ["DNS Zone fragment associated this this user"],
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       print FormatPGPKey(x);
123
124 # Print the SSH RSA Authentication keys for a user
125 def PrintSshRSAKeys(Attrs):
126    if Attrs[1].has_key("sshrsaauthkey") == 0:
127       return;
128    First = 0;
129    for x in Attrs[1]["sshrsaauthkey"]:
130       if First == 0:
131          print "%-24s:" % ("SSH RSA Auth Keys"),
132          First = 1;
133       else:
134          print "%-24s:" % (""),
135
136       print FormatSSHAuth(x);
137       
138 # Display all of the attributes in a numbered list
139 def ShowAttrs(Attrs):
140    print;
141    print EmailAddress(Attrs);   
142    PrintModTime(Attrs);
143    PrintShadow(Attrs);
144    PrintKeys(Attrs);
145    PrintSshRSAKeys(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" or Attr == "allowedhosts" or \
171        Attr == "member" or Attr == "dnszoneentry"):
172       return MultiChangeAttr(Attrs,Attr);
173
174    print "Old value: '%s'" % (GetAttr(Attrs,Attr,""));
175    print "Press enter to leave unchanged and a single space to set to empty";
176    NewValue = raw_input("New? ");
177   
178    # Empty string
179    if (NewValue == ""):
180       print "Leaving unchanged.";
181       return;
182
183    # Single space designates delete, trap the delete error
184    if (NewValue == " "):
185       print "Deleting.",;
186       try:
187          l.modify_s(UserDn,[(ldap.MOD_DELETE,Attr,None)]);
188       except ldap.NO_SUCH_ATTRIBUTE:
189          pass;
190
191       print;
192       Attrs[1][Attr] = [""];
193       return;
194
195    # Set a new value
196    print "Setting.",;
197    l.modify_s(UserDn,[(ldap.MOD_REPLACE,Attr,NewValue)]);
198    Attrs[1][Attr] = [NewValue];
199    print;
200
201 def MultiChangeAttr(Attrs,Attr):
202    # Make sure that we have an entry
203    if not Attrs[1].has_key(Attr):
204       Attrs[1][Attr] = [];
205
206    Attrs[1][Attr].sort();
207    print "Old values: ",Attrs[1][Attr];
208
209    Mode = string.upper(raw_input("[D]elete or [A]dd? "));
210    if (Mode != 'D' and Mode != 'A'):
211       return;
212
213    NewValue = raw_input("Value? ");
214    # Empty string
215    if (NewValue == ""):
216       print "Leaving unchanged.";
217       return;
218    
219    # Delete   
220    if (Mode == "D"):
221       print "Deleting.",;
222       try:
223          l.modify_s(UserDn,[(ldap.MOD_DELETE,Attr,NewValue)]);
224       except ldap.NO_SUCH_ATTRIBUTE:
225          print "Failed";
226
227       print;
228       Attrs[1][Attr].remove(NewValue);
229       return;
230
231    # Set a new value
232    print "Setting.",;
233    l.modify_s(UserDn,[(ldap.MOD_ADD,Attr,NewValue)]);
234    Attrs[1][Attr].append(NewValue);
235    print;
236
237 # Main program starts here
238 User = pwd.getpwuid(posix.getuid())[0];
239 BindUser = User;
240 # Process options
241 (options, arguments) = getopt.getopt(sys.argv[1:], "nu:c:a:r")
242 for (switch, val) in options:
243    if (switch == '-u'):
244       User = val;
245    elif (switch == '-a'):
246       BindUser = val;
247    elif (switch == '-c'):
248       BindUser = val;
249       User = val;
250    elif (switch == '-r'):
251       RootMode = 1;
252    elif (switch == '-n'):
253       BindUser = "";
254
255 if (BindUser != ""):
256    print "Accessing LDAP entry for '" + User + "'",
257 if (BindUser != User):
258    if (BindUser != ""):
259       print "as '" + BindUser + "'";
260 else:
261    print;
262 if (BindUser != ""):
263    Password = getpass(BindUser + "'s password: ");
264
265 # Connect to the ldap server
266 l = ldap.open(LDAPServer);
267 UserDn = "uid=" + BindUser + "," + BaseDn;
268 if (BindUser != ""):
269    l.simple_bind_s(UserDn,Password);
270 else:
271    l.simple_bind_s("","");
272 UserDn = "uid=" + User + "," + BaseDn;
273
274 # Enable changing of supplementary gid's
275 if (RootMode == 1):
276    # Items that root can edit
277    list = ["supplementarygid","allowedhosts","member"];
278    Count = 0;
279    for x in list:
280       AttrInfo[x][1] = 200 + Count;
281       OrderedIndex[AttrInfo[x][1]] = [AttrInfo[x][0], "",x];
282       OrigOrderedIndex[AttrInfo[x][1]] = [AttrInfo[x][0], "",x];
283       Count = Count + 1;
284
285 # Query the server for all of the attributes
286 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid=" + User);
287 if len(Attrs) == 0:
288    print "User",User,"was not found.";
289    sys.exit(0); 
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       NAttrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid=" + NewUser);
315       if len(NAttrs) == 0:
316          print "User",NewUser,"was not found.";
317          continue;
318       Attrs = NAttrs;
319       User = NewUser;
320       UserDn = "uid=" + User + "," + BaseDn;
321       OrderedIndex = copy.deepcopy(OrigOrderedIndex);
322       continue;
323
324    # Handle changing the password
325    if (Response == "p"):
326       print "Please enter a new password. Your password can be of unlimited length,";
327       print "contain spaces and other special characters. No checking is done on the";
328       print "strength of the passwords so pick good ones please!";
329
330       Pass1 = getpass(User + "'s new password: ");
331       Pass2 = getpass(User + "'s new password again: ");
332       if Pass1 != Pass2:
333          print "Passwords did not match";
334          raw_input("Press a key");
335          continue;
336
337       # Hash it telling glibc to use the MD5 algorithm - if you dont have
338       # glibc then just change Salt = "$1$" to Salt = "";
339       SaltVals = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/.";
340       Salt  = "$1$";
341       for x in range(0,10):
342          Salt = Salt + SaltVals[whrandom.randint(0,len(SaltVals)-1)];
343       Pass = crypt.crypt(Pass1,Salt);
344       if len(Pass) < 14:
345          print "Caution! MD5 Password hashing failed, not changing password!";
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       continue;
353
354    # Handle changing an arbitary value
355    if (Response == "a"):
356       Attr = raw_input("Attr? ");
357       ChangeAttr(Attrs[0],Attr);
358       continue;
359
360    # Convert the integer response
361    try:
362       ID = int(Response);
363       if (not OrderedIndex.has_key(ID) or (ID > 100 and RootMode == 0)):
364          raise ValueError;
365    except ValueError:
366       print "Invalid";
367       continue;
368
369    # Print the what to do prompt
370    print "Changing LDAP entry '%s' (%s)" % (OrderedIndex[ID][0],OrderedIndex[ID][2]);
371    print AttrPrompt[OrderedIndex[ID][2]][0];
372    ChangeAttr(Attrs[0],OrderedIndex[ID][2]);