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,8 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>
27 # Copyright (c) 2008 Thomas Viehmann <tv@beamnet.de>
29 # This program is free software; you can redistribute it and/or modify
30 # it under the terms of the GNU General Public License as published by
31 # the Free Software Foundation; either version 2 of the License, or
32 # (at your option) any later version.
34 # This program is distributed in the hope that it will be useful,
35 # but WITHOUT ANY WARRANTY; without even the implied warranty of
36 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
37 # GNU General Public License for more details.
39 # You should have received a copy of the GNU General Public License
40 # along with this program; if not, write to the Free Software
41 # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
43 import time, os, pwd, sys, getopt, ldap, crypt, readline, copy, getpass
44 from userdir_ldap import *;
47 AttrInfo = {"cn": ["First Name", 101],
48 "mn": ["Middle Name", 102],
49 "sn": ["Surname", 103],
50 "c": ["Country Code",1],
52 "ou": ["Membership",0],
53 "facsimileTelephoneNumber": ["Fax Phone Number",3],
54 "telephoneNumber": ["Phone Number",4],
55 "postalAddress": ["Mailing Address",5],
56 "postalCode": ["Postal Code",6],
57 "uid": ["Unix User ID",0],
58 "loginShell": ["Unix Shell",7],
59 "supplementaryGid": ["Unix Groups",0],
60 "allowedHost": ["Host ACL",0],
61 "member": ["LDAP Group",0],
62 "emailForward": ["Email Forwarding",8],
63 "ircNick": ["IRC Nickname",9],
64 "onVacation": ["Vacation Message",10],
65 "labeledURI": ["Home Page",11],
66 "latitude": ["Latitude",12],
67 "longitude": ["Longitude",13],
68 "icqUin": ["ICQ UIN",14],
69 "jabberJID": ["Jabber ID",15],
70 "privateSub": ["Debian-Private",16],
71 "gender": ["Gender",17],
72 "birthDate": ["Date of Birth",18],
73 "mailDisableMessage": ["Mail Disabled",19],
74 "mailGreylisting": ["Mail Greylisting",20],
75 "mailCallout": ["Mail Callouts",21],
76 "mailRBL": ["Mail RBLs",22],
77 "mailRHSBL": ["Mail RHSBLs",23],
78 "mailWhitelist": ["Mail Whitelist",24],
79 "mailContentInspectionAction": ["mail C-I Action",25],
80 "VoIP": ["VoIP Address",26],
81 "comment": ["Comment",116],
82 "userPassword": ["Crypted Password",117],
83 "dnsZoneEntry": ["d.net Entry",118],
84 "accountStatus": ["DD status",301],
85 "accountComment": ["DD status comment",302],
88 AttrPrompt = {"cn": ["Common name or first name"],
89 "mn": ["Middle name (or initial if it ends in a dot)"],
90 "sn": ["Surname or last name"],
91 "c": ["ISO 2 letter country code, such as US, DE, etc"],
92 "l": ["City name, State/Provice (Locality)\n e.g. Dallas, Texas"],
93 "facsimileTelephoneNumber": ["Fax phone number, with area code and country code"],
94 "telephoneNumber": ["Voice phone number"],
95 "postalAddress": ["Complete mailing address including postal codes and country designations\nSeperate lines using a $ character"],
96 "postalCode": ["Postal Code or Zip Code"],
97 "loginShell": ["Login shell with full path (no check is done for validity)"],
98 "emailForward": ["EMail address to send all mail to or blank to disable"],
99 "ircNick": ["IRC nickname if you use IRC"],
100 "onVacation": ["A message if on vaction, indicating the time of departure and return"],
101 "userPassword": ["The users Crypt'd password"],
102 "comment": ["Admin Comment about the account"],
103 "supplementaryGid": ["Groups the user is in"],
104 "allowedHost": ["Grant access to certain hosts"],
105 "privateSub": ["Debian-Private mailing list subscription"],
106 "gender": ["ISO5218 Gender code (1=male,2=female,9=unspecified)"],
107 "birthDate": ["Date of Birth (YYYYMMDD)"],
108 "mailDisableMessage": ["Error message to return via SMTP"],
109 "mailGreylisting": ["SMTP Greylisting (TRUE/FALSE)"],
110 "mailCallout": ["SMTP Callouts (TRUE/FALSE)"],
111 "mailRBL": ["SMTP time RBL lists"],
112 "mailRHSBL": ["SMTP time RHSBL lists"],
113 "mailWhitelist": ["SMTP time whitelist from other checks"],
114 "mailContentInspectionAction": ["Content Inspection Action (reject, blackhole, markup)"],
115 "member": ["LDAP Group Member for slapd ACLs"],
116 "latitude": ["XEarth latitude in ISO 6709 format - see /usr/share/zoneinfo/zone.tab or etak.com"],
117 "longitude": ["XEarth latitude in ISO 6709 format - see /usr/share/zoneinfo/zone.tab or etak.com"],
118 "dnsZoneEntry": ["DNS Zone fragment associated this this user"],
119 "labeledURI": ["Web home page"],
120 "jabberJID": ["Jabber ID"],
121 "icqUin": ["ICQ UIN Number"],
122 "VoIP": ["VoIP Address"],
123 "accountStatus": ["DD status"],
124 "accountComment": ["DD status comment"],
127 # Create a map of IDs to desc,value,attr
129 for at in AttrInfo.keys():
130 if (AttrInfo[at][1] != 0):
131 OrderedIndex[AttrInfo[at][1]] = [AttrInfo[at][0], "", at];
132 OrigOrderedIndex = copy.deepcopy(OrderedIndex);
134 for id in OrderedIndex:
135 if not AttrPrompt.has_key( OrderedIndex[id][2] ):
136 print "Warning: no AttrPrompt for %s"%(id)
138 # Show shadow information
139 def PrintShadow(Attrs):
140 Changed = int(GetAttr(Attrs,"shadowLastChange","0"));
141 MinDays = int(GetAttr(Attrs,"shadowMin","0"));
142 MaxDays = int(GetAttr(Attrs,"shadowMax","0"));
143 WarnDays = int(GetAttr(Attrs,"shadowWarning","0"));
144 InactDays = int(GetAttr(Attrs,"shadowInactive","0"));
145 Expire = int(GetAttr(Attrs,"shadowExpire","0"));
147 print "%-24s:" % ("Password last changed"),
148 print time.strftime("%a %d/%m/%Y %Z",time.localtime(Changed*24*60*60));
150 print "%-24s:" % ("Account expires on"),
151 print time.strftime("%a %d/%m/%Y %Z",time.localtime(Expire*24*60*60));
152 if (InactDays >= 0 and MaxDays < 99999):
153 print "Account aging is active, you must change your password every", MaxDays, "days."
155 # Print out the automatic time stamp information
156 def PrintModTime(Attrs):
157 Stamp = GetAttr(Attrs,"modifyTimestamp","");
159 Time = (int(Stamp[0:4]),int(Stamp[4:6]),int(Stamp[6:8]),
160 int(Stamp[8:10]),int(Stamp[10:12]),int(Stamp[12:14]),0,0,-1);
161 print "%-24s:" % ("Record last modified on"), time.strftime("%a %d/%m/%Y %X UTC",Time),
162 print "by",ldap.explode_dn(GetAttr(Attrs,"modifiersName"),1)[0];
164 Stamp = GetAttr(Attrs,"createTimestamp","");
166 Time = (int(Stamp[0:4]),int(Stamp[4:6]),int(Stamp[6:8]),
167 int(Stamp[8:10]),int(Stamp[10:12]),int(Stamp[12:14]),0,0,-1);
168 print "%-24s:" % ("Record created on"), time.strftime("%a %d/%m/%Y %X UTC",Time);
170 # Print the PGP key for a user
171 def PrintKeys(Attrs):
172 if Attrs[1].has_key("keyFingerPrint") == 0:
175 for x in Attrs[1]["keyFingerPrint"]:
177 print "%-24s:" % ("PGP/GPG Key Fingerprints"),
180 print "%-24s:" % (""),
181 print FormatPGPKey(x);
183 # Print the SSH RSA Authentication keys for a user
184 def PrintSshRSAKeys(Attrs):
185 if Attrs[1].has_key("sshRSAAuthKey") == 0:
188 for x in Attrs[1]["sshRSAAuthKey"]:
190 print "%-24s:" % ("SSH Auth Keys"),
193 print "%-24s:" % (""),
195 print FormatSSHAuth(x);
197 # Display all of the attributes in a numbered list
198 def ShowAttrs(Attrs):
200 print EmailAddress(Attrs);
204 PrintSshRSAKeys(Attrs);
206 for at in Attrs[1].keys():
207 if AttrInfo.has_key(at):
208 if AttrInfo[at][1] == 0:
209 print " %-18s:" % (AttrInfo[at][0]),
210 for x in Attrs[1][at]:
213 print "(id=%s, gid=%s)" % (GetAttr(Attrs,"uidNumber","-1"),GetAttr(Attrs,"gidNumber","-1")),
216 OrderedIndex[AttrInfo[at][1]][1] = Attrs[1][at];
218 Keys = OrderedIndex.keys();
221 if at < 100 or RootMode != 0:
222 print " %3u) %-19s: " % (at,OrderedIndex[at][0]),
223 for x in OrderedIndex[at][1]:
224 print "'%s'" % (re.sub('[\n\r]','?',x)),
227 # Change a single attribute
228 def ChangeAttr(Attrs,Attr):
229 if (Attr == "supplementaryGid" or Attr == "allowedHost" or \
230 Attr == "member" or Attr == "dnsZoneEntry" or Attr == "mailWhitelist" or \
231 Attr == "mailRBL" or Attr == "mailRHSBL"):
232 return MultiChangeAttr(Attrs,Attr);
234 print "Old value: '%s'" % (GetAttr(Attrs,Attr,""));
235 print "Press enter to leave unchanged and a single space to set to empty";
236 NewValue = raw_input("New? ");
240 print "Leaving unchanged.";
243 # Single space designates delete, trap the delete error
244 if (NewValue == " "):
247 l.modify_s(UserDn,[(ldap.MOD_DELETE,Attr,None)]);
248 except ldap.NO_SUCH_ATTRIBUTE:
252 Attrs[1][Attr] = [""];
255 if (Attr == "mailGreylisting" or Attr == "mailCallout"):
256 if (NewValue.lower() != "true" and NewValue.lower() != "false"):
257 if (NewValue == "1"): NewValue = "true"
259 if (NewValue == "0"): NewValue = "false"
261 print "Need a boolean value"
263 NewValue = NewValue.upper()
267 l.modify_s(UserDn,[(ldap.MOD_REPLACE,Attr,NewValue)]);
268 Attrs[1][Attr] = [NewValue];
271 def MultiChangeAttr(Attrs,Attr):
272 # Make sure that we have an entry
273 if not Attrs[1].has_key(Attr):
276 Attrs[1][Attr].sort();
277 print "Old values: ",Attrs[1][Attr];
279 Mode = raw_input("[D]elete or [A]dd? ").upper()
280 if (Mode != 'D' and Mode != 'A'):
283 NewValue = raw_input("Value? ");
286 print "Leaving unchanged.";
293 l.modify_s(UserDn,[(ldap.MOD_DELETE,Attr,NewValue)]);
294 except ldap.NO_SUCH_ATTRIBUTE:
298 Attrs[1][Attr].remove(NewValue);
303 l.modify_s(UserDn,[(ldap.MOD_ADD,Attr,NewValue)]);
304 Attrs[1][Attr].append(NewValue);
307 def Lock(UserDn, Attrs, DisableMail=True):
308 shadowLast = str(int(time.time()/24/60/60));
310 (ldap.MOD_REPLACE,"userPassword","{crypt}*LK*"),
311 (ldap.MOD_REPLACE,"shadowLastChange",shadowLast),
312 (ldap.MOD_REPLACE,"shadowExpire","1")];
314 recs.append( (ldap.MOD_REPLACE,"mailDisableMessage","account locked") )
315 Attrs[0][1]["mailDisableMessage"] = ["account locked"];
316 l.modify_s(UserDn,recs);
317 Attrs[0][1]["userPassword"] = ["{crypt}*LK*"];
318 Attrs[0][1]["shadowLastChange"] = [shadowLast];
319 Attrs[0][1]["shadowExpire"] = ["1"];
321 # Main program starts here
322 User = pwd.getpwuid(os.getuid())[0];
326 (options, arguments) = getopt.getopt(sys.argv[1:], "nu:c:a:r")
327 except getopt.GetoptError, data:
331 for (switch, val) in options:
334 elif (switch == '-a'):
336 elif (switch == '-c'):
339 elif (switch == '-r'):
341 elif (switch == '-n'):
345 print "Accessing LDAP entry for '" + User + "'",
346 if (BindUser != User):
348 print "as '" + BindUser + "'";
352 # Connect to the ldap server
354 UserDn = "uid=" + User + "," + BaseDn
356 Password = getpass.getpass(BindUser + "'s password: ")
357 BindUserDn = "uid=" + BindUser + "," + BaseDn
362 l.simple_bind_s(BindUserDn,Password)
363 except ldap.LDAPError,e:
364 print >> sys.stderr, "LDAP error:", e.args[0]['desc']
365 print >> sys.stderr, " ", e.args[0]['info']
368 # Enable changing of supplementary gid's
370 # Items that root can edit
371 list = ["supplementaryGid","allowedHost","member"];
374 AttrInfo[x][1] = 200 + Count;
375 OrderedIndex[AttrInfo[x][1]] = [AttrInfo[x][0], "",x];
376 OrigOrderedIndex[AttrInfo[x][1]] = [AttrInfo[x][0], "",x];
379 # Query the server for all of the attributes
380 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid=" + User);
382 print "User",User,"was not found.";
385 # repeatedly show the account configuration
392 print " a) Arbitary Change";
393 print " r) retire developer";
394 print " R) Randomize Password";
395 print " L) Lock account and disable mail";
396 print " p) Change Password";
397 print " u) Switch Users";
401 Response = raw_input("Change? ");
402 if (Response == "x" or Response == "X" or Response == "q" or
403 Response == "quit" or Response == "exit"):
406 # Change who we are looking at
407 if (Response == 'u' or Response == 'U'):
408 NewUser = raw_input("User? ");
411 NAttrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid=" + NewUser);
413 print "User",NewUser,"was not found.";
417 UserDn = "uid=" + User + "," + BaseDn;
418 OrderedIndex = copy.deepcopy(OrigOrderedIndex);
421 # Handle changing the password
422 if (Response == "p"):
423 print "Please enter a new password. Your password can be of unlimited length,";
424 print "contain spaces and other special characters. No checking is done on the";
425 print "strength of the passwords so pick good ones please!";
427 Pass1 = getpass.getpass(User + "'s new password: ")
428 Pass2 = getpass.getpass(User + "'s new password again: ")
430 print "Passwords did not match";
431 raw_input("Press a key");
435 Pass = HashPass(Pass1);
437 print "%s: %s\n" %(sys.exc_type,sys.exc_value);
438 raw_input("Press a key");
441 print "Setting password..";
442 Pass = "{crypt}" + Pass;
443 shadowLast = str(int(time.time()/24/60/60));
444 l.modify_s(UserDn,[(ldap.MOD_REPLACE,"userPassword",Pass),
445 (ldap.MOD_REPLACE,"shadowLastChange",shadowLast)]);
446 Attrs[0][1]["userPassword"] = [Pass];
447 Attrs[0][1]["shadowLastChange"] = [shadowLast];
451 if Response == 'r' and RootMode == 1:
452 if Attrs[0][1].has_key("accountStatus") == 0:
453 curStatus = "<not set>"
455 curStatus = Attrs[0][1]["accountStatus"][0]
456 if Attrs[0][1].has_key("accountComment") == 0:
457 curComment = "<not set>"
459 curComment = Attrs[0][1]["accountComment"][0]
460 print "\n\nCurrent status is %s"%curStatus
461 print "Current comment is %s\n"%curComment
463 print "Set account to:"
464 print " 1) retiring (lock account but do not disable mail):"
465 print " 2) inactive (removed/emeritus/... - lock account and disable mail):"
466 print " 3) memorial (lock account and disable mail):"
467 print " 4) active (do not change other settings, you will have to deal with them)"
468 print " q) return (no change)"
469 Resp = raw_input("Action? ")
470 if Resp == "1" or Resp == "2":
471 Lock(UserDn, Attrs, Resp == "2")
473 newstatus = "retiring %s"%(time.strftime("%Y-%m-%d"))
475 newstatus = "inactive %s"%(time.strftime("%Y-%m-%d"))
476 l.modify_s(UserDn,[(ldap.MOD_REPLACE,"accountStatus",newstatus)])
477 Attrs[0][1]["accountStatus"] = [newstatus]
479 Resp2 = raw_input("Optional RT ticket number? ")
481 comment = "RT#%s"%(Resp2)
482 l.modify_s(UserDn,[(ldap.MOD_REPLACE,"accountComment",comment)])
483 Attrs[0][1]["accountComment"] = [comment]
486 newstatus = "memorial"
487 l.modify_s(UserDn,[(ldap.MOD_REPLACE,"accountStatus",newstatus)])
488 Attrs[0][1]["accountStatus"] = [newstatus]
491 l.modify_s(UserDn,[(ldap.MOD_REPLACE,"accountStatus",newstatus)])
492 Attrs[0][1]["accountStatus"] = [newstatus]
498 if Response == 'R' and RootMode == 1:
499 Resp = raw_input("Randomize Users Password? [no/yes]");
503 # Generate a random password
505 Password = GenPass();
506 Pass = HashPass(Password);
508 print "%s: %s\n" %(sys.exc_type,sys.exc_value);
509 raw_input("Press a key");
512 print "Setting password..";
513 Pass = "{crypt}" + Pass;
514 shadowLast = str(int(time.time()/24/60/60));
515 l.modify_s(UserDn,[(ldap.MOD_REPLACE,"userPassword",Pass),
516 (ldap.MOD_REPLACE,"shadowLastChange",shadowLast)]);
517 Attrs[0][1]["userPassword"] = [Pass];
518 Attrs[0][1]["shadowLastChange"] = [shadowLast];
522 if Response == 'L' and RootMode == 1:
523 Resp = raw_input("Really lock account? [no/yes]");
527 print "Setting password..";
531 # Handle changing an arbitary value
532 if (Response == "a"):
533 Attr = raw_input("Attr? ");
534 ChangeAttr(Attrs[0],Attr);
537 # Convert the integer response
540 if (not OrderedIndex.has_key(ID) or (ID > 100 and RootMode == 0)):
546 # Print the what to do prompt
547 print "Changing LDAP entry '%s' (%s)" % (OrderedIndex[ID][0],OrderedIndex[ID][2]);
548 print AttrPrompt[OrderedIndex[ID][2]][0];
549 ChangeAttr(Attrs[0],OrderedIndex[ID][2]);