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 # Copyright (c) 1999-2001 Jason Gunthorpe <jgg@debian.org>
21 # Copyright (c) 2004-2005,7 Joey Schulze <joey@infodrom.org>
22 # Copyright (c) 2001-2006 Ryan Murray <rmurray@debian.org>
23 # Copyright (c) 2008 Peter Palfrader <peter@palfrader.org>
24 # Copyright (c) 2008 Martin Zobel-Helas <zobel@debian.org>
25 # Copyright (c) 2008 Marc 'HE' Brockschmidt <he@debian.org>
26 # Copyright (c) 2008 Mark Hymers <mhy@debian.org>
28 # This program is free software; you can redistribute it and/or modify
29 # it under the terms of the GNU General Public License as published by
30 # the Free Software Foundation; either version 2 of the License, or
31 # (at your option) any later version.
33 # This program is distributed in the hope that it will be useful,
34 # but WITHOUT ANY WARRANTY; without even the implied warranty of
35 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
36 # GNU General Public License for more details.
38 # You should have received a copy of the GNU General Public License
39 # along with this program; if not, write to the Free Software
40 # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
42 import time, os, pwd, sys, getopt, ldap, crypt, readline, copy;
43 from userdir_ldap import *;
46 AttrInfo = {"cn": ["First Name", 101],
47 "mn": ["Middle Name", 102],
48 "sn": ["Surname", 103],
49 "c": ["Country Code",1],
51 "ou": ["Membership",0],
52 "facsimileTelephoneNumber": ["Fax Phone Number",3],
53 "telephoneNumber": ["Phone Number",4],
54 "postalAddress": ["Mailing Address",5],
55 "postalCode": ["Postal Code",6],
56 "uid": ["Unix User ID",0],
57 "loginShell": ["Unix Shell",7],
58 "supplementaryGid": ["Unix Groups",0],
59 "allowedHost": ["Host ACL",0],
60 "member": ["LDAP Group",0],
61 "emailForward": ["Email Forwarding",8],
62 "ircNick": ["IRC Nickname",9],
63 "onVacation": ["Vacation Message",10],
64 "labeledURI": ["Home Page",11],
65 "latitude": ["Latitude",12],
66 "longitude": ["Longitude",13],
67 "icqUin": ["ICQ UIN",14],
68 "jabberJID": ["Jabber ID",15],
69 "privateSub": ["Debian-Private",16],
70 "gender": ["Gender",17],
71 "birthDate": ["Date of Birth",18],
72 "mailDisableMessage": ["Mail Disabled",19],
73 "mailGreylisting": ["Mail Greylisting",20],
74 "mailCallout": ["Mail Callouts",21],
75 "mailRBL": ["Mail RBLs",22],
76 "mailRHSBL": ["Mail RHSBLs",23],
77 "mailWhitelist": ["Mail Whitelist",24],
78 "comment": ["Comment",116],
79 "userPassword": ["Crypted Password",117],
80 "dnsZoneEntry": ["d.net Entry",118],
81 "VoIP": ["VoIP Address",119]};
83 AttrPrompt = {"cn": ["Common name or first name"],
84 "mn": ["Middle name (or initial if it ends in a dot)"],
85 "sn": ["Surname or last name"],
86 "c": ["ISO 2 letter country code, such as US, DE, etc"],
87 "l": ["City name, State/Provice (Locality)\n e.g. Dallas, Texas"],
88 "facsimileTelephoneNumber": ["Fax phone number, with area code and country code"],
89 "telephoneNumber": ["Voice phone number"],
90 "postalAddress": ["Complete mailing address including postal codes and country designations\nSeperate lines using a $ character"],
91 "postalCode": ["Postal Code or Zip Code"],
92 "loginShell": ["Login shell with full path (no check is done for validity)"],
93 "emailForward": ["EMail address to send all mail to or blank to disable"],
94 "ircNick": ["IRC nickname if you use IRC"],
95 "onVacation": ["A message if on vaction, indicating the time of departure and return"],
96 "userPassword": ["The users Crypt'd password"],
97 "comment": ["Admin Comment about the account"],
98 "supplementaryGid": ["Groups the user is in"],
99 "allowedHost": ["Grant access to certain hosts"],
100 "privateSub": ["Debian-Private mailing list subscription"],
101 "gender": ["ISO5218 Gender code (1=male,2=female,9=unspecified)"],
102 "birthDate": ["Date of Birth (YYYYMMDD)"],
103 "mailDisableMessage": ["Error message to return via SMTP"],
104 "mailGreylisting": ["SMTP Greylisting (TRUE/FALSE)"],
105 "mailCallout": ["SMTP Callouts (TRUE/FALSE)"],
106 "mailRBL": ["SMTP time RBL lists"],
107 "mailRHSBL": ["SMTP time RHSBL lists"],
108 "mailWhitelist": ["SMTP time whitelist from other checks"],
109 "member": ["LDAP Group Member for slapd ACLs"],
110 "latitude": ["XEarth latitude in ISO 6709 format - see /usr/share/zoneinfo/zone.tab or etak.com"],
111 "longitude": ["XEarth latitude in ISO 6709 format - see /usr/share/zoneinfo/zone.tab or etak.com"],
112 "dnsZoneEntry": ["DNS Zone fragment associated this this user"],
113 "labeledURI": ["Web home page"],
114 "jabberJID": ["Jabber ID"],
115 "icqUin": ["ICQ UIN Number"],
116 "VoIP": ["VoIP Address"]};
118 # Create a map of IDs to desc,value,attr
120 for at in AttrInfo.keys():
121 if (AttrInfo[at][1] != 0):
122 OrderedIndex[AttrInfo[at][1]] = [AttrInfo[at][0], "", at];
123 OrigOrderedIndex = copy.deepcopy(OrderedIndex);
125 # Show shadow information
126 def PrintShadow(Attrs):
127 Changed = int(GetAttr(Attrs,"shadowLastChange","0"));
128 MinDays = int(GetAttr(Attrs,"shadowMin","0"));
129 MaxDays = int(GetAttr(Attrs,"shadowMax","0"));
130 WarnDays = int(GetAttr(Attrs,"shadowWarning","0"));
131 InactDays = int(GetAttr(Attrs,"shadowInactive","0"));
132 Expire = int(GetAttr(Attrs,"shadowExpire","0"));
134 print "%-24s:" % ("Password last changed"),
135 print time.strftime("%a %d/%m/%Y %Z",time.localtime(Changed*24*60*60));
137 print "%-24s:" % ("Account expires on"),
138 print time.strftime("%a %d/%m/%Y %Z",time.localtime(Expire*24*60*60));
139 if (InactDays >= 0 and MaxDays < 99999):
140 print "Account aging is active, you must change your password every", MaxDays, "days."
142 # Print out the automatic time stamp information
143 def PrintModTime(Attrs):
144 Stamp = GetAttr(Attrs,"modifyTimestamp","");
146 Time = (int(Stamp[0:4]),int(Stamp[4:6]),int(Stamp[6:8]),
147 int(Stamp[8:10]),int(Stamp[10:12]),int(Stamp[12:14]),0,0,-1);
148 print "%-24s:" % ("Record last modified on"), time.strftime("%a %d/%m/%Y %X UTC",Time),
149 print "by",ldap.explode_dn(GetAttr(Attrs,"modifiersName"),1)[0];
151 Stamp = GetAttr(Attrs,"createTimestamp","");
153 Time = (int(Stamp[0:4]),int(Stamp[4:6]),int(Stamp[6:8]),
154 int(Stamp[8:10]),int(Stamp[10:12]),int(Stamp[12:14]),0,0,-1);
155 print "%-24s:" % ("Record created on"), time.strftime("%a %d/%m/%Y %X UTC",Time);
157 # Print the PGP key for a user
158 def PrintKeys(Attrs):
159 if Attrs[1].has_key("keyFingerPrint") == 0:
162 for x in Attrs[1]["keyFingerPrint"]:
164 print "%-24s:" % ("PGP/GPG Key Fingerprints"),
167 print "%-24s:" % (""),
168 print FormatPGPKey(x);
170 # Print the SSH RSA Authentication keys for a user
171 def PrintSshRSAKeys(Attrs):
172 if Attrs[1].has_key("sshRSAAuthKey") == 0:
175 for x in Attrs[1]["sshRSAAuthKey"]:
177 print "%-24s:" % ("SSH Auth Keys"),
180 print "%-24s:" % (""),
182 print FormatSSHAuth(x);
184 # Display all of the attributes in a numbered list
185 def ShowAttrs(Attrs):
187 print EmailAddress(Attrs);
191 PrintSshRSAKeys(Attrs);
193 for at in Attrs[1].keys():
194 if AttrInfo.has_key(at):
195 if AttrInfo[at][1] == 0:
196 print " %-18s:" % (AttrInfo[at][0]),
197 for x in Attrs[1][at]:
200 print "(id=%s, gid=%s)" % (GetAttr(Attrs,"uidNumber","-1"),GetAttr(Attrs,"gidNumber","-1")),
203 OrderedIndex[AttrInfo[at][1]][1] = Attrs[1][at];
205 Keys = OrderedIndex.keys();
208 if at < 100 or RootMode != 0:
209 print " %3u) %-18s: " % (at,OrderedIndex[at][0]),
210 for x in OrderedIndex[at][1]:
211 print "'%s'" % (re.sub('[\n\r]','?',x)),
214 # Change a single attribute
215 def ChangeAttr(Attrs,Attr):
216 if (Attr == "supplementaryGid" or Attr == "allowedHost" or \
217 Attr == "member" or Attr == "dnsZoneEntry" or Attr == "mailWhitelist" or \
218 Attr == "mailRBL" or Attr == "mailRHSBL"):
219 return MultiChangeAttr(Attrs,Attr);
221 print "Old value: '%s'" % (GetAttr(Attrs,Attr,""));
222 print "Press enter to leave unchanged and a single space to set to empty";
223 NewValue = raw_input("New? ");
227 print "Leaving unchanged.";
230 # Single space designates delete, trap the delete error
231 if (NewValue == " "):
234 l.modify_s(UserDn,[(ldap.MOD_DELETE,Attr,None)]);
235 except ldap.NO_SUCH_ATTRIBUTE:
239 Attrs[1][Attr] = [""];
244 l.modify_s(UserDn,[(ldap.MOD_REPLACE,Attr,NewValue)]);
245 Attrs[1][Attr] = [NewValue];
248 def MultiChangeAttr(Attrs,Attr):
249 # Make sure that we have an entry
250 if not Attrs[1].has_key(Attr):
253 Attrs[1][Attr].sort();
254 print "Old values: ",Attrs[1][Attr];
256 Mode = raw_input("[D]elete or [A]dd? ").upper()
257 if (Mode != 'D' and Mode != 'A'):
260 NewValue = raw_input("Value? ");
263 print "Leaving unchanged.";
270 l.modify_s(UserDn,[(ldap.MOD_DELETE,Attr,NewValue)]);
271 except ldap.NO_SUCH_ATTRIBUTE:
275 Attrs[1][Attr].remove(NewValue);
280 l.modify_s(UserDn,[(ldap.MOD_ADD,Attr,NewValue)]);
281 Attrs[1][Attr].append(NewValue);
284 # Main program starts here
285 User = pwd.getpwuid(os.getuid())[0];
289 (options, arguments) = getopt.getopt(sys.argv[1:], "nu:c:a:r")
290 except getopt.GetoptError, data:
294 for (switch, val) in options:
297 elif (switch == '-a'):
299 elif (switch == '-c'):
302 elif (switch == '-r'):
304 elif (switch == '-n'):
308 print "Accessing LDAP entry for '" + User + "'",
309 if (BindUser != User):
311 print "as '" + BindUser + "'";
315 Password = getpass(BindUser + "'s password: ");
317 # Connect to the ldap server
319 UserDn = "uid=" + BindUser + "," + BaseDn;
321 l.simple_bind_s(UserDn,Password);
323 l.simple_bind_s("","");
324 UserDn = "uid=" + User + "," + BaseDn;
326 # Enable changing of supplementary gid's
328 # Items that root can edit
329 list = ["supplementaryGid","allowedHost","member"];
332 AttrInfo[x][1] = 200 + Count;
333 OrderedIndex[AttrInfo[x][1]] = [AttrInfo[x][0], "",x];
334 OrigOrderedIndex[AttrInfo[x][1]] = [AttrInfo[x][0], "",x];
337 # Query the server for all of the attributes
338 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid=" + User);
340 print "User",User,"was not found.";
343 # repeatedly show the account configuration
350 print " a) Arbitary Change";
351 print " R) Randomize Password";
352 print " p) Change Password";
353 print " L) Lock account";
354 print " u) Switch Users";
358 Response = raw_input("Change? ");
359 if (Response == "x" or Response == "X" or Response == "q" or
360 Response == "quit" or Response == "exit"):
363 # Change who we are looking at
364 if (Response == 'u' or Response == 'U'):
365 NewUser = raw_input("User? ");
368 NAttrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid=" + NewUser);
370 print "User",NewUser,"was not found.";
374 UserDn = "uid=" + User + "," + BaseDn;
375 OrderedIndex = copy.deepcopy(OrigOrderedIndex);
378 # Handle changing the password
379 if (Response == "p"):
380 print "Please enter a new password. Your password can be of unlimited length,";
381 print "contain spaces and other special characters. No checking is done on the";
382 print "strength of the passwords so pick good ones please!";
384 Pass1 = getpass(User + "'s new password: ");
385 Pass2 = getpass(User + "'s new password again: ");
387 print "Passwords did not match";
388 raw_input("Press a key");
392 Pass = HashPass(Pass1);
394 print "%s: %s\n" %(sys.exc_type,sys.exc_value);
395 raw_input("Press a key");
398 print "Setting password..";
399 Pass = "{crypt}" + Pass;
400 shadowLast = str(int(time.time()/24/60/60));
401 l.modify_s(UserDn,[(ldap.MOD_REPLACE,"userPassword",Pass),
402 (ldap.MOD_REPLACE,"shadowLastChange",shadowLast)]);
403 Attrs[0][1]["userPassword"] = [Pass];
404 Attrs[0][1]["shadowLastChange"] = [shadowLast];
408 if Response == 'R' and RootMode == 1:
409 Resp = raw_input("Randomize Users Password? [no/yes]");
413 # Generate a random password
415 Password = GenPass();
416 Pass = HashPass(Password);
418 print "%s: %s\n" %(sys.exc_type,sys.exc_value);
419 raw_input("Press a key");
422 print "Setting password..";
423 Pass = "{crypt}" + Pass;
424 shadowLast = str(int(time.time()/24/60/60));
425 l.modify_s(UserDn,[(ldap.MOD_REPLACE,"userPassword",Pass),
426 (ldap.MOD_REPLACE,"shadowLastChange",shadowLast)]);
427 Attrs[0][1]["userPassword"] = [Pass];
428 Attrs[0][1]["shadowLastChange"] = [shadowLast];
432 if Response == 'L' and RootMode == 1:
433 Resp = raw_input("Really lock account? [no/yes]");
437 print "Setting password..";
438 shadowLast = str(int(time.time()/24/60/60));
440 (ldap.MOD_REPLACE,"userPassword","{crypt}*LK*"),
441 (ldap.MOD_REPLACE,"mailDisableMessage","account locked"),
442 (ldap.MOD_REPLACE,"shadowLastChange",shadowLast),
443 (ldap.MOD_REPLACE,"shadowExpire","1")]);
444 Attrs[0][1]["userPassword"] = ["{crypt}*LK*"];
445 Attrs[0][1]["mailDisableMessage"] = ["account locked"];
446 Attrs[0][1]["shadowLastChange"] = [shadowLast];
447 Attrs[0][1]["shadowExpire"] = ["1"];
450 # Handle changing an arbitary value
451 if (Response == "a"):
452 Attr = raw_input("Attr? ");
453 ChangeAttr(Attrs[0],Attr);
456 # Convert the integer response
459 if (not OrderedIndex.has_key(ID) or (ID > 100 and RootMode == 0)):
465 # Print the what to do prompt
466 print "Changing LDAP entry '%s' (%s)" % (OrderedIndex[ID][0],OrderedIndex[ID][2]);
467 print AttrPrompt[OrderedIndex[ID][2]][0];
468 ChangeAttr(Attrs[0],OrderedIndex[ID][2]);