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 string, 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]};
60 AttrPrompt = {"cn": ["Common name or first name"],
61 "mn": ["Middle name (or initial if it ends in a dot)"],
62 "sn": ["Surname or last name"],
63 "c": ["ISO 2 letter country code, such as US, DE, etc"],
64 "l": ["City name, State/Provice (Locality)\n e.g. Dallas, Texas"],
65 "facsimileTelephoneNumber": ["Fax phone number, with area code and country code"],
66 "telephoneNumber": ["Voice phone number"],
67 "postalAddress": ["Complete mailing address including postal codes and country designations\nSeperate lines using a $ character"],
68 "postalCode": ["Postal Code or Zip Code"],
69 "loginShell": ["Login shell with full path (no check is done for validity)"],
70 "emailForward": ["EMail address to send all mail to or blank to disable"],
71 "ircNick": ["IRC nickname if you use IRC"],
72 "onVacation": ["A message if on vaction, indicating the time of departure and return"],
73 "userPassword": ["The users Crypt'd password"],
74 "comment": ["Admin Comment about the account"],
75 "supplementaryGid": ["Groups the user is in"],
76 "allowedHost": ["Grant access to certain hosts"],
77 "privateSub": ["Debian-Private mailing list subscription"],
78 "gender": ["ISO5218 Gender code (1=male,2=female,9=unspecified)"],
79 "birthDate": ["Date of Birth (YYYYMMDD)"],
80 "mailDisableMessage": ["Error message to return via SMTP"],
81 "mailGreylisting": ["SMTP Greylisting (TRUE/FALSE)"],
82 "mailCallout": ["SMTP Callouts (TRUE/FALSE)"],
83 "mailRBL": ["SMTP time RBL lists"],
84 "mailRHSBL": ["SMTP time RHSBL lists"],
85 "mailWhitelist": ["SMTP time whitelist from other checks"],
86 "member": ["LDAP Group Member for slapd ACLs"],
87 "latitude": ["XEarth latitude in ISO 6709 format - see /usr/share/zoneinfo/zone.tab or etak.com"],
88 "longitude": ["XEarth latitude in ISO 6709 format - see /usr/share/zoneinfo/zone.tab or etak.com"],
89 "dnsZoneEntry": ["DNS Zone fragment associated this this user"],
90 "labeledURI": ["Web home page"],
91 "jabberJID": ["Jabber ID"],
92 "icqUin": ["ICQ UIN Number"]};
94 # Create a map of IDs to desc,value,attr
96 for at in AttrInfo.keys():
97 if (AttrInfo[at][1] != 0):
98 OrderedIndex[AttrInfo[at][1]] = [AttrInfo[at][0], "", at];
99 OrigOrderedIndex = copy.deepcopy(OrderedIndex);
101 # Show shadow information
102 def PrintShadow(Attrs):
103 Changed = int(GetAttr(Attrs,"shadowLastChange","0"));
104 MinDays = int(GetAttr(Attrs,"shadowMin","0"));
105 MaxDays = int(GetAttr(Attrs,"shadowMax","0"));
106 WarnDays = int(GetAttr(Attrs,"shadowWarning","0"));
107 InactDays = int(GetAttr(Attrs,"shadowinactive","0"));
108 Expire = int(GetAttr(Attrs,"shadowexpire","0"));
110 print "%-24s:" % ("Password last changed"),
111 print time.strftime("%a %d/%m/%Y %Z",time.localtime(Changed*24*60*60));
113 print "%-24s:" % ("Account expires on"),
114 print time.strftime("%a %d/%m/%Y %Z",time.localtime(Expire*24*60*60));
115 if (InactDays >= 0 and MaxDays < 99999):
116 print "Account aging is active, you must change your password every", MaxDays, "days."
118 # Print out the automatic time stamp information
119 def PrintModTime(Attrs):
120 Stamp = GetAttr(Attrs,"modifyTimestamp","");
122 Time = (int(Stamp[0:4]),int(Stamp[4:6]),int(Stamp[6:8]),
123 int(Stamp[8:10]),int(Stamp[10:12]),int(Stamp[12:14]),0,0,-1);
124 print "%-24s:" % ("Record last modified on"), time.strftime("%a %d/%m/%Y %X UTC",Time),
125 print "by",ldap.explode_dn(GetAttr(Attrs,"modifiersName"),1)[0];
127 Stamp = GetAttr(Attrs,"createTimestamp","");
129 Time = (int(Stamp[0:4]),int(Stamp[4:6]),int(Stamp[6:8]),
130 int(Stamp[8:10]),int(Stamp[10:12]),int(Stamp[12:14]),0,0,-1);
131 print "%-24s:" % ("Record created on"), time.strftime("%a %d/%m/%Y %X UTC",Time);
133 # Print the PGP key for a user
134 def PrintKeys(Attrs):
135 if Attrs[1].has_key("keyFingerPrint") == 0:
138 for x in Attrs[1]["keyFingerPrint"]:
140 print "%-24s:" % ("PGP/GPG Key Fingerprints"),
143 print "%-24s:" % (""),
144 print FormatPGPKey(x);
146 # Print the SSH RSA Authentication keys for a user
147 def PrintSshRSAKeys(Attrs):
148 if Attrs[1].has_key("sshRSAAuthKey") == 0:
151 for x in Attrs[1]["sshRSAAuthKey"]:
153 print "%-24s:" % ("SSH Auth Keys"),
156 print "%-24s:" % (""),
158 print FormatSSHAuth(x);
160 # Display all of the attributes in a numbered list
161 def ShowAttrs(Attrs):
163 print EmailAddress(Attrs);
167 PrintSshRSAKeys(Attrs);
169 for at in Attrs[1].keys():
170 if AttrInfo.has_key(at):
171 if AttrInfo[at][1] == 0:
172 print " %-18s:" % (AttrInfo[at][0]),
173 for x in Attrs[1][at]:
176 print "(id=%s, gid=%s)" % (GetAttr(Attrs,"uidNumber","-1"),GetAttr(Attrs,"gidNumber","-1")),
179 OrderedIndex[AttrInfo[at][1]][1] = Attrs[1][at];
181 Keys = OrderedIndex.keys();
184 if at < 100 or RootMode != 0:
185 print " %3u) %-18s: " % (at,OrderedIndex[at][0]),
186 for x in OrderedIndex[at][1]:
187 print "'%s'" % (re.sub('[\n\r]','?',x)),
190 # Change a single attribute
191 def ChangeAttr(Attrs,Attr):
192 if (Attr == "supplementaryGid" or Attr == "allowedHost" or \
193 Attr == "member" or Attr == "dnsZoneEntry" or Attr == "mailWhitelist" or \
194 Attr == "mailRBL" or Attr == "mailRHSBL"):
195 return MultiChangeAttr(Attrs,Attr);
197 print "Old value: '%s'" % (GetAttr(Attrs,Attr,""));
198 print "Press enter to leave unchanged and a single space to set to empty";
199 NewValue = raw_input("New? ");
203 print "Leaving unchanged.";
206 # Single space designates delete, trap the delete error
207 if (NewValue == " "):
210 l.modify_s(UserDn,[(ldap.MOD_DELETE,Attr,None)]);
211 except ldap.NO_SUCH_ATTRIBUTE:
215 Attrs[1][Attr] = [""];
220 l.modify_s(UserDn,[(ldap.MOD_REPLACE,Attr,NewValue)]);
221 Attrs[1][Attr] = [NewValue];
224 def MultiChangeAttr(Attrs,Attr):
225 # Make sure that we have an entry
226 if not Attrs[1].has_key(Attr):
229 Attrs[1][Attr].sort();
230 print "Old values: ",Attrs[1][Attr];
232 Mode = string.upper(raw_input("[D]elete or [A]dd? "));
233 if (Mode != 'D' and Mode != 'A'):
236 NewValue = raw_input("Value? ");
239 print "Leaving unchanged.";
246 l.modify_s(UserDn,[(ldap.MOD_DELETE,Attr,NewValue)]);
247 except ldap.NO_SUCH_ATTRIBUTE:
251 Attrs[1][Attr].remove(NewValue);
256 l.modify_s(UserDn,[(ldap.MOD_ADD,Attr,NewValue)]);
257 Attrs[1][Attr].append(NewValue);
260 # Main program starts here
261 User = pwd.getpwuid(os.getuid())[0];
265 (options, arguments) = getopt.getopt(sys.argv[1:], "nu:c:a:r")
266 except getopt.GetoptError, data:
270 for (switch, val) in options:
273 elif (switch == '-a'):
275 elif (switch == '-c'):
278 elif (switch == '-r'):
280 elif (switch == '-n'):
284 print "Accessing LDAP entry for '" + User + "'",
285 if (BindUser != User):
287 print "as '" + BindUser + "'";
291 Password = getpass(BindUser + "'s password: ");
293 # Connect to the ldap server
294 l = ldap.open(LDAPServer);
295 UserDn = "uid=" + BindUser + "," + BaseDn;
297 l.simple_bind_s(UserDn,Password);
299 l.simple_bind_s("","");
300 UserDn = "uid=" + User + "," + BaseDn;
302 # Enable changing of supplementary gid's
304 # Items that root can edit
305 list = ["supplementaryGid","allowedHost","member"];
308 AttrInfo[x][1] = 200 + Count;
309 OrderedIndex[AttrInfo[x][1]] = [AttrInfo[x][0], "",x];
310 OrigOrderedIndex[AttrInfo[x][1]] = [AttrInfo[x][0], "",x];
313 # Query the server for all of the attributes
314 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid=" + User);
316 print "User",User,"was not found.";
319 # repeatedly show the account configuration
326 print " a) Arbitary Change";
327 print " R) Randomize Password";
328 print " p) Change Password";
329 print " u) Switch Users";
333 Response = raw_input("Change? ");
334 if (Response == "x" or Response == "X" or Response == "q" or
335 Response == "quit" or Response == "exit"):
338 # Change who we are looking at
339 if (Response == 'u' or Response == 'U'):
340 NewUser = raw_input("User? ");
343 NAttrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid=" + NewUser);
345 print "User",NewUser,"was not found.";
349 UserDn = "uid=" + User + "," + BaseDn;
350 OrderedIndex = copy.deepcopy(OrigOrderedIndex);
353 # Handle changing the password
354 if (Response == "p"):
355 print "Please enter a new password. Your password can be of unlimited length,";
356 print "contain spaces and other special characters. No checking is done on the";
357 print "strength of the passwords so pick good ones please!";
359 Pass1 = getpass(User + "'s new password: ");
360 Pass2 = getpass(User + "'s new password again: ");
362 print "Passwords did not match";
363 raw_input("Press a key");
367 Pass = HashPass(Pass1);
369 print "%s: %s\n" %(sys.exc_type,sys.exc_value);
370 raw_input("Press a key");
373 print "Setting password..";
374 Pass = "{crypt}" + Pass;
375 l.modify_s(UserDn,[(ldap.MOD_REPLACE,"userPassword",Pass)]);
376 Attrs[0][1]["userPassword"] = [Pass];
380 if Response == 'R' and RootMode == 1:
381 Resp = raw_input("Randomize Users Password? [no/yes]");
385 # Generate a random password
387 Password = GenPass();
388 Pass = HashPass(Password);
390 print "%s: %s\n" %(sys.exc_type,sys.exc_value);
391 raw_input("Press a key");
394 print "Setting password..";
395 Pass = "{crypt}" + Pass;
396 l.modify_s(UserDn,[(ldap.MOD_REPLACE,"userPassword",Pass)]);
397 Attrs[0][1]["userPassword"] = [Pass];
400 # Handle changing an arbitary value
401 if (Response == "a"):
402 Attr = raw_input("Attr? ");
403 ChangeAttr(Attrs[0],Attr);
406 # Convert the integer response
409 if (not OrderedIndex.has_key(ID) or (ID > 100 and RootMode == 0)):
415 # Print the what to do prompt
416 print "Changing LDAP entry '%s' (%s)" % (OrderedIndex[ID][0],OrderedIndex[ID][2]);
417 print AttrPrompt[OrderedIndex[ID][2]][0];
418 ChangeAttr(Attrs[0],OrderedIndex[ID][2]);