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 "VoIP": ["VoIP Address",26],
80 "comment": ["Comment",116],
81 "userPassword": ["Crypted Password",117],
82 "dnsZoneEntry": ["d.net Entry",118],
83 "accountStatus": ["DD status",301],
84 "accountComment": ["DD status comment",302],
87 AttrPrompt = {"cn": ["Common name or first name"],
88 "mn": ["Middle name (or initial if it ends in a dot)"],
89 "sn": ["Surname or last name"],
90 "c": ["ISO 2 letter country code, such as US, DE, etc"],
91 "l": ["City name, State/Provice (Locality)\n e.g. Dallas, Texas"],
92 "facsimileTelephoneNumber": ["Fax phone number, with area code and country code"],
93 "telephoneNumber": ["Voice phone number"],
94 "postalAddress": ["Complete mailing address including postal codes and country designations\nSeperate lines using a $ character"],
95 "postalCode": ["Postal Code or Zip Code"],
96 "loginShell": ["Login shell with full path (no check is done for validity)"],
97 "emailForward": ["EMail address to send all mail to or blank to disable"],
98 "ircNick": ["IRC nickname if you use IRC"],
99 "onVacation": ["A message if on vaction, indicating the time of departure and return"],
100 "userPassword": ["The users Crypt'd password"],
101 "comment": ["Admin Comment about the account"],
102 "supplementaryGid": ["Groups the user is in"],
103 "allowedHost": ["Grant access to certain hosts"],
104 "privateSub": ["Debian-Private mailing list subscription"],
105 "gender": ["ISO5218 Gender code (1=male,2=female,9=unspecified)"],
106 "birthDate": ["Date of Birth (YYYYMMDD)"],
107 "mailDisableMessage": ["Error message to return via SMTP"],
108 "mailGreylisting": ["SMTP Greylisting (TRUE/FALSE)"],
109 "mailCallout": ["SMTP Callouts (TRUE/FALSE)"],
110 "mailRBL": ["SMTP time RBL lists"],
111 "mailRHSBL": ["SMTP time RHSBL lists"],
112 "mailWhitelist": ["SMTP time whitelist from other checks"],
113 "member": ["LDAP Group Member for slapd ACLs"],
114 "latitude": ["XEarth latitude in ISO 6709 format - see /usr/share/zoneinfo/zone.tab or etak.com"],
115 "longitude": ["XEarth latitude in ISO 6709 format - see /usr/share/zoneinfo/zone.tab or etak.com"],
116 "dnsZoneEntry": ["DNS Zone fragment associated this this user"],
117 "labeledURI": ["Web home page"],
118 "jabberJID": ["Jabber ID"],
119 "icqUin": ["ICQ UIN Number"],
120 "VoIP": ["VoIP Address"],
121 "accountStatus": ["DD status"],
122 "accountComment": ["DD status comment"],
125 # Create a map of IDs to desc,value,attr
127 for at in AttrInfo.keys():
128 if (AttrInfo[at][1] != 0):
129 OrderedIndex[AttrInfo[at][1]] = [AttrInfo[at][0], "", at];
130 OrigOrderedIndex = copy.deepcopy(OrderedIndex);
132 for id in OrderedIndex:
133 if not AttrPrompt.has_key( OrderedIndex[id][2] ):
134 print "Warning: no AttrPrompt for %s"%(id)
136 # Show shadow information
137 def PrintShadow(Attrs):
138 Changed = int(GetAttr(Attrs,"shadowLastChange","0"));
139 MinDays = int(GetAttr(Attrs,"shadowMin","0"));
140 MaxDays = int(GetAttr(Attrs,"shadowMax","0"));
141 WarnDays = int(GetAttr(Attrs,"shadowWarning","0"));
142 InactDays = int(GetAttr(Attrs,"shadowInactive","0"));
143 Expire = int(GetAttr(Attrs,"shadowExpire","0"));
145 print "%-24s:" % ("Password last changed"),
146 print time.strftime("%a %d/%m/%Y %Z",time.localtime(Changed*24*60*60));
148 print "%-24s:" % ("Account expires on"),
149 print time.strftime("%a %d/%m/%Y %Z",time.localtime(Expire*24*60*60));
150 if (InactDays >= 0 and MaxDays < 99999):
151 print "Account aging is active, you must change your password every", MaxDays, "days."
153 # Print out the automatic time stamp information
154 def PrintModTime(Attrs):
155 Stamp = GetAttr(Attrs,"modifyTimestamp","");
157 Time = (int(Stamp[0:4]),int(Stamp[4:6]),int(Stamp[6:8]),
158 int(Stamp[8:10]),int(Stamp[10:12]),int(Stamp[12:14]),0,0,-1);
159 print "%-24s:" % ("Record last modified on"), time.strftime("%a %d/%m/%Y %X UTC",Time),
160 print "by",ldap.explode_dn(GetAttr(Attrs,"modifiersName"),1)[0];
162 Stamp = GetAttr(Attrs,"createTimestamp","");
164 Time = (int(Stamp[0:4]),int(Stamp[4:6]),int(Stamp[6:8]),
165 int(Stamp[8:10]),int(Stamp[10:12]),int(Stamp[12:14]),0,0,-1);
166 print "%-24s:" % ("Record created on"), time.strftime("%a %d/%m/%Y %X UTC",Time);
168 # Print the PGP key for a user
169 def PrintKeys(Attrs):
170 if Attrs[1].has_key("keyFingerPrint") == 0:
173 for x in Attrs[1]["keyFingerPrint"]:
175 print "%-24s:" % ("PGP/GPG Key Fingerprints"),
178 print "%-24s:" % (""),
179 print FormatPGPKey(x);
181 # Print the SSH RSA Authentication keys for a user
182 def PrintSshRSAKeys(Attrs):
183 if Attrs[1].has_key("sshRSAAuthKey") == 0:
186 for x in Attrs[1]["sshRSAAuthKey"]:
188 print "%-24s:" % ("SSH Auth Keys"),
191 print "%-24s:" % (""),
193 print FormatSSHAuth(x);
195 # Display all of the attributes in a numbered list
196 def ShowAttrs(Attrs):
198 print EmailAddress(Attrs);
202 PrintSshRSAKeys(Attrs);
204 for at in Attrs[1].keys():
205 if AttrInfo.has_key(at):
206 if AttrInfo[at][1] == 0:
207 print " %-18s:" % (AttrInfo[at][0]),
208 for x in Attrs[1][at]:
211 print "(id=%s, gid=%s)" % (GetAttr(Attrs,"uidNumber","-1"),GetAttr(Attrs,"gidNumber","-1")),
214 OrderedIndex[AttrInfo[at][1]][1] = Attrs[1][at];
216 Keys = OrderedIndex.keys();
219 if at < 100 or RootMode != 0:
220 print " %3u) %-19s: " % (at,OrderedIndex[at][0]),
221 for x in OrderedIndex[at][1]:
222 print "'%s'" % (re.sub('[\n\r]','?',x)),
225 # Change a single attribute
226 def ChangeAttr(Attrs,Attr):
227 if (Attr == "supplementaryGid" or Attr == "allowedHost" or \
228 Attr == "member" or Attr == "dnsZoneEntry" or Attr == "mailWhitelist" or \
229 Attr == "mailRBL" or Attr == "mailRHSBL"):
230 return MultiChangeAttr(Attrs,Attr);
232 print "Old value: '%s'" % (GetAttr(Attrs,Attr,""));
233 print "Press enter to leave unchanged and a single space to set to empty";
234 NewValue = raw_input("New? ");
238 print "Leaving unchanged.";
241 # Single space designates delete, trap the delete error
242 if (NewValue == " "):
245 l.modify_s(UserDn,[(ldap.MOD_DELETE,Attr,None)]);
246 except ldap.NO_SUCH_ATTRIBUTE:
250 Attrs[1][Attr] = [""];
253 if (Attr == "mailGreylisting" or Attr == "mailCallout"):
254 if (NewValue.lower() != "true" and NewValue.lower() != "false"):
255 if (NewValue == "1"): NewValue = "true"
257 if (NewValue == "0"): NewValue = "false"
259 print "Need a boolean value"
261 NewValue = NewValue.upper()
265 l.modify_s(UserDn,[(ldap.MOD_REPLACE,Attr,NewValue)]);
266 Attrs[1][Attr] = [NewValue];
269 def MultiChangeAttr(Attrs,Attr):
270 # Make sure that we have an entry
271 if not Attrs[1].has_key(Attr):
274 Attrs[1][Attr].sort();
275 print "Old values: ",Attrs[1][Attr];
277 Mode = raw_input("[D]elete or [A]dd? ").upper()
278 if (Mode != 'D' and Mode != 'A'):
281 NewValue = raw_input("Value? ");
284 print "Leaving unchanged.";
291 l.modify_s(UserDn,[(ldap.MOD_DELETE,Attr,NewValue)]);
292 except ldap.NO_SUCH_ATTRIBUTE:
296 Attrs[1][Attr].remove(NewValue);
301 l.modify_s(UserDn,[(ldap.MOD_ADD,Attr,NewValue)]);
302 Attrs[1][Attr].append(NewValue);
305 def Lock(UserDn, Attrs, DisableMail=True):
306 shadowLast = str(int(time.time()/24/60/60));
308 (ldap.MOD_REPLACE,"userPassword","{crypt}*LK*"),
309 (ldap.MOD_REPLACE,"shadowLastChange",shadowLast),
310 (ldap.MOD_REPLACE,"shadowExpire","1")];
312 recs.append( (ldap.MOD_REPLACE,"mailDisableMessage","account locked") )
313 Attrs[0][1]["mailDisableMessage"] = ["account locked"];
314 l.modify_s(UserDn,recs);
315 Attrs[0][1]["userPassword"] = ["{crypt}*LK*"];
316 Attrs[0][1]["shadowLastChange"] = [shadowLast];
317 Attrs[0][1]["shadowExpire"] = ["1"];
319 # Main program starts here
320 User = pwd.getpwuid(os.getuid())[0];
324 (options, arguments) = getopt.getopt(sys.argv[1:], "nu:c:a:r")
325 except getopt.GetoptError, data:
329 for (switch, val) in options:
332 elif (switch == '-a'):
334 elif (switch == '-c'):
337 elif (switch == '-r'):
339 elif (switch == '-n'):
343 print "Accessing LDAP entry for '" + User + "'",
344 if (BindUser != User):
346 print "as '" + BindUser + "'";
350 # Connect to the ldap server
352 UserDn = "uid=" + User + "," + BaseDn
354 Password = getpass.getpass(BindUser + "'s password: ")
355 BindUserDn = "uid=" + BindUser + "," + BaseDn
360 l.simple_bind_s(BindUserDn,Password)
361 except ldap.LDAPError,e:
362 print >> sys.stderr, "LDAP error:", e.args[0]['desc']
363 print >> sys.stderr, " ", e.args[0]['info']
366 # Enable changing of supplementary gid's
368 # Items that root can edit
369 list = ["supplementaryGid","allowedHost","member"];
372 AttrInfo[x][1] = 200 + Count;
373 OrderedIndex[AttrInfo[x][1]] = [AttrInfo[x][0], "",x];
374 OrigOrderedIndex[AttrInfo[x][1]] = [AttrInfo[x][0], "",x];
377 # Query the server for all of the attributes
378 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid=" + User);
380 print "User",User,"was not found.";
383 # repeatedly show the account configuration
390 print " a) Arbitary Change";
391 print " r) retire developer";
392 print " R) Randomize Password";
393 print " L) Lock account and disable mail";
394 print " p) Change Password";
395 print " u) Switch Users";
399 Response = raw_input("Change? ");
400 if (Response == "x" or Response == "X" or Response == "q" or
401 Response == "quit" or Response == "exit"):
404 # Change who we are looking at
405 if (Response == 'u' or Response == 'U'):
406 NewUser = raw_input("User? ");
409 NAttrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid=" + NewUser);
411 print "User",NewUser,"was not found.";
415 UserDn = "uid=" + User + "," + BaseDn;
416 OrderedIndex = copy.deepcopy(OrigOrderedIndex);
419 # Handle changing the password
420 if (Response == "p"):
421 print "Please enter a new password. Your password can be of unlimited length,";
422 print "contain spaces and other special characters. No checking is done on the";
423 print "strength of the passwords so pick good ones please!";
425 Pass1 = getpass.getpass(User + "'s new password: ")
426 Pass2 = getpass.getpass(User + "'s new password again: ")
428 print "Passwords did not match";
429 raw_input("Press a key");
433 Pass = HashPass(Pass1);
435 print "%s: %s\n" %(sys.exc_type,sys.exc_value);
436 raw_input("Press a key");
439 print "Setting password..";
440 Pass = "{crypt}" + Pass;
441 shadowLast = str(int(time.time()/24/60/60));
442 l.modify_s(UserDn,[(ldap.MOD_REPLACE,"userPassword",Pass),
443 (ldap.MOD_REPLACE,"shadowLastChange",shadowLast)]);
444 Attrs[0][1]["userPassword"] = [Pass];
445 Attrs[0][1]["shadowLastChange"] = [shadowLast];
449 if Response == 'r' and RootMode == 1:
450 if Attrs[0][1].has_key("accountStatus") == 0:
451 curStatus = "<not set>"
453 curStatus = Attrs[0][1]["accountStatus"][0]
454 if Attrs[0][1].has_key("accountComment") == 0:
455 curComment = "<not set>"
457 curComment = Attrs[0][1]["accountComment"][0]
458 print "\n\nCurrent status is %s"%curStatus
459 print "Current comment is %s\n"%curComment
461 print "Set account to:"
462 print " 1) retiring (lock account but do not disable mail):"
463 print " 2) inactive (removed/emeritus/... - lock account and disable mail):"
464 print " 3) memorial (lock account and disable mail):"
465 print " 4) active (do not change other settings, you will have to deal with them)"
466 print " q) return (no change)"
467 Resp = raw_input("Action? ")
468 if Resp == "1" or Resp == "2":
469 Lock(UserDn, Attrs, Resp == "2")
471 newstatus = "retiring %s"%(time.strftime("%Y-%m-%d"))
473 newstatus = "inactive %s"%(time.strftime("%Y-%m-%d"))
474 l.modify_s(UserDn,[(ldap.MOD_REPLACE,"accountStatus",newstatus)])
475 Attrs[0][1]["accountStatus"] = [newstatus]
477 Resp2 = raw_input("Optional RT ticket number? ")
479 comment = "RT#%s"%(Resp2)
480 l.modify_s(UserDn,[(ldap.MOD_REPLACE,"accountComment",comment)])
481 Attrs[0][1]["accountComment"] = [comment]
484 newstatus = "memorial"
485 l.modify_s(UserDn,[(ldap.MOD_REPLACE,"accountStatus",newstatus)])
486 Attrs[0][1]["accountStatus"] = [newstatus]
489 l.modify_s(UserDn,[(ldap.MOD_REPLACE,"accountStatus",newstatus)])
490 Attrs[0][1]["accountStatus"] = [newstatus]
496 if Response == 'R' and RootMode == 1:
497 Resp = raw_input("Randomize Users Password? [no/yes]");
501 # Generate a random password
503 Password = GenPass();
504 Pass = HashPass(Password);
506 print "%s: %s\n" %(sys.exc_type,sys.exc_value);
507 raw_input("Press a key");
510 print "Setting password..";
511 Pass = "{crypt}" + Pass;
512 shadowLast = str(int(time.time()/24/60/60));
513 l.modify_s(UserDn,[(ldap.MOD_REPLACE,"userPassword",Pass),
514 (ldap.MOD_REPLACE,"shadowLastChange",shadowLast)]);
515 Attrs[0][1]["userPassword"] = [Pass];
516 Attrs[0][1]["shadowLastChange"] = [shadowLast];
520 if Response == 'L' and RootMode == 1:
521 Resp = raw_input("Really lock account? [no/yes]");
525 print "Setting password..";
529 # Handle changing an arbitary value
530 if (Response == "a"):
531 Attr = raw_input("Attr? ");
532 ChangeAttr(Attrs[0],Attr);
535 # Convert the integer response
538 if (not OrderedIndex.has_key(ID) or (ID > 100 and RootMode == 0)):
544 # Print the what to do prompt
545 print "Changing LDAP entry '%s' (%s)" % (OrderedIndex[ID][0],OrderedIndex[ID][2]);
546 print AttrPrompt[OrderedIndex[ID][2]][0];
547 ChangeAttr(Attrs[0],OrderedIndex[ID][2]);