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