Add support for this attribute in ud-info taking into account that
[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 #   Copyright (c) 2008 Joey Schulze <joey@infodrom.org>
28 #
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.
33 #
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.
38 #
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.
42
43 import time, os, pwd, sys, getopt, ldap, crypt, readline, copy;
44 from userdir_ldap import *;
45
46 RootMode = 0;
47 AttrInfo = {"cn": ["First Name", 101],
48             "mn": ["Middle Name", 102],
49             "sn": ["Surname", 103],
50             "c": ["Country Code",1],
51             "l": ["Locality",2],
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],
86             };
87
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"],
125               };
126
127 # Create a map of IDs to desc,value,attr
128 OrderedIndex = {};
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);
133
134 for id in OrderedIndex:
135    if not AttrPrompt.has_key( OrderedIndex[id][2] ):
136       print "Warning: no AttrPrompt for %s"%(id)
137
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"));
146
147    print "%-24s:" % ("Password last changed"),
148    print time.strftime("%a %d/%m/%Y %Z",time.localtime(Changed*24*60*60));
149    if (Expire > 0):
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."
154
155 # Print out the automatic time stamp information
156 def PrintModTime(Attrs):
157    Stamp = GetAttr(Attrs,"modifyTimestamp","");
158    if len(Stamp) >= 13:
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];
163
164    Stamp = GetAttr(Attrs,"createTimestamp","");
165    if len(Stamp) >= 13:
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);
169
170 # Print the PGP key for a user
171 def PrintKeys(Attrs):
172    if Attrs[1].has_key("keyFingerPrint") == 0:
173       return;
174    First = 0;
175    for x in Attrs[1]["keyFingerPrint"]:
176       if First == 0:
177          print "%-24s:" % ("PGP/GPG Key Fingerprints"),
178          First = 1;
179       else:
180          print "%-24s:" % (""),
181       print FormatPGPKey(x);
182
183 # Print the SSH RSA Authentication keys for a user
184 def PrintSshRSAKeys(Attrs):
185    if Attrs[1].has_key("sshRSAAuthKey") == 0:
186       return;
187    First = 0;
188    for x in Attrs[1]["sshRSAAuthKey"]:
189       if First == 0:
190          print "%-24s:" % ("SSH Auth Keys"),
191          First = 1;
192       else:
193          print "%-24s:" % (""),
194
195       print FormatSSHAuth(x);
196       
197 # Display all of the attributes in a numbered list
198 def ShowAttrs(Attrs):
199    print;
200    print EmailAddress(Attrs);   
201    PrintModTime(Attrs);
202    PrintShadow(Attrs);
203    PrintKeys(Attrs);
204    PrintSshRSAKeys(Attrs);
205
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]:
211                print "'%s'" % (x),
212             if at == "uid":
213                print "(id=%s, gid=%s)" % (GetAttr(Attrs,"uidNumber","-1"),GetAttr(Attrs,"gidNumber","-1")),
214             print;
215          else:
216             OrderedIndex[AttrInfo[at][1]][1] = Attrs[1][at];
217                                        
218    Keys = OrderedIndex.keys();
219    Keys.sort();
220    for at in 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)),
225          print;
226
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);
233
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? ");
237   
238    # Empty string
239    if (NewValue == ""):
240       print "Leaving unchanged.";
241       return;
242
243    # Single space designates delete, trap the delete error
244    if (NewValue == " "):
245       print "Deleting.",;
246       try:
247          l.modify_s(UserDn,[(ldap.MOD_DELETE,Attr,None)]);
248       except ldap.NO_SUCH_ATTRIBUTE:
249          pass;
250
251       print;
252       Attrs[1][Attr] = [""];
253       return;
254
255    if (Attr == "mailSpamOptOut" and NewValue != "true" and NewValue != "false"):
256       if (NewValue == "1"): NewValue = "true"
257       else:
258          if (NewValue == "0"): NewValue = "false"
259          else:
260             print "Need a boolean value"
261             return
262
263    # Set a new value
264    print "Setting.",;
265    l.modify_s(UserDn,[(ldap.MOD_REPLACE,Attr,NewValue)]);
266    Attrs[1][Attr] = [NewValue];
267    print;
268
269 def MultiChangeAttr(Attrs,Attr):
270    # Make sure that we have an entry
271    if not Attrs[1].has_key(Attr):
272       Attrs[1][Attr] = [];
273
274    Attrs[1][Attr].sort();
275    print "Old values: ",Attrs[1][Attr];
276
277    Mode = raw_input("[D]elete or [A]dd? ").upper()
278    if (Mode != 'D' and Mode != 'A'):
279       return;
280
281    NewValue = raw_input("Value? ");
282    # Empty string
283    if (NewValue == ""):
284       print "Leaving unchanged.";
285       return;
286    
287    # Delete   
288    if (Mode == "D"):
289       print "Deleting.",;
290       try:
291          l.modify_s(UserDn,[(ldap.MOD_DELETE,Attr,NewValue)]);
292       except ldap.NO_SUCH_ATTRIBUTE:
293          print "Failed";
294
295       print;
296       Attrs[1][Attr].remove(NewValue);
297       return;
298
299    # Set a new value
300    print "Setting.",;
301    l.modify_s(UserDn,[(ldap.MOD_ADD,Attr,NewValue)]);
302    Attrs[1][Attr].append(NewValue);
303    print;
304
305 def Lock(UserDn, Attrs, DisableMail=True):
306    shadowLast = str(int(time.time()/24/60/60));
307    recs = [
308       (ldap.MOD_REPLACE,"userPassword","{crypt}*LK*"),
309       (ldap.MOD_REPLACE,"shadowLastChange",shadowLast),
310       (ldap.MOD_REPLACE,"shadowExpire","1")];
311    if DisableMail:
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"];
318
319 # Main program starts here
320 User = pwd.getpwuid(os.getuid())[0];
321 BindUser = User;
322 # Process options
323 try:
324    (options, arguments) = getopt.getopt(sys.argv[1:], "nu:c:a:r")
325 except getopt.GetoptError, data:
326    print data
327    sys.exit(1)
328
329 for (switch, val) in options:
330    if (switch == '-u'):
331       User = val;
332    elif (switch == '-a'):
333       BindUser = val;
334    elif (switch == '-c'):
335       BindUser = val;
336       User = val;
337    elif (switch == '-r'):
338       RootMode = 1;
339    elif (switch == '-n'):
340       BindUser = "";
341
342 if (BindUser != ""):
343    print "Accessing LDAP entry for '" + User + "'",
344 if (BindUser != User):
345    if (BindUser != ""):
346       print "as '" + BindUser + "'";
347 else:
348    print;
349 if (BindUser != ""):
350    Password = getpass(BindUser + "'s password: ");
351
352 # Connect to the ldap server
353 l = connectLDAP()
354 UserDn = "uid=" + BindUser + "," + BaseDn;
355 if (BindUser != ""):
356    l.simple_bind_s(UserDn,Password);
357 else:
358    l.simple_bind_s("","");
359 UserDn = "uid=" + User + "," + BaseDn;
360
361 # Enable changing of supplementary gid's
362 if (RootMode == 1):
363    # Items that root can edit
364    list = ["supplementaryGid","allowedHost","member"];
365    Count = 0;
366    for x in list:
367       AttrInfo[x][1] = 200 + Count;
368       OrderedIndex[AttrInfo[x][1]] = [AttrInfo[x][0], "",x];
369       OrigOrderedIndex[AttrInfo[x][1]] = [AttrInfo[x][0], "",x];
370       Count = Count + 1;
371
372 # Query the server for all of the attributes
373 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid=" + User);
374 if len(Attrs) == 0:
375    print "User",User,"was not found.";
376    sys.exit(0); 
377
378 # repeatedly show the account configuration
379 while(1):
380    ShowAttrs(Attrs[0]);
381    if (BindUser == ""):
382       sys.exit(0);
383
384    if RootMode == 1:
385       print "   a) Arbitary Change";
386       print "   r) retire developer";
387       print "   R) Randomize Password";
388       print "   L) Lock account and disable mail";
389    print "   p) Change Password";
390    print "   u) Switch Users";
391    print "   x) Exit";
392    
393    # Prompt
394    Response = raw_input("Change? ");
395    if (Response == "x" or Response == "X" or Response == "q" or 
396        Response == "quit" or Response == "exit"):
397       break;
398
399    # Change who we are looking at
400    if (Response == 'u' or Response == 'U'):
401       NewUser = raw_input("User? ");
402       if NewUser == "":
403          continue;
404       NAttrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid=" + NewUser);
405       if len(NAttrs) == 0:
406          print "User",NewUser,"was not found.";
407          continue;
408       Attrs = NAttrs;
409       User = NewUser;
410       UserDn = "uid=" + User + "," + BaseDn;
411       OrderedIndex = copy.deepcopy(OrigOrderedIndex);
412       continue;
413
414    # Handle changing the password
415    if (Response == "p"):
416       print "Please enter a new password. Your password can be of unlimited length,";
417       print "contain spaces and other special characters. No checking is done on the";
418       print "strength of the passwords so pick good ones please!";
419
420       Pass1 = getpass(User + "'s new password: ");
421       Pass2 = getpass(User + "'s new password again: ");
422       if Pass1 != Pass2:
423          print "Passwords did not match";
424          raw_input("Press a key");
425          continue;
426
427       try:
428          Pass = HashPass(Pass1);
429       except:
430          print "%s: %s\n" %(sys.exc_type,sys.exc_value);
431          raw_input("Press a key");
432          continue;
433
434       print "Setting password..";
435       Pass = "{crypt}" + Pass;
436       shadowLast = str(int(time.time()/24/60/60));
437       l.modify_s(UserDn,[(ldap.MOD_REPLACE,"userPassword",Pass),
438                          (ldap.MOD_REPLACE,"shadowLastChange",shadowLast)]);
439       Attrs[0][1]["userPassword"] = [Pass];
440       Attrs[0][1]["shadowLastChange"] = [shadowLast];
441       continue;
442
443    # retire DD
444    if Response == 'r' and RootMode == 1:
445       if Attrs[0][1].has_key("accountStatus") == 0:
446         curStatus = "<not set>"
447       else:
448         curStatus = Attrs[0][1]["accountStatus"][0]
449       if Attrs[0][1].has_key("accountComment") == 0:
450         curComment = "<not set>"
451       else:
452         curComment = Attrs[0][1]["accountComment"][0]
453       print "\n\nCurrent status is %s"%curStatus
454       print "Current comment is %s\n"%curComment
455
456       print "Set account to:"
457       print "  1) retiring (lock account but do not disable mail):"
458       print "  2) inactive (removed/emeritus/... - lock account and disable mail):"
459       print "  3) memorial (lock account and disable mail):"
460       print "  4) active (do not change other settings, you will have to deal with them)"
461       print "  q) return (no change)"
462       Resp = raw_input("Action? ")
463       if Resp == "1" or Resp == "2":
464          Lock(UserDn, Attrs, Resp == "2")
465          if Resp == "1":
466            newstatus = "retiring %s"%(time.strftime("%Y-%m-%d"))
467          else:
468            newstatus = "inactive %s"%(time.strftime("%Y-%m-%d"))
469          l.modify_s(UserDn,[(ldap.MOD_REPLACE,"accountStatus",newstatus)])
470          Attrs[0][1]["accountStatus"] = [newstatus]
471
472          Resp2 = raw_input("Optional RT ticket number? ")
473          if (Resp2 != ''):
474            comment = "RT#%s"%(Resp2)
475            l.modify_s(UserDn,[(ldap.MOD_REPLACE,"accountComment",comment)])
476            Attrs[0][1]["accountComment"] = [comment]
477       elif Resp == "3":
478          Lock(UserDn, Attrs)
479          newstatus = "memorial"
480          l.modify_s(UserDn,[(ldap.MOD_REPLACE,"accountStatus",newstatus)])
481          Attrs[0][1]["accountStatus"] = [newstatus]
482       elif Resp == "4":
483          newstatus = "active"
484          l.modify_s(UserDn,[(ldap.MOD_REPLACE,"accountStatus",newstatus)])
485          Attrs[0][1]["accountStatus"] = [newstatus]
486
487       continue;
488
489
490    # Randomize password
491    if Response == 'R' and RootMode == 1:
492       Resp = raw_input("Randomize Users Password? [no/yes]");
493       if Resp != "yes":
494          continue;
495          
496       # Generate a random password
497       try:
498          Password = GenPass();
499          Pass = HashPass(Password);
500       except:
501          print "%s: %s\n" %(sys.exc_type,sys.exc_value);
502          raw_input("Press a key");
503          continue;
504          
505       print "Setting password..";
506       Pass = "{crypt}" + Pass;
507       shadowLast = str(int(time.time()/24/60/60));
508       l.modify_s(UserDn,[(ldap.MOD_REPLACE,"userPassword",Pass),
509                          (ldap.MOD_REPLACE,"shadowLastChange",shadowLast)]);
510       Attrs[0][1]["userPassword"] = [Pass];
511       Attrs[0][1]["shadowLastChange"] = [shadowLast];
512       continue;
513
514    # Lock account
515    if Response == 'L' and RootMode == 1:
516       Resp = raw_input("Really lock account? [no/yes]");
517       if Resp != "yes":
518          continue;
519
520       print "Setting password..";
521       Lock(UserDn, Attrs)
522       continue;
523
524    # Handle changing an arbitary value
525    if (Response == "a"):
526       Attr = raw_input("Attr? ");
527       ChangeAttr(Attrs[0],Attr);
528       continue;
529
530    # Convert the integer response
531    try:
532       ID = int(Response);
533       if (not OrderedIndex.has_key(ID) or (ID > 100 and RootMode == 0)):
534          raise ValueError;
535    except ValueError:
536       print "Invalid";
537       continue;
538
539    # Print the what to do prompt
540    print "Changing LDAP entry '%s' (%s)" % (OrderedIndex[ID][0],OrderedIndex[ID][2]);
541    print AttrPrompt[OrderedIndex[ID][2]][0];
542    ChangeAttr(Attrs[0],OrderedIndex[ID][2]);