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.
11 # Usage: userinfo -a <user> -u <user> -c <user> -r
12 # -a Set the authentication user (the user whose password you are
14 # -u Set the user to display
15 # -c Set both -a and -u, use this if your login uid is not in the
17 # -r Enable 'root' functions, do this if your uid has access to
18 # restricted variables.
20 # http://www.geocode.com/eagle.html-ssi
22 import string, time, posix, pwd, sys, getopt, ldap, crypt, whrandom, readline, copy;
23 from userdir_ldap import *;
26 AttrInfo = {"cn": ["First Name", 101],
27 "mn": ["Middle Name", 102],
28 "sn": ["Surname", 103],
29 "c": ["Country Code",1],
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]};
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"]};
74 # Create a map of IDs to desc,value,attr
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);
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"));
90 print "%-24s:" % ("Password last changed"),
91 print time.strftime("%a %d/%m/%Y %Z",time.localtime(Changed*24*60*60));
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."
98 # Print out the automatic time stamp information
99 def PrintModTime(Attrs):
100 Stamp = GetAttr(Attrs,"modifytimestamp","");
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];
107 Stamp = GetAttr(Attrs,"createtimestamp","");
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);
113 # Print the PGP key for a user
114 def PrintKeys(Attrs):
115 if Attrs[1].has_key("keyfingerprint") == 0:
118 for x in Attrs[1]["keyfingerprint"]:
120 print "%-24s:" % ("PGP/GPG Key Fingerprints"),
123 print "%-24s:" % (""),
137 print x[I]+x[I+1]+x[I+2]+x[I+3],
145 # Print the SSH RSA Authentication keys for a user
146 def PrintSshRSAKeys(Attrs):
147 if Attrs[1].has_key("sshrsaauthkey") == 0:
150 for x in Attrs[1]["sshrsaauthkey"]:
152 print "%-24s:" % ("SSH RSA Auth Keys"),
155 print "%-24s:" % (""),
157 print FormatSSHAuth(x);
159 # Display all of the attributes in a numbered list
160 def ShowAttrs(Attrs):
162 print EmailAddress(Attrs);
166 PrintSshRSAKeys(Attrs);
168 for at in Attrs[1].keys():
169 if AttrInfo.has_key(at):
170 if AttrInfo[at][1] == 0:
171 print " %-18s:" % (AttrInfo[at][0]),
172 for x in Attrs[1][at]:
175 print "(id=%s, gid=%s)" % (GetAttr(Attrs,"uidnumber","-1"),GetAttr(Attrs,"gidnumber","-1")),
178 OrderedIndex[AttrInfo[at][1]][1] = Attrs[1][at];
180 Keys = OrderedIndex.keys();
183 if at < 100 or RootMode != 0:
184 print " %3u) %-18s: " % (at,OrderedIndex[at][0]),
185 for x in OrderedIndex[at][1]:
186 print "'%s'" % (re.sub('[\n\r]','?',x)),
189 # Change a single attribute
190 def ChangeAttr(Attrs,Attr):
191 if (Attr == "supplementarygid" or Attr == "allowedhosts" or \
192 Attr == "member" or Attr == "dnszoneentry"):
193 return MultiChangeAttr(Attrs,Attr);
195 print "Old value: '%s'" % (GetAttr(Attrs,Attr,""));
196 print "Press enter to leave unchanged and a single space to set to empty";
197 NewValue = raw_input("New? ");
201 print "Leaving unchanged.";
204 # Single space designates delete, trap the delete error
205 if (NewValue == " "):
208 l.modify_s(UserDn,[(ldap.MOD_DELETE,Attr,None)]);
209 except ldap.NO_SUCH_ATTRIBUTE:
213 Attrs[1][Attr] = [""];
218 l.modify_s(UserDn,[(ldap.MOD_REPLACE,Attr,NewValue)]);
219 Attrs[1][Attr] = [NewValue];
222 def MultiChangeAttr(Attrs,Attr):
223 # Make sure that we have an entry
224 if not Attrs[1].has_key(Attr):
227 Attrs[1][Attr].sort();
228 print "Old values: ",Attrs[1][Attr];
230 Mode = string.upper(raw_input("[D]elete or [A]dd? "));
231 if (Mode != 'D' and Mode != 'A'):
234 NewValue = raw_input("Value? ");
237 print "Leaving unchanged.";
244 l.modify_s(UserDn,[(ldap.MOD_DELETE,Attr,NewValue)]);
245 except ldap.NO_SUCH_ATTRIBUTE:
249 Attrs[1][Attr].remove(NewValue);
254 l.modify_s(UserDn,[(ldap.MOD_ADD,Attr,NewValue)]);
255 Attrs[1][Attr].append(NewValue);
258 # Main program starts here
259 User = pwd.getpwuid(posix.getuid())[0];
262 (options, arguments) = getopt.getopt(sys.argv[1:], "nu:c:a:r")
263 for (switch, val) in options:
266 elif (switch == '-a'):
268 elif (switch == '-c'):
271 elif (switch == '-r'):
273 elif (switch == '-n'):
277 print "Accessing LDAP entry for '" + User + "'",
278 if (BindUser != User):
280 print "as '" + BindUser + "'";
284 Password = getpass(BindUser + "'s password: ");
286 # Connect to the ldap server
287 l = ldap.open(LDAPServer);
288 UserDn = "uid=" + BindUser + "," + BaseDn;
290 l.simple_bind_s(UserDn,Password);
292 l.simple_bind_s("","");
293 UserDn = "uid=" + User + "," + BaseDn;
295 # Enable changing of supplementary gid's
297 # Items that root can edit
298 list = ["supplementarygid","allowedhosts","member"];
301 AttrInfo[x][1] = 200 + Count;
302 OrderedIndex[AttrInfo[x][1]] = [AttrInfo[x][0], "",x];
303 OrigOrderedIndex[AttrInfo[x][1]] = [AttrInfo[x][0], "",x];
306 # Query the server for all of the attributes
307 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid=" + User);
309 print "User",User,"was not found.";
312 # repeatedly show the account configuration
319 print " a) Arbitary Change";
320 print " p) Change Password";
321 print " u) Switch Users";
325 Response = raw_input("Change? ");
326 if (Response == "x" or Response == "X" or Response == "q" or
327 Response == "quit" or Response == "exit"):
330 # Change who we are looking at
331 if (Response == 'u' or Response == 'U'):
332 NewUser = raw_input("User? ");
335 NAttrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid=" + NewUser);
337 print "User",NewUser,"was not found.";
341 UserDn = "uid=" + User + "," + BaseDn;
342 OrderedIndex = copy.deepcopy(OrigOrderedIndex);
345 # Handle changing the password
346 if (Response == "p"):
347 print "Please enter a new password. Your password can be of unlimited length,";
348 print "contain spaces and other special characters. No checking is done on the";
349 print "strength of the passwords so pick good ones please!";
351 Pass1 = getpass(User + "'s new password: ");
352 Pass2 = getpass(User + "'s new password again: ");
354 print "Passwords did not match";
355 raw_input("Press a key");
358 # Hash it telling glibc to use the MD5 algorithm - if you dont have
359 # glibc then just change Salt = "$1$" to Salt = "";
360 SaltVals = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/.";
362 for x in range(0,10):
363 Salt = Salt + SaltVals[whrandom.randint(0,len(SaltVals)-1)];
364 Pass = crypt.crypt(Pass1,Salt);
366 print "Caution! MD5 Password hashing failed, not changing password!";
367 raw_input("Press a key");
370 print "Setting password..";
371 Pass = "{crypt}" + Pass;
372 l.modify_s(UserDn,[(ldap.MOD_REPLACE,"userpassword",Pass)]);
375 # Handle changing an arbitary value
376 if (Response == "a"):
377 Attr = raw_input("Attr? ");
378 ChangeAttr(Attrs[0],Attr);
381 # Convert the integer response
384 if (not OrderedIndex.has_key(ID) or (ID > 100 and RootMode == 0)):
390 # Print the what to do prompt
391 print "Changing LDAP entry '%s' (%s)" % (OrderedIndex[ID][0],OrderedIndex[ID][2]);
392 print AttrPrompt[OrderedIndex[ID][2]][0];
393 ChangeAttr(Attrs[0],OrderedIndex[ID][2]);