ud-mailgate: remove exception for münchen.debian.net
[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,2009 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             "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             "mailContentInspectionAction": ["mail C-I Action",25],
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],
85             };
86
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               "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               "mailContentInspectionAction": ["Content Inspection Action (reject, blackhole, markup)"],
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"],
123               };
124
125 # Create a map of IDs to desc,value,attr
126 OrderedIndex = {};
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);
131
132 for id in OrderedIndex:
133    if not AttrPrompt.has_key( OrderedIndex[id][2] ):
134       print "Warning: no AttrPrompt for %s"%(id)
135
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"));
144
145    print "%-24s:" % ("Password last changed"),
146    print time.strftime("%a %d/%m/%Y %Z",time.localtime(Changed*24*60*60));
147    if (Expire > 0):
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."
152
153 # Print out the automatic time stamp information
154 def PrintModTime(Attrs):
155    Stamp = GetAttr(Attrs,"modifyTimestamp","");
156    if len(Stamp) >= 13:
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];
161
162    Stamp = GetAttr(Attrs,"createTimestamp","");
163    if len(Stamp) >= 13:
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);
167
168 # Print the PGP key for a user
169 def PrintKeys(Attrs):
170    if Attrs[1].has_key("keyFingerPrint") == 0:
171       return;
172    First = 0;
173    for x in Attrs[1]["keyFingerPrint"]:
174       if First == 0:
175          print "%-24s:" % ("PGP/GPG Key Fingerprints"),
176          First = 1;
177       else:
178          print "%-24s:" % (""),
179       print FormatPGPKey(x);
180
181 # Print the SSH RSA Authentication keys for a user
182 def PrintSshRSAKeys(Attrs):
183    if Attrs[1].has_key("sshRSAAuthKey") == 0:
184       return;
185    First = 0;
186    for x in Attrs[1]["sshRSAAuthKey"]:
187       if First == 0:
188          print "%-24s:" % ("SSH Auth Keys"),
189          First = 1;
190       else:
191          print "%-24s:" % (""),
192
193       print FormatSSHAuth(x);
194       
195 # Display all of the attributes in a numbered list
196 def ShowAttrs(Attrs):
197    print;
198    print EmailAddress(Attrs);   
199    PrintModTime(Attrs);
200    PrintShadow(Attrs);
201    PrintKeys(Attrs);
202    PrintSshRSAKeys(Attrs);
203
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]:
209                print "'%s'" % (x),
210             if at == "uid":
211                print "(id=%s, gid=%s)" % (GetAttr(Attrs,"uidNumber","-1"),GetAttr(Attrs,"gidNumber","-1")),
212             print;
213          else:
214             OrderedIndex[AttrInfo[at][1]][1] = Attrs[1][at];
215                                        
216    Keys = OrderedIndex.keys();
217    Keys.sort();
218    for at in 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)),
223          print;
224
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);
231
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? ");
235   
236    # Empty string
237    if (NewValue == ""):
238       print "Leaving unchanged.";
239       return;
240
241    # Single space designates delete, trap the delete error
242    if (NewValue == " "):
243       print "Deleting.",;
244       try:
245          l.modify_s(UserDn,[(ldap.MOD_DELETE,Attr,None)]);
246       except ldap.NO_SUCH_ATTRIBUTE:
247          pass;
248
249       print;
250       Attrs[1][Attr] = [""];
251       return;
252
253    if (Attr == "mailGreylisting" or Attr == "mailCallout"):
254       if (NewValue.lower() != "true" and NewValue.lower() != "false"):
255          if (NewValue == "1"): NewValue = "true"
256          else:
257             if (NewValue == "0"): NewValue = "false"
258             else:
259                print "Need a boolean value"
260                return
261       NewValue = NewValue.upper()
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 UserDn = "uid=" + User + "," + BaseDn
353 if (BindUser != ""):
354    Password = getpass.getpass(BindUser + "'s password: ")
355    BindUserDn = "uid=" + BindUser + "," + BaseDn
356 else:
357    Password = ""
358    BindUserDn = ""
359 try:
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']
364    sys.exit(1)
365
366 # Enable changing of supplementary gid's
367 if (RootMode == 1):
368    # Items that root can edit
369    list = ["supplementaryGid","allowedHost","member"];
370    Count = 0;
371    for x in list:
372       AttrInfo[x][1] = 200 + Count;
373       OrderedIndex[AttrInfo[x][1]] = [AttrInfo[x][0], "",x];
374       OrigOrderedIndex[AttrInfo[x][1]] = [AttrInfo[x][0], "",x];
375       Count = Count + 1;
376
377 # Query the server for all of the attributes
378 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid=" + User);
379 if len(Attrs) == 0:
380    print "User",User,"was not found.";
381    sys.exit(0); 
382
383 # repeatedly show the account configuration
384 while(1):
385    ShowAttrs(Attrs[0]);
386    if (BindUser == ""):
387       sys.exit(0);
388
389    if RootMode == 1:
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";
396    print "   x) Exit";
397    
398    # Prompt
399    Response = raw_input("Change? ");
400    if (Response == "x" or Response == "X" or Response == "q" or 
401        Response == "quit" or Response == "exit"):
402       break;
403
404    # Change who we are looking at
405    if (Response == 'u' or Response == 'U'):
406       NewUser = raw_input("User? ");
407       if NewUser == "":
408          continue;
409       NAttrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid=" + NewUser);
410       if len(NAttrs) == 0:
411          print "User",NewUser,"was not found.";
412          continue;
413       Attrs = NAttrs;
414       User = NewUser;
415       UserDn = "uid=" + User + "," + BaseDn;
416       OrderedIndex = copy.deepcopy(OrigOrderedIndex);
417       continue;
418
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!";
424
425       Pass1 = getpass.getpass(User + "'s new password: ")
426       Pass2 = getpass.getpass(User + "'s new password again: ")
427       if Pass1 != Pass2:
428          print "Passwords did not match";
429          raw_input("Press a key");
430          continue;
431
432       try:
433          Pass = HashPass(Pass1);
434       except:
435          print "%s: %s\n" %(sys.exc_type,sys.exc_value);
436          raw_input("Press a key");
437          continue;
438
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];
446       continue;
447
448    # retire DD
449    if Response == 'r' and RootMode == 1:
450       if Attrs[0][1].has_key("accountStatus") == 0:
451         curStatus = "<not set>"
452       else:
453         curStatus = Attrs[0][1]["accountStatus"][0]
454       if Attrs[0][1].has_key("accountComment") == 0:
455         curComment = "<not set>"
456       else:
457         curComment = Attrs[0][1]["accountComment"][0]
458       print "\n\nCurrent status is %s"%curStatus
459       print "Current comment is %s\n"%curComment
460
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")
470          if Resp == "1":
471            newstatus = "retiring %s"%(time.strftime("%Y-%m-%d"))
472          else:
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]
476
477          Resp2 = raw_input("Optional RT ticket number? ")
478          if (Resp2 != ''):
479            comment = "RT#%s"%(Resp2)
480            l.modify_s(UserDn,[(ldap.MOD_REPLACE,"accountComment",comment)])
481            Attrs[0][1]["accountComment"] = [comment]
482       elif Resp == "3":
483          Lock(UserDn, Attrs)
484          newstatus = "memorial"
485          l.modify_s(UserDn,[(ldap.MOD_REPLACE,"accountStatus",newstatus)])
486          Attrs[0][1]["accountStatus"] = [newstatus]
487       elif Resp == "4":
488          newstatus = "active"
489          l.modify_s(UserDn,[(ldap.MOD_REPLACE,"accountStatus",newstatus)])
490          Attrs[0][1]["accountStatus"] = [newstatus]
491
492       continue;
493
494
495    # Randomize password
496    if Response == 'R' and RootMode == 1:
497       Resp = raw_input("Randomize Users Password? [no/yes]");
498       if Resp != "yes":
499          continue;
500          
501       # Generate a random password
502       try:
503          Password = GenPass();
504          Pass = HashPass(Password);
505       except:
506          print "%s: %s\n" %(sys.exc_type,sys.exc_value);
507          raw_input("Press a key");
508          continue;
509          
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];
517       continue;
518
519    # Lock account
520    if Response == 'L' and RootMode == 1:
521       Resp = raw_input("Really lock account? [no/yes]");
522       if Resp != "yes":
523          continue;
524
525       print "Setting password..";
526       Lock(UserDn, Attrs)
527       continue;
528
529    # Handle changing an arbitary value
530    if (Response == "a"):
531       Attr = raw_input("Attr? ");
532       ChangeAttr(Attrs[0],Attr);
533       continue;
534
535    # Convert the integer response
536    try:
537       ID = int(Response);
538       if (not OrderedIndex.has_key(ID) or (ID > 100 and RootMode == 0)):
539          raise ValueError;
540    except ValueError:
541       print "Invalid";
542       continue;
543
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]);