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