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 "mailSpamOptOut": ["Mail Spam Filtering",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 "mailSpamOptOut": ["Mail Spam Filtering"],
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) %-18s: " % (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 == "mailSpamOptOut" and NewValue != "true" and NewValue != "false"):
256 if (NewValue == "1"): NewValue = "true"
258 if (NewValue == "0"): NewValue = "false"
260 print "Need a boolean value"
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
353 Password = getpass.getpass(BindUser + "'s password: ")
354 UserDn = "uid=" + BindUser + "," + BaseDn
359 l.simple_bind_s(UserDn,Password)
360 except ldap.LDAPError,e:
361 print >> sys.stderr, "LDAP error:", e.args[0]['desc']
362 print >> sys.stderr, " ", e.args[0]['info']
365 # Enable changing of supplementary gid's
367 # Items that root can edit
368 list = ["supplementaryGid","allowedHost","member"];
371 AttrInfo[x][1] = 200 + Count;
372 OrderedIndex[AttrInfo[x][1]] = [AttrInfo[x][0], "",x];
373 OrigOrderedIndex[AttrInfo[x][1]] = [AttrInfo[x][0], "",x];
376 # Query the server for all of the attributes
377 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid=" + User);
379 print "User",User,"was not found.";
382 # repeatedly show the account configuration
389 print " a) Arbitary Change";
390 print " r) retire developer";
391 print " R) Randomize Password";
392 print " L) Lock account and disable mail";
393 print " p) Change Password";
394 print " u) Switch Users";
398 Response = raw_input("Change? ");
399 if (Response == "x" or Response == "X" or Response == "q" or
400 Response == "quit" or Response == "exit"):
403 # Change who we are looking at
404 if (Response == 'u' or Response == 'U'):
405 NewUser = raw_input("User? ");
408 NAttrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid=" + NewUser);
410 print "User",NewUser,"was not found.";
414 UserDn = "uid=" + User + "," + BaseDn;
415 OrderedIndex = copy.deepcopy(OrigOrderedIndex);
418 # Handle changing the password
419 if (Response == "p"):
420 print "Please enter a new password. Your password can be of unlimited length,";
421 print "contain spaces and other special characters. No checking is done on the";
422 print "strength of the passwords so pick good ones please!";
424 Pass1 = getpass.getpass(User + "'s new password: ")
425 Pass2 = getpass.getpass(User + "'s new password again: ")
427 print "Passwords did not match";
428 raw_input("Press a key");
432 Pass = HashPass(Pass1);
434 print "%s: %s\n" %(sys.exc_type,sys.exc_value);
435 raw_input("Press a key");
438 print "Setting password..";
439 Pass = "{crypt}" + Pass;
440 shadowLast = str(int(time.time()/24/60/60));
441 l.modify_s(UserDn,[(ldap.MOD_REPLACE,"userPassword",Pass),
442 (ldap.MOD_REPLACE,"shadowLastChange",shadowLast)]);
443 Attrs[0][1]["userPassword"] = [Pass];
444 Attrs[0][1]["shadowLastChange"] = [shadowLast];
448 if Response == 'r' and RootMode == 1:
449 if Attrs[0][1].has_key("accountStatus") == 0:
450 curStatus = "<not set>"
452 curStatus = Attrs[0][1]["accountStatus"][0]
453 if Attrs[0][1].has_key("accountComment") == 0:
454 curComment = "<not set>"
456 curComment = Attrs[0][1]["accountComment"][0]
457 print "\n\nCurrent status is %s"%curStatus
458 print "Current comment is %s\n"%curComment
460 print "Set account to:"
461 print " 1) retiring (lock account but do not disable mail):"
462 print " 2) inactive (removed/emeritus/... - lock account and disable mail):"
463 print " 3) memorial (lock account and disable mail):"
464 print " 4) active (do not change other settings, you will have to deal with them)"
465 print " q) return (no change)"
466 Resp = raw_input("Action? ")
467 if Resp == "1" or Resp == "2":
468 Lock(UserDn, Attrs, Resp == "2")
470 newstatus = "retiring %s"%(time.strftime("%Y-%m-%d"))
472 newstatus = "inactive %s"%(time.strftime("%Y-%m-%d"))
473 l.modify_s(UserDn,[(ldap.MOD_REPLACE,"accountStatus",newstatus)])
474 Attrs[0][1]["accountStatus"] = [newstatus]
476 Resp2 = raw_input("Optional RT ticket number? ")
478 comment = "RT#%s"%(Resp2)
479 l.modify_s(UserDn,[(ldap.MOD_REPLACE,"accountComment",comment)])
480 Attrs[0][1]["accountComment"] = [comment]
483 newstatus = "memorial"
484 l.modify_s(UserDn,[(ldap.MOD_REPLACE,"accountStatus",newstatus)])
485 Attrs[0][1]["accountStatus"] = [newstatus]
488 l.modify_s(UserDn,[(ldap.MOD_REPLACE,"accountStatus",newstatus)])
489 Attrs[0][1]["accountStatus"] = [newstatus]
495 if Response == 'R' and RootMode == 1:
496 Resp = raw_input("Randomize Users Password? [no/yes]");
500 # Generate a random password
502 Password = GenPass();
503 Pass = HashPass(Password);
505 print "%s: %s\n" %(sys.exc_type,sys.exc_value);
506 raw_input("Press a key");
509 print "Setting password..";
510 Pass = "{crypt}" + Pass;
511 shadowLast = str(int(time.time()/24/60/60));
512 l.modify_s(UserDn,[(ldap.MOD_REPLACE,"userPassword",Pass),
513 (ldap.MOD_REPLACE,"shadowLastChange",shadowLast)]);
514 Attrs[0][1]["userPassword"] = [Pass];
515 Attrs[0][1]["shadowLastChange"] = [shadowLast];
519 if Response == 'L' and RootMode == 1:
520 Resp = raw_input("Really lock account? [no/yes]");
524 print "Setting password..";
528 # Handle changing an arbitary value
529 if (Response == "a"):
530 Attr = raw_input("Attr? ");
531 ChangeAttr(Attrs[0],Attr);
534 # Convert the integer response
537 if (not OrderedIndex.has_key(ID) or (ID > 100 and RootMode == 0)):
543 # Print the what to do prompt
544 print "Changing LDAP entry '%s' (%s)" % (OrderedIndex[ID][0],OrderedIndex[ID][2]);
545 print AttrPrompt[OrderedIndex[ID][2]][0];
546 ChangeAttr(Attrs[0],OrderedIndex[ID][2]);