ud-info: Add "retire developer" option that sets accountStatus properly to
[mirror/userdir-ldap.git] / ud-info
1 #!/usr/bin/env python
2 # -*- mode: python -*-
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.
10 #
11 #  Usage: userinfo -a <user> -u <user> -c <user> -r
12 #    -a    Set the authentication user (the user whose password you are 
13 #          going to enter)
14 #    -u    Set the user to display
15 #    -c    Set both -a and -u, use this if your login uid is not in the 
16 #          database
17 #    -r    Enable 'root' functions, do this if your uid has access to
18 #          restricted variables.
19
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>
27 #
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.
32 #
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.
37 #
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.
41
42 import time, os, pwd, sys, getopt, ldap, crypt, readline, copy;
43 from userdir_ldap import *;
44
45 RootMode = 0;
46 AttrInfo = {"cn": ["First Name", 101],
47             "mn": ["Middle Name", 102],
48             "sn": ["Surname", 103],
49             "c": ["Country Code",1],
50             "l": ["Locality",2],
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             "VoIP": ["VoIP Address",25],
79             "comment": ["Comment",116],
80             "userPassword": ["Crypted Password",117],
81             "dnsZoneEntry": ["d.net Entry",118],
82             "accountStatus": ["DD status",301],
83             "accountComment": ["DD status comment",302],
84             };
85
86 AttrPrompt = {"cn": ["Common name or first name"],
87               "mn": ["Middle name (or initial if it ends in a dot)"],
88               "sn": ["Surname or last name"],
89               "c": ["ISO 2 letter country code, such as US, DE, etc"],
90               "l": ["City name, State/Provice (Locality)\n e.g. Dallas, Texas"],
91               "facsimileTelephoneNumber": ["Fax phone number, with area code and country code"],
92               "telephoneNumber": ["Voice phone number"],
93               "postalAddress": ["Complete mailing address including postal codes and country designations\nSeperate lines using a $ character"],
94               "postalCode": ["Postal Code or Zip Code"],
95               "loginShell": ["Login shell with full path (no check is done for validity)"],
96               "emailForward": ["EMail address to send all mail to or blank to disable"],
97               "ircNick": ["IRC nickname if you use IRC"],
98               "onVacation": ["A message if on vaction, indicating the time of departure and return"],
99               "userPassword": ["The users Crypt'd password"],
100               "comment": ["Admin Comment about the account"],
101               "supplementaryGid": ["Groups the user is in"],
102               "allowedHost": ["Grant access to certain hosts"],
103               "privateSub": ["Debian-Private mailing list subscription"],
104               "gender": ["ISO5218 Gender code (1=male,2=female,9=unspecified)"],
105               "birthDate": ["Date of Birth (YYYYMMDD)"],
106               "mailDisableMessage": ["Error message to return via SMTP"],
107               "mailGreylisting": ["SMTP Greylisting (TRUE/FALSE)"],
108               "mailCallout": ["SMTP Callouts (TRUE/FALSE)"],
109               "mailRBL": ["SMTP time RBL lists"],
110               "mailRHSBL": ["SMTP time RHSBL lists"],
111               "mailWhitelist": ["SMTP time whitelist from other checks"],
112               "member": ["LDAP Group Member for slapd ACLs"],
113               "latitude": ["XEarth latitude in ISO 6709 format - see /usr/share/zoneinfo/zone.tab or etak.com"],
114               "longitude": ["XEarth latitude in ISO 6709 format - see /usr/share/zoneinfo/zone.tab or etak.com"],
115               "dnsZoneEntry": ["DNS Zone fragment associated this this user"],
116               "labeledURI": ["Web home page"],
117               "jabberJID": ["Jabber ID"],
118               "icqUin": ["ICQ UIN Number"],
119               "VoIP": ["VoIP Address"]};
120
121 # Create a map of IDs to desc,value,attr
122 OrderedIndex = {};
123 for at in AttrInfo.keys():
124    if (AttrInfo[at][1] != 0):
125       OrderedIndex[AttrInfo[at][1]] = [AttrInfo[at][0], "", at];
126 OrigOrderedIndex = copy.deepcopy(OrderedIndex);
127
128 # Show shadow information
129 def PrintShadow(Attrs):
130    Changed = int(GetAttr(Attrs,"shadowLastChange","0"));
131    MinDays = int(GetAttr(Attrs,"shadowMin","0"));
132    MaxDays = int(GetAttr(Attrs,"shadowMax","0"));
133    WarnDays = int(GetAttr(Attrs,"shadowWarning","0"));
134    InactDays = int(GetAttr(Attrs,"shadowInactive","0"));
135    Expire = int(GetAttr(Attrs,"shadowExpire","0"));
136
137    print "%-24s:" % ("Password last changed"),
138    print time.strftime("%a %d/%m/%Y %Z",time.localtime(Changed*24*60*60));
139    if (Expire > 0):
140       print "%-24s:" % ("Account expires on"),
141       print time.strftime("%a %d/%m/%Y %Z",time.localtime(Expire*24*60*60));
142    if (InactDays >= 0 and MaxDays < 99999):
143       print "Account aging is active, you must change your password every", MaxDays, "days."
144
145 # Print out the automatic time stamp information
146 def PrintModTime(Attrs):
147    Stamp = GetAttr(Attrs,"modifyTimestamp","");
148    if len(Stamp) >= 13:
149       Time = (int(Stamp[0:4]),int(Stamp[4:6]),int(Stamp[6:8]),
150               int(Stamp[8:10]),int(Stamp[10:12]),int(Stamp[12:14]),0,0,-1);
151       print "%-24s:" % ("Record last modified on"), time.strftime("%a %d/%m/%Y %X UTC",Time),
152       print "by",ldap.explode_dn(GetAttr(Attrs,"modifiersName"),1)[0];
153
154    Stamp = GetAttr(Attrs,"createTimestamp","");
155    if len(Stamp) >= 13:
156       Time = (int(Stamp[0:4]),int(Stamp[4:6]),int(Stamp[6:8]),
157               int(Stamp[8:10]),int(Stamp[10:12]),int(Stamp[12:14]),0,0,-1);
158       print "%-24s:" % ("Record created on"), time.strftime("%a %d/%m/%Y %X UTC",Time);
159
160 # Print the PGP key for a user
161 def PrintKeys(Attrs):
162    if Attrs[1].has_key("keyFingerPrint") == 0:
163       return;
164    First = 0;
165    for x in Attrs[1]["keyFingerPrint"]:
166       if First == 0:
167          print "%-24s:" % ("PGP/GPG Key Fingerprints"),
168          First = 1;
169       else:
170          print "%-24s:" % (""),
171       print FormatPGPKey(x);
172
173 # Print the SSH RSA Authentication keys for a user
174 def PrintSshRSAKeys(Attrs):
175    if Attrs[1].has_key("sshRSAAuthKey") == 0:
176       return;
177    First = 0;
178    for x in Attrs[1]["sshRSAAuthKey"]:
179       if First == 0:
180          print "%-24s:" % ("SSH Auth Keys"),
181          First = 1;
182       else:
183          print "%-24s:" % (""),
184
185       print FormatSSHAuth(x);
186       
187 # Display all of the attributes in a numbered list
188 def ShowAttrs(Attrs):
189    print;
190    print EmailAddress(Attrs);   
191    PrintModTime(Attrs);
192    PrintShadow(Attrs);
193    PrintKeys(Attrs);
194    PrintSshRSAKeys(Attrs);
195
196    for at in Attrs[1].keys():
197       if AttrInfo.has_key(at):
198          if AttrInfo[at][1] == 0:
199             print "      %-18s:" % (AttrInfo[at][0]),
200             for x in Attrs[1][at]:
201                print "'%s'" % (x),
202             if at == "uid":
203                print "(id=%s, gid=%s)" % (GetAttr(Attrs,"uidNumber","-1"),GetAttr(Attrs,"gidNumber","-1")),
204             print;
205          else:
206             OrderedIndex[AttrInfo[at][1]][1] = Attrs[1][at];
207                                        
208    Keys = OrderedIndex.keys();
209    Keys.sort();
210    for at in Keys:
211       if at < 100 or RootMode != 0:
212          print " %3u) %-18s: " % (at,OrderedIndex[at][0]),
213          for x in OrderedIndex[at][1]:
214             print "'%s'" % (re.sub('[\n\r]','?',x)),
215          print;
216
217 # Change a single attribute
218 def ChangeAttr(Attrs,Attr):
219    if (Attr == "supplementaryGid" or Attr == "allowedHost" or \
220        Attr == "member" or Attr == "dnsZoneEntry" or Attr == "mailWhitelist" or \
221        Attr == "mailRBL" or Attr == "mailRHSBL"):
222       return MultiChangeAttr(Attrs,Attr);
223
224    print "Old value: '%s'" % (GetAttr(Attrs,Attr,""));
225    print "Press enter to leave unchanged and a single space to set to empty";
226    NewValue = raw_input("New? ");
227   
228    # Empty string
229    if (NewValue == ""):
230       print "Leaving unchanged.";
231       return;
232
233    # Single space designates delete, trap the delete error
234    if (NewValue == " "):
235       print "Deleting.",;
236       try:
237          l.modify_s(UserDn,[(ldap.MOD_DELETE,Attr,None)]);
238       except ldap.NO_SUCH_ATTRIBUTE:
239          pass;
240
241       print;
242       Attrs[1][Attr] = [""];
243       return;
244
245    # Set a new value
246    print "Setting.",;
247    l.modify_s(UserDn,[(ldap.MOD_REPLACE,Attr,NewValue)]);
248    Attrs[1][Attr] = [NewValue];
249    print;
250
251 def MultiChangeAttr(Attrs,Attr):
252    # Make sure that we have an entry
253    if not Attrs[1].has_key(Attr):
254       Attrs[1][Attr] = [];
255
256    Attrs[1][Attr].sort();
257    print "Old values: ",Attrs[1][Attr];
258
259    Mode = raw_input("[D]elete or [A]dd? ").upper()
260    if (Mode != 'D' and Mode != 'A'):
261       return;
262
263    NewValue = raw_input("Value? ");
264    # Empty string
265    if (NewValue == ""):
266       print "Leaving unchanged.";
267       return;
268    
269    # Delete   
270    if (Mode == "D"):
271       print "Deleting.",;
272       try:
273          l.modify_s(UserDn,[(ldap.MOD_DELETE,Attr,NewValue)]);
274       except ldap.NO_SUCH_ATTRIBUTE:
275          print "Failed";
276
277       print;
278       Attrs[1][Attr].remove(NewValue);
279       return;
280
281    # Set a new value
282    print "Setting.",;
283    l.modify_s(UserDn,[(ldap.MOD_ADD,Attr,NewValue)]);
284    Attrs[1][Attr].append(NewValue);
285    print;
286
287 def Lock(UserDn, Attrs, DisableMail=True):
288    shadowLast = str(int(time.time()/24/60/60));
289    recs = [
290       (ldap.MOD_REPLACE,"userPassword","{crypt}*LK*"),
291       (ldap.MOD_REPLACE,"shadowLastChange",shadowLast),
292       (ldap.MOD_REPLACE,"shadowExpire","1")];
293    if DisableMail:
294       recs.append( (ldap.MOD_REPLACE,"mailDisableMessage","account locked") )
295       Attrs[0][1]["shadowLastChange"] = [shadowLast];
296    l.modify_s(UserDn,recs);
297    Attrs[0][1]["userPassword"] = ["{crypt}*LK*"];
298    Attrs[0][1]["mailDisableMessage"] = ["account locked"];
299    Attrs[0][1]["shadowExpire"] = ["1"];
300
301 # Main program starts here
302 User = pwd.getpwuid(os.getuid())[0];
303 BindUser = User;
304 # Process options
305 try:
306    (options, arguments) = getopt.getopt(sys.argv[1:], "nu:c:a:r")
307 except getopt.GetoptError, data:
308    print data
309    sys.exit(1)
310
311 for (switch, val) in options:
312    if (switch == '-u'):
313       User = val;
314    elif (switch == '-a'):
315       BindUser = val;
316    elif (switch == '-c'):
317       BindUser = val;
318       User = val;
319    elif (switch == '-r'):
320       RootMode = 1;
321    elif (switch == '-n'):
322       BindUser = "";
323
324 if (BindUser != ""):
325    print "Accessing LDAP entry for '" + User + "'",
326 if (BindUser != User):
327    if (BindUser != ""):
328       print "as '" + BindUser + "'";
329 else:
330    print;
331 if (BindUser != ""):
332    Password = getpass(BindUser + "'s password: ");
333
334 # Connect to the ldap server
335 l = connectLDAP()
336 UserDn = "uid=" + BindUser + "," + BaseDn;
337 if (BindUser != ""):
338    l.simple_bind_s(UserDn,Password);
339 else:
340    l.simple_bind_s("","");
341 UserDn = "uid=" + User + "," + BaseDn;
342
343 # Enable changing of supplementary gid's
344 if (RootMode == 1):
345    # Items that root can edit
346    list = ["supplementaryGid","allowedHost","member"];
347    Count = 0;
348    for x in list:
349       AttrInfo[x][1] = 200 + Count;
350       OrderedIndex[AttrInfo[x][1]] = [AttrInfo[x][0], "",x];
351       OrigOrderedIndex[AttrInfo[x][1]] = [AttrInfo[x][0], "",x];
352       Count = Count + 1;
353
354 # Query the server for all of the attributes
355 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid=" + User);
356 if len(Attrs) == 0:
357    print "User",User,"was not found.";
358    sys.exit(0); 
359
360 # repeatedly show the account configuration
361 while(1):
362    ShowAttrs(Attrs[0]);
363    if (BindUser == ""):
364       sys.exit(0);
365
366    if RootMode == 1:
367       print "   a) Arbitary Change";
368       print "   r) retire developer";
369       print "   R) Randomize Password";
370       print "   L) Lock account and disable mail";
371    print "   p) Change Password";
372    print "   u) Switch Users";
373    print "   x) Exit";
374    
375    # Prompt
376    Response = raw_input("Change? ");
377    if (Response == "x" or Response == "X" or Response == "q" or 
378        Response == "quit" or Response == "exit"):
379       break;
380
381    # Change who we are looking at
382    if (Response == 'u' or Response == 'U'):
383       NewUser = raw_input("User? ");
384       if NewUser == "":
385          continue;
386       NAttrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid=" + NewUser);
387       if len(NAttrs) == 0:
388          print "User",NewUser,"was not found.";
389          continue;
390       Attrs = NAttrs;
391       User = NewUser;
392       UserDn = "uid=" + User + "," + BaseDn;
393       OrderedIndex = copy.deepcopy(OrigOrderedIndex);
394       continue;
395
396    # Handle changing the password
397    if (Response == "p"):
398       print "Please enter a new password. Your password can be of unlimited length,";
399       print "contain spaces and other special characters. No checking is done on the";
400       print "strength of the passwords so pick good ones please!";
401
402       Pass1 = getpass(User + "'s new password: ");
403       Pass2 = getpass(User + "'s new password again: ");
404       if Pass1 != Pass2:
405          print "Passwords did not match";
406          raw_input("Press a key");
407          continue;
408
409       try:
410          Pass = HashPass(Pass1);
411       except:
412          print "%s: %s\n" %(sys.exc_type,sys.exc_value);
413          raw_input("Press a key");
414          continue;
415
416       print "Setting password..";
417       Pass = "{crypt}" + Pass;
418       shadowLast = str(int(time.time()/24/60/60));
419       l.modify_s(UserDn,[(ldap.MOD_REPLACE,"userPassword",Pass),
420                          (ldap.MOD_REPLACE,"shadowLastChange",shadowLast)]);
421       Attrs[0][1]["userPassword"] = [Pass];
422       Attrs[0][1]["shadowLastChange"] = [shadowLast];
423       continue;
424
425    # retire DD
426    if Response == 'r' and RootMode == 1:
427       if Attrs[0][1].has_key("accountStatus") == 0:
428         curStatus = "<not set>"
429       else:
430         curStatus = Attrs[0][1]["accountStatus"][0]
431       if Attrs[0][1].has_key("accountComment") == 0:
432         curComment = "<not set>"
433       else:
434         curComment = Attrs[0][1]["accountComment"][0]
435       print "\n\nCurrent status is %s"%curStatus
436       print "Current comment is %s\n"%curComment
437
438       print "Set account to:"
439       print "  1) retiring (lock account but do not disable mail):"
440       print "  2) retired (lock account and disable mail):"
441       print "  3) memorial (lock account and disable mail):"
442       print "  4) active (do not change other settings, you will have to deal with them)"
443       print "  q) return (no change)"
444       Resp = raw_input("Action? ")
445       if Resp == "1" or Resp == "2":
446          Lock(UserDn, Attrs, Resp == "2")
447          if Resp == "1":
448            newstatus = "retiring %s"%(time.strftime("%Y-%m-%d"))
449          else:
450            newstatus = "retired %s"%(time.strftime("%Y-%m-%d"))
451          l.modify_s(UserDn,[(ldap.MOD_REPLACE,"accountStatus",newstatus)])
452          Attrs[0][1]["accountStatus"] = [newstatus]
453
454          Resp2 = raw_input("Optional RT ticket number? ")
455          if (Resp2 != ''):
456            comment = "RT#%s"%(Resp2)
457            l.modify_s(UserDn,[(ldap.MOD_REPLACE,"accountComment",comment)])
458            Attrs[0][1]["accountComment"] = [comment]
459       elif Resp == "3":
460          Lock(UserDn, Attrs)
461          newstatus = "memorial"
462          l.modify_s(UserDn,[(ldap.MOD_REPLACE,"accountStatus",newstatus)])
463          Attrs[0][1]["accountStatus"] = [newstatus]
464       elif Resp == "4":
465          newstatus = "active"
466          l.modify_s(UserDn,[(ldap.MOD_REPLACE,"accountStatus",newstatus)])
467          Attrs[0][1]["accountStatus"] = [newstatus]
468
469       continue;
470
471
472    # Randomize password
473    if Response == 'R' and RootMode == 1:
474       Resp = raw_input("Randomize Users Password? [no/yes]");
475       if Resp != "yes":
476          continue;
477          
478       # Generate a random password
479       try:
480          Password = GenPass();
481          Pass = HashPass(Password);
482       except:
483          print "%s: %s\n" %(sys.exc_type,sys.exc_value);
484          raw_input("Press a key");
485          continue;
486          
487       print "Setting password..";
488       Pass = "{crypt}" + Pass;
489       shadowLast = str(int(time.time()/24/60/60));
490       l.modify_s(UserDn,[(ldap.MOD_REPLACE,"userPassword",Pass),
491                          (ldap.MOD_REPLACE,"shadowLastChange",shadowLast)]);
492       Attrs[0][1]["userPassword"] = [Pass];
493       Attrs[0][1]["shadowLastChange"] = [shadowLast];
494       continue;
495
496    # Lock account
497    if Response == 'L' and RootMode == 1:
498       Resp = raw_input("Really lock account? [no/yes]");
499       if Resp != "yes":
500          continue;
501
502       print "Setting password..";
503       Lock(UserDn, Attrs)
504       continue;
505
506    # Handle changing an arbitary value
507    if (Response == "a"):
508       Attr = raw_input("Attr? ");
509       ChangeAttr(Attrs[0],Attr);
510       continue;
511
512    # Convert the integer response
513    try:
514       ID = int(Response);
515       if (not OrderedIndex.has_key(ID) or (ID > 100 and RootMode == 0)):
516          raise ValueError;
517    except ValueError:
518       print "Invalid";
519       continue;
520
521    # Print the what to do prompt
522    print "Changing LDAP entry '%s' (%s)" % (OrderedIndex[ID][0],OrderedIndex[ID][2]);
523    print AttrPrompt[OrderedIndex[ID][2]][0];
524    ChangeAttr(Attrs[0],OrderedIndex[ID][2]);