Patch by Thomas Viehmann: remove code copy of getpass
[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,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>
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, getpass
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
350 # Connect to the ldap server
351 l = connectLDAP()
352 if (BindUser != ""):
353    Password = getpass.getpass(BindUser + "'s password: ")
354    UserDn = "uid=" + BindUser + "," + BaseDn
355 else:
356    Password = ""
357    UserDn = ""
358 try:
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']
363    sys.exit(1)
364
365 # Enable changing of supplementary gid's
366 if (RootMode == 1):
367    # Items that root can edit
368    list = ["supplementaryGid","allowedHost","member"];
369    Count = 0;
370    for x in list:
371       AttrInfo[x][1] = 200 + Count;
372       OrderedIndex[AttrInfo[x][1]] = [AttrInfo[x][0], "",x];
373       OrigOrderedIndex[AttrInfo[x][1]] = [AttrInfo[x][0], "",x];
374       Count = Count + 1;
375
376 # Query the server for all of the attributes
377 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid=" + User);
378 if len(Attrs) == 0:
379    print "User",User,"was not found.";
380    sys.exit(0); 
381
382 # repeatedly show the account configuration
383 while(1):
384    ShowAttrs(Attrs[0]);
385    if (BindUser == ""):
386       sys.exit(0);
387
388    if RootMode == 1:
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";
395    print "   x) Exit";
396    
397    # Prompt
398    Response = raw_input("Change? ");
399    if (Response == "x" or Response == "X" or Response == "q" or 
400        Response == "quit" or Response == "exit"):
401       break;
402
403    # Change who we are looking at
404    if (Response == 'u' or Response == 'U'):
405       NewUser = raw_input("User? ");
406       if NewUser == "":
407          continue;
408       NAttrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid=" + NewUser);
409       if len(NAttrs) == 0:
410          print "User",NewUser,"was not found.";
411          continue;
412       Attrs = NAttrs;
413       User = NewUser;
414       UserDn = "uid=" + User + "," + BaseDn;
415       OrderedIndex = copy.deepcopy(OrigOrderedIndex);
416       continue;
417
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!";
423
424       Pass1 = getpass.getpass(User + "'s new password: ")
425       Pass2 = getpass.getpass(User + "'s new password again: ")
426       if Pass1 != Pass2:
427          print "Passwords did not match";
428          raw_input("Press a key");
429          continue;
430
431       try:
432          Pass = HashPass(Pass1);
433       except:
434          print "%s: %s\n" %(sys.exc_type,sys.exc_value);
435          raw_input("Press a key");
436          continue;
437
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];
445       continue;
446
447    # retire DD
448    if Response == 'r' and RootMode == 1:
449       if Attrs[0][1].has_key("accountStatus") == 0:
450         curStatus = "<not set>"
451       else:
452         curStatus = Attrs[0][1]["accountStatus"][0]
453       if Attrs[0][1].has_key("accountComment") == 0:
454         curComment = "<not set>"
455       else:
456         curComment = Attrs[0][1]["accountComment"][0]
457       print "\n\nCurrent status is %s"%curStatus
458       print "Current comment is %s\n"%curComment
459
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")
469          if Resp == "1":
470            newstatus = "retiring %s"%(time.strftime("%Y-%m-%d"))
471          else:
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]
475
476          Resp2 = raw_input("Optional RT ticket number? ")
477          if (Resp2 != ''):
478            comment = "RT#%s"%(Resp2)
479            l.modify_s(UserDn,[(ldap.MOD_REPLACE,"accountComment",comment)])
480            Attrs[0][1]["accountComment"] = [comment]
481       elif Resp == "3":
482          Lock(UserDn, Attrs)
483          newstatus = "memorial"
484          l.modify_s(UserDn,[(ldap.MOD_REPLACE,"accountStatus",newstatus)])
485          Attrs[0][1]["accountStatus"] = [newstatus]
486       elif Resp == "4":
487          newstatus = "active"
488          l.modify_s(UserDn,[(ldap.MOD_REPLACE,"accountStatus",newstatus)])
489          Attrs[0][1]["accountStatus"] = [newstatus]
490
491       continue;
492
493
494    # Randomize password
495    if Response == 'R' and RootMode == 1:
496       Resp = raw_input("Randomize Users Password? [no/yes]");
497       if Resp != "yes":
498          continue;
499          
500       # Generate a random password
501       try:
502          Password = GenPass();
503          Pass = HashPass(Password);
504       except:
505          print "%s: %s\n" %(sys.exc_type,sys.exc_value);
506          raw_input("Press a key");
507          continue;
508          
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];
516       continue;
517
518    # Lock account
519    if Response == 'L' and RootMode == 1:
520       Resp = raw_input("Really lock account? [no/yes]");
521       if Resp != "yes":
522          continue;
523
524       print "Setting password..";
525       Lock(UserDn, Attrs)
526       continue;
527
528    # Handle changing an arbitary value
529    if (Response == "a"):
530       Attr = raw_input("Attr? ");
531       ChangeAttr(Attrs[0],Attr);
532       continue;
533
534    # Convert the integer response
535    try:
536       ID = int(Response);
537       if (not OrderedIndex.has_key(ID) or (ID > 100 and RootMode == 0)):
538          raise ValueError;
539    except ValueError:
540       print "Invalid";
541       continue;
542
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]);