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 import time, os, pwd, sys, getopt, ldap, crypt, readline, copy;
21 from userdir_ldap import *;
24 AttrInfo = {"cn": ["First Name", 101],
25 "mn": ["Middle Name", 102],
26 "sn": ["Surname", 103],
27 "c": ["Country Code",1],
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 "allowedHost": ["Host ACL",0],
38 "member": ["LDAP Group",0],
39 "emailForward": ["Email Forwarding",8],
40 "ircNick": ["IRC Nickname",9],
41 "onVacation": ["Vacation Message",10],
42 "labeledURI": ["Home Page",11],
43 "latitude": ["Latitude",12],
44 "longitude": ["Longitude",13],
45 "icqUin": ["ICQ UIN",14],
46 "jabberJID": ["Jabber ID",15],
47 "privateSub": ["Debian-Private",16],
48 "gender": ["Gender",17],
49 "birthDate": ["Date of Birth",18],
50 "mailDisableMessage": ["Mail Disabled",19],
51 "mailGreylisting": ["Mail Greylisting",20],
52 "mailCallout": ["Mail Callouts",21],
53 "mailRBL": ["Mail RBLs",22],
54 "mailRHSBL": ["Mail RHSBLs",23],
55 "mailWhitelist": ["Mail Whitelist",24],
56 "comment": ["Comment",116],
57 "userPassword": ["Crypted Password",117],
58 "dnsZoneEntry": ["d.net Entry",118],
59 "VoIP": ["VoIP Address",119]};
61 AttrPrompt = {"cn": ["Common name or first name"],
62 "mn": ["Middle name (or initial if it ends in a dot)"],
63 "sn": ["Surname or last name"],
64 "c": ["ISO 2 letter country code, such as US, DE, etc"],
65 "l": ["City name, State/Provice (Locality)\n e.g. Dallas, Texas"],
66 "facsimileTelephoneNumber": ["Fax phone number, with area code and country code"],
67 "telephoneNumber": ["Voice phone number"],
68 "postalAddress": ["Complete mailing address including postal codes and country designations\nSeperate lines using a $ character"],
69 "postalCode": ["Postal Code or Zip Code"],
70 "loginShell": ["Login shell with full path (no check is done for validity)"],
71 "emailForward": ["EMail address to send all mail to or blank to disable"],
72 "ircNick": ["IRC nickname if you use IRC"],
73 "onVacation": ["A message if on vaction, indicating the time of departure and return"],
74 "userPassword": ["The users Crypt'd password"],
75 "comment": ["Admin Comment about the account"],
76 "supplementaryGid": ["Groups the user is in"],
77 "allowedHost": ["Grant access to certain hosts"],
78 "privateSub": ["Debian-Private mailing list subscription"],
79 "gender": ["ISO5218 Gender code (1=male,2=female,9=unspecified)"],
80 "birthDate": ["Date of Birth (YYYYMMDD)"],
81 "mailDisableMessage": ["Error message to return via SMTP"],
82 "mailGreylisting": ["SMTP Greylisting (TRUE/FALSE)"],
83 "mailCallout": ["SMTP Callouts (TRUE/FALSE)"],
84 "mailRBL": ["SMTP time RBL lists"],
85 "mailRHSBL": ["SMTP time RHSBL lists"],
86 "mailWhitelist": ["SMTP time whitelist from other checks"],
87 "member": ["LDAP Group Member for slapd ACLs"],
88 "latitude": ["XEarth latitude in ISO 6709 format - see /usr/share/zoneinfo/zone.tab or etak.com"],
89 "longitude": ["XEarth latitude in ISO 6709 format - see /usr/share/zoneinfo/zone.tab or etak.com"],
90 "dnsZoneEntry": ["DNS Zone fragment associated this this user"],
91 "labeledURI": ["Web home page"],
92 "jabberJID": ["Jabber ID"],
93 "icqUin": ["ICQ UIN Number"],
94 "VoIP": ["VoIP Address"]};
96 # Create a map of IDs to desc,value,attr
98 for at in AttrInfo.keys():
99 if (AttrInfo[at][1] != 0):
100 OrderedIndex[AttrInfo[at][1]] = [AttrInfo[at][0], "", at];
101 OrigOrderedIndex = copy.deepcopy(OrderedIndex);
103 # Show shadow information
104 def PrintShadow(Attrs):
105 Changed = int(GetAttr(Attrs,"shadowLastChange","0"));
106 MinDays = int(GetAttr(Attrs,"shadowMin","0"));
107 MaxDays = int(GetAttr(Attrs,"shadowMax","0"));
108 WarnDays = int(GetAttr(Attrs,"shadowWarning","0"));
109 InactDays = int(GetAttr(Attrs,"shadowinactive","0"));
110 Expire = int(GetAttr(Attrs,"shadowexpire","0"));
112 print "%-24s:" % ("Password last changed"),
113 print time.strftime("%a %d/%m/%Y %Z",time.localtime(Changed*24*60*60));
115 print "%-24s:" % ("Account expires on"),
116 print time.strftime("%a %d/%m/%Y %Z",time.localtime(Expire*24*60*60));
117 if (InactDays >= 0 and MaxDays < 99999):
118 print "Account aging is active, you must change your password every", MaxDays, "days."
120 # Print out the automatic time stamp information
121 def PrintModTime(Attrs):
122 Stamp = GetAttr(Attrs,"modifyTimestamp","");
124 Time = (int(Stamp[0:4]),int(Stamp[4:6]),int(Stamp[6:8]),
125 int(Stamp[8:10]),int(Stamp[10:12]),int(Stamp[12:14]),0,0,-1);
126 print "%-24s:" % ("Record last modified on"), time.strftime("%a %d/%m/%Y %X UTC",Time),
127 print "by",ldap.explode_dn(GetAttr(Attrs,"modifiersName"),1)[0];
129 Stamp = GetAttr(Attrs,"createTimestamp","");
131 Time = (int(Stamp[0:4]),int(Stamp[4:6]),int(Stamp[6:8]),
132 int(Stamp[8:10]),int(Stamp[10:12]),int(Stamp[12:14]),0,0,-1);
133 print "%-24s:" % ("Record created on"), time.strftime("%a %d/%m/%Y %X UTC",Time);
135 # Print the PGP key for a user
136 def PrintKeys(Attrs):
137 if Attrs[1].has_key("keyFingerPrint") == 0:
140 for x in Attrs[1]["keyFingerPrint"]:
142 print "%-24s:" % ("PGP/GPG Key Fingerprints"),
145 print "%-24s:" % (""),
146 print FormatPGPKey(x);
148 # Print the SSH RSA Authentication keys for a user
149 def PrintSshRSAKeys(Attrs):
150 if Attrs[1].has_key("sshRSAAuthKey") == 0:
153 for x in Attrs[1]["sshRSAAuthKey"]:
155 print "%-24s:" % ("SSH Auth Keys"),
158 print "%-24s:" % (""),
160 print FormatSSHAuth(x);
162 # Display all of the attributes in a numbered list
163 def ShowAttrs(Attrs):
165 print EmailAddress(Attrs);
169 PrintSshRSAKeys(Attrs);
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]:
178 print "(id=%s, gid=%s)" % (GetAttr(Attrs,"uidNumber","-1"),GetAttr(Attrs,"gidNumber","-1")),
181 OrderedIndex[AttrInfo[at][1]][1] = Attrs[1][at];
183 Keys = OrderedIndex.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)),
192 # Change a single attribute
193 def ChangeAttr(Attrs,Attr):
194 if (Attr == "supplementaryGid" or Attr == "allowedHost" or \
195 Attr == "member" or Attr == "dnsZoneEntry" or Attr == "mailWhitelist" or \
196 Attr == "mailRBL" or Attr == "mailRHSBL"):
197 return MultiChangeAttr(Attrs,Attr);
199 print "Old value: '%s'" % (GetAttr(Attrs,Attr,""));
200 print "Press enter to leave unchanged and a single space to set to empty";
201 NewValue = raw_input("New? ");
205 print "Leaving unchanged.";
208 # Single space designates delete, trap the delete error
209 if (NewValue == " "):
212 l.modify_s(UserDn,[(ldap.MOD_DELETE,Attr,None)]);
213 except ldap.NO_SUCH_ATTRIBUTE:
217 Attrs[1][Attr] = [""];
222 l.modify_s(UserDn,[(ldap.MOD_REPLACE,Attr,NewValue)]);
223 Attrs[1][Attr] = [NewValue];
226 def MultiChangeAttr(Attrs,Attr):
227 # Make sure that we have an entry
228 if not Attrs[1].has_key(Attr):
231 Attrs[1][Attr].sort();
232 print "Old values: ",Attrs[1][Attr];
234 Mode = raw_input("[D]elete or [A]dd? ").upper()
235 if (Mode != 'D' and Mode != 'A'):
238 NewValue = raw_input("Value? ");
241 print "Leaving unchanged.";
248 l.modify_s(UserDn,[(ldap.MOD_DELETE,Attr,NewValue)]);
249 except ldap.NO_SUCH_ATTRIBUTE:
253 Attrs[1][Attr].remove(NewValue);
258 l.modify_s(UserDn,[(ldap.MOD_ADD,Attr,NewValue)]);
259 Attrs[1][Attr].append(NewValue);
262 # Main program starts here
263 User = pwd.getpwuid(os.getuid())[0];
267 (options, arguments) = getopt.getopt(sys.argv[1:], "nu:c:a:r")
268 except getopt.GetoptError, data:
272 for (switch, val) in options:
275 elif (switch == '-a'):
277 elif (switch == '-c'):
280 elif (switch == '-r'):
282 elif (switch == '-n'):
286 print "Accessing LDAP entry for '" + User + "'",
287 if (BindUser != User):
289 print "as '" + BindUser + "'";
293 Password = getpass(BindUser + "'s password: ");
295 # Connect to the ldap server
296 l = ldap.open(LDAPServer);
297 UserDn = "uid=" + BindUser + "," + BaseDn;
299 l.simple_bind_s(UserDn,Password);
301 l.simple_bind_s("","");
302 UserDn = "uid=" + User + "," + BaseDn;
304 # Enable changing of supplementary gid's
306 # Items that root can edit
307 list = ["supplementaryGid","allowedHost","member"];
310 AttrInfo[x][1] = 200 + Count;
311 OrderedIndex[AttrInfo[x][1]] = [AttrInfo[x][0], "",x];
312 OrigOrderedIndex[AttrInfo[x][1]] = [AttrInfo[x][0], "",x];
315 # Query the server for all of the attributes
316 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid=" + User);
318 print "User",User,"was not found.";
321 # repeatedly show the account configuration
328 print " a) Arbitary Change";
329 print " R) Randomize Password";
330 print " p) Change Password";
331 print " L) Lock account";
332 print " u) Switch Users";
336 Response = raw_input("Change? ");
337 if (Response == "x" or Response == "X" or Response == "q" or
338 Response == "quit" or Response == "exit"):
341 # Change who we are looking at
342 if (Response == 'u' or Response == 'U'):
343 NewUser = raw_input("User? ");
346 NAttrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid=" + NewUser);
348 print "User",NewUser,"was not found.";
352 UserDn = "uid=" + User + "," + BaseDn;
353 OrderedIndex = copy.deepcopy(OrigOrderedIndex);
356 # Handle changing the password
357 if (Response == "p"):
358 print "Please enter a new password. Your password can be of unlimited length,";
359 print "contain spaces and other special characters. No checking is done on the";
360 print "strength of the passwords so pick good ones please!";
362 Pass1 = getpass(User + "'s new password: ");
363 Pass2 = getpass(User + "'s new password again: ");
365 print "Passwords did not match";
366 raw_input("Press a key");
370 Pass = HashPass(Pass1);
372 print "%s: %s\n" %(sys.exc_type,sys.exc_value);
373 raw_input("Press a key");
376 print "Setting password..";
377 Pass = "{crypt}" + Pass;
378 shadowLast = str(int(time.time()/24/60/60));
379 l.modify_s(UserDn,[(ldap.MOD_REPLACE,"userPassword",Pass),
380 (ldap.MOD_REPLACE,"shadowLastChange",shadowLast)]);
381 Attrs[0][1]["userPassword"] = [Pass];
382 Attrs[0][1]["shadowLastChange"] = [shadowLast];
386 if Response == 'R' and RootMode == 1:
387 Resp = raw_input("Randomize Users Password? [no/yes]");
391 # Generate a random password
393 Password = GenPass();
394 Pass = HashPass(Password);
396 print "%s: %s\n" %(sys.exc_type,sys.exc_value);
397 raw_input("Press a key");
400 print "Setting password..";
401 Pass = "{crypt}" + Pass;
402 shadowLast = str(int(time.time()/24/60/60));
403 l.modify_s(UserDn,[(ldap.MOD_REPLACE,"userPassword",Pass),
404 (ldap.MOD_REPLACE,"shadowLastChange",shadowLast)]);
405 Attrs[0][1]["userPassword"] = [Pass];
406 Attrs[0][1]["shadowLastChange"] = [shadowLast];
410 if Response == 'L' and RootMode == 1:
411 Resp = raw_input("Really lock account? [no/yes]");
415 print "Setting password..";
416 shadowLast = str(int(time.time()/24/60/60));
418 (ldap.MOD_REPLACE,"userPassword","{crypt}*LK*"),
419 (ldap.MOD_REPLACE,"mailDisableMessage","account locked"),
420 (ldap.MOD_REPLACE,"shadowLastChange",shadowLast)]);
421 Attrs[0][1]["userPassword"] = ["{crypt}*LK*"];
422 Attrs[0][1]["mailDisableMessage"] = ["account locked"];
423 Attrs[0][1]["shadowLastChange"] = [shadowLast];
426 # Handle changing an arbitary value
427 if (Response == "a"):
428 Attr = raw_input("Attr? ");
429 ChangeAttr(Attrs[0],Attr);
432 # Convert the integer response
435 if (not OrderedIndex.has_key(ID) or (ID > 100 and RootMode == 0)):
441 # Print the what to do prompt
442 print "Changing LDAP entry '%s' (%s)" % (OrderedIndex[ID][0],OrderedIndex[ID][2]);
443 print AttrPrompt[OrderedIndex[ID][2]][0];
444 ChangeAttr(Attrs[0],OrderedIndex[ID][2]);