Document sshdistAuthKeysHost
[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             "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             "mailContentInspectionAction": ["mail C-I Action",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               "mailContentInspectionAction": ["Content Inspection Action (reject, blackhole, markup)"],
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) %-19s: " % (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 == "mailGreylisting" or Attr == "mailCallout"):
256       if (NewValue.lower() != "true" and NewValue.lower() != "false"):
257          if (NewValue == "1"): NewValue = "true"
258          else:
259             if (NewValue == "0"): NewValue = "false"
260             else:
261                print "Need a boolean value"
262                return
263       NewValue = NewValue.upper()
264
265    # Set a new value
266    print "Setting.",;
267    l.modify_s(UserDn,[(ldap.MOD_REPLACE,Attr,NewValue)]);
268    Attrs[1][Attr] = [NewValue];
269    print;
270
271 def MultiChangeAttr(Attrs,Attr):
272    # Make sure that we have an entry
273    if not Attrs[1].has_key(Attr):
274       Attrs[1][Attr] = [];
275
276    Attrs[1][Attr].sort();
277    print "Old values: ",Attrs[1][Attr];
278
279    Mode = raw_input("[D]elete or [A]dd? ").upper()
280    if (Mode != 'D' and Mode != 'A'):
281       return;
282
283    NewValue = raw_input("Value? ");
284    # Empty string
285    if (NewValue == ""):
286       print "Leaving unchanged.";
287       return;
288    
289    # Delete   
290    if (Mode == "D"):
291       print "Deleting.",;
292       try:
293          l.modify_s(UserDn,[(ldap.MOD_DELETE,Attr,NewValue)]);
294       except ldap.NO_SUCH_ATTRIBUTE:
295          print "Failed";
296
297       print;
298       Attrs[1][Attr].remove(NewValue);
299       return;
300
301    # Set a new value
302    print "Setting.",;
303    l.modify_s(UserDn,[(ldap.MOD_ADD,Attr,NewValue)]);
304    Attrs[1][Attr].append(NewValue);
305    print;
306
307 def Lock(UserDn, Attrs, DisableMail=True):
308    shadowLast = str(int(time.time()/24/60/60));
309    recs = [
310       (ldap.MOD_REPLACE,"userPassword","{crypt}*LK*"),
311       (ldap.MOD_REPLACE,"shadowLastChange",shadowLast),
312       (ldap.MOD_REPLACE,"shadowExpire","1")];
313    if DisableMail:
314       recs.append( (ldap.MOD_REPLACE,"mailDisableMessage","account locked") )
315       Attrs[0][1]["mailDisableMessage"] = ["account locked"];
316    l.modify_s(UserDn,recs);
317    Attrs[0][1]["userPassword"] = ["{crypt}*LK*"];
318    Attrs[0][1]["shadowLastChange"] = [shadowLast];
319    Attrs[0][1]["shadowExpire"] = ["1"];
320
321 # Main program starts here
322 User = pwd.getpwuid(os.getuid())[0];
323 BindUser = User;
324 # Process options
325 try:
326    (options, arguments) = getopt.getopt(sys.argv[1:], "nu:c:a:r")
327 except getopt.GetoptError, data:
328    print data
329    sys.exit(1)
330
331 for (switch, val) in options:
332    if (switch == '-u'):
333       User = val;
334    elif (switch == '-a'):
335       BindUser = val;
336    elif (switch == '-c'):
337       BindUser = val;
338       User = val;
339    elif (switch == '-r'):
340       RootMode = 1;
341    elif (switch == '-n'):
342       BindUser = "";
343
344 if (BindUser != ""):
345    print "Accessing LDAP entry for '" + User + "'",
346 if (BindUser != User):
347    if (BindUser != ""):
348       print "as '" + BindUser + "'";
349 else:
350    print;
351
352 # Connect to the ldap server
353 l = connectLDAP()
354 UserDn = "uid=" + User + "," + BaseDn
355 if (BindUser != ""):
356    Password = getpass.getpass(BindUser + "'s password: ")
357    BindUserDn = "uid=" + BindUser + "," + BaseDn
358 else:
359    Password = ""
360    BindUserDn = ""
361 try:
362    l.simple_bind_s(BindUserDn,Password)
363 except ldap.LDAPError,e:
364    print >> sys.stderr, "LDAP error:", e.args[0]['desc']
365    print >> sys.stderr, "           ", e.args[0]['info']
366    sys.exit(1)
367
368 # Enable changing of supplementary gid's
369 if (RootMode == 1):
370    # Items that root can edit
371    list = ["supplementaryGid","allowedHost","member"];
372    Count = 0;
373    for x in list:
374       AttrInfo[x][1] = 200 + Count;
375       OrderedIndex[AttrInfo[x][1]] = [AttrInfo[x][0], "",x];
376       OrigOrderedIndex[AttrInfo[x][1]] = [AttrInfo[x][0], "",x];
377       Count = Count + 1;
378
379 # Query the server for all of the attributes
380 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid=" + User);
381 if len(Attrs) == 0:
382    print "User",User,"was not found.";
383    sys.exit(0); 
384
385 # repeatedly show the account configuration
386 while(1):
387    ShowAttrs(Attrs[0]);
388    if (BindUser == ""):
389       sys.exit(0);
390
391    if RootMode == 1:
392       print "   a) Arbitary Change";
393       print "   r) retire developer";
394       print "   R) Randomize Password";
395       print "   L) Lock account and disable mail";
396    print "   p) Change Password";
397    print "   u) Switch Users";
398    print "   x) Exit";
399    
400    # Prompt
401    Response = raw_input("Change? ");
402    if (Response == "x" or Response == "X" or Response == "q" or 
403        Response == "quit" or Response == "exit"):
404       break;
405
406    # Change who we are looking at
407    if (Response == 'u' or Response == 'U'):
408       NewUser = raw_input("User? ");
409       if NewUser == "":
410          continue;
411       NAttrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid=" + NewUser);
412       if len(NAttrs) == 0:
413          print "User",NewUser,"was not found.";
414          continue;
415       Attrs = NAttrs;
416       User = NewUser;
417       UserDn = "uid=" + User + "," + BaseDn;
418       OrderedIndex = copy.deepcopy(OrigOrderedIndex);
419       continue;
420
421    # Handle changing the password
422    if (Response == "p"):
423       print "Please enter a new password. Your password can be of unlimited length,";
424       print "contain spaces and other special characters. No checking is done on the";
425       print "strength of the passwords so pick good ones please!";
426
427       Pass1 = getpass.getpass(User + "'s new password: ")
428       Pass2 = getpass.getpass(User + "'s new password again: ")
429       if Pass1 != Pass2:
430          print "Passwords did not match";
431          raw_input("Press a key");
432          continue;
433
434       try:
435          Pass = HashPass(Pass1);
436       except:
437          print "%s: %s\n" %(sys.exc_type,sys.exc_value);
438          raw_input("Press a key");
439          continue;
440
441       print "Setting password..";
442       Pass = "{crypt}" + Pass;
443       shadowLast = str(int(time.time()/24/60/60));
444       l.modify_s(UserDn,[(ldap.MOD_REPLACE,"userPassword",Pass),
445                          (ldap.MOD_REPLACE,"shadowLastChange",shadowLast)]);
446       Attrs[0][1]["userPassword"] = [Pass];
447       Attrs[0][1]["shadowLastChange"] = [shadowLast];
448       continue;
449
450    # retire DD
451    if Response == 'r' and RootMode == 1:
452       if Attrs[0][1].has_key("accountStatus") == 0:
453         curStatus = "<not set>"
454       else:
455         curStatus = Attrs[0][1]["accountStatus"][0]
456       if Attrs[0][1].has_key("accountComment") == 0:
457         curComment = "<not set>"
458       else:
459         curComment = Attrs[0][1]["accountComment"][0]
460       print "\n\nCurrent status is %s"%curStatus
461       print "Current comment is %s\n"%curComment
462
463       print "Set account to:"
464       print "  1) retiring (lock account but do not disable mail):"
465       print "  2) inactive (removed/emeritus/... - lock account and disable mail):"
466       print "  3) memorial (lock account and disable mail):"
467       print "  4) active (do not change other settings, you will have to deal with them)"
468       print "  q) return (no change)"
469       Resp = raw_input("Action? ")
470       if Resp == "1" or Resp == "2":
471          Lock(UserDn, Attrs, Resp == "2")
472          if Resp == "1":
473            newstatus = "retiring %s"%(time.strftime("%Y-%m-%d"))
474          else:
475            newstatus = "inactive %s"%(time.strftime("%Y-%m-%d"))
476          l.modify_s(UserDn,[(ldap.MOD_REPLACE,"accountStatus",newstatus)])
477          Attrs[0][1]["accountStatus"] = [newstatus]
478
479          Resp2 = raw_input("Optional RT ticket number? ")
480          if (Resp2 != ''):
481            comment = "RT#%s"%(Resp2)
482            l.modify_s(UserDn,[(ldap.MOD_REPLACE,"accountComment",comment)])
483            Attrs[0][1]["accountComment"] = [comment]
484       elif Resp == "3":
485          Lock(UserDn, Attrs)
486          newstatus = "memorial"
487          l.modify_s(UserDn,[(ldap.MOD_REPLACE,"accountStatus",newstatus)])
488          Attrs[0][1]["accountStatus"] = [newstatus]
489       elif Resp == "4":
490          newstatus = "active"
491          l.modify_s(UserDn,[(ldap.MOD_REPLACE,"accountStatus",newstatus)])
492          Attrs[0][1]["accountStatus"] = [newstatus]
493
494       continue;
495
496
497    # Randomize password
498    if Response == 'R' and RootMode == 1:
499       Resp = raw_input("Randomize Users Password? [no/yes]");
500       if Resp != "yes":
501          continue;
502          
503       # Generate a random password
504       try:
505          Password = GenPass();
506          Pass = HashPass(Password);
507       except:
508          print "%s: %s\n" %(sys.exc_type,sys.exc_value);
509          raw_input("Press a key");
510          continue;
511          
512       print "Setting password..";
513       Pass = "{crypt}" + Pass;
514       shadowLast = str(int(time.time()/24/60/60));
515       l.modify_s(UserDn,[(ldap.MOD_REPLACE,"userPassword",Pass),
516                          (ldap.MOD_REPLACE,"shadowLastChange",shadowLast)]);
517       Attrs[0][1]["userPassword"] = [Pass];
518       Attrs[0][1]["shadowLastChange"] = [shadowLast];
519       continue;
520
521    # Lock account
522    if Response == 'L' and RootMode == 1:
523       Resp = raw_input("Really lock account? [no/yes]");
524       if Resp != "yes":
525          continue;
526
527       print "Setting password..";
528       Lock(UserDn, Attrs)
529       continue;
530
531    # Handle changing an arbitary value
532    if (Response == "a"):
533       Attr = raw_input("Attr? ");
534       ChangeAttr(Attrs[0],Attr);
535       continue;
536
537    # Convert the integer response
538    try:
539       ID = int(Response);
540       if (not OrderedIndex.has_key(ID) or (ID > 100 and RootMode == 0)):
541          raise ValueError;
542    except ValueError:
543       print "Invalid";
544       continue;
545
546    # Print the what to do prompt
547    print "Changing LDAP entry '%s' (%s)" % (OrderedIndex[ID][0],OrderedIndex[ID][2]);
548    print AttrPrompt[OrderedIndex[ID][2]][0];
549    ChangeAttr(Attrs[0],OrderedIndex[ID][2]);