DSA key support
[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 import string, time, os, pwd, sys, getopt, ldap, crypt, whrandom, readline, copy;
21 from userdir_ldap import *;
22
23 RootMode = 0;
24 AttrInfo = {"cn": ["First Name", 101],
25             "mn": ["Middle Name", 102],
26             "sn": ["Surname", 103],
27             "c": ["Country Code",1],
28             "l": ["Locality",2],
29             "ou": ["Membership",0],
30             "facsimiletelephonenumber": ["Fax Phone Number",3],
31             "telephonenumber": ["Phone Number",4],
32             "postaladdress": ["Mailing Address",5],
33             "postalcode": ["Postal Code",6],
34             "uid": ["Unix User ID",0],
35             "loginshell": ["Unix Shell",7],
36             "supplementarygid": ["Unix Groups",0],
37             "allowedhosts": ["Host ACL",0],
38             "member": ["LDAP Group",0],
39             "emailforward": ["Email Forwarding",8],
40             "ircnick": ["IRC Nickname",9],
41             "onvacation": ["Vacation Message",10],
42             "labeledurl": ["Home Page",11],
43             "latitude": ["Latitude",12],
44             "longitude": ["Longitude",13],
45             "icquin": ["ICQ UIN",14],
46             "privatesub": ["Debian-Private",15],
47             "comment": ["Comment",116],
48             "userpassword": ["Crypted Password",117],
49             "dnszoneentry": ["d.net Entry",118]};
50
51 AttrPrompt = {"cn": ["Common name or first name"],
52               "mn": ["Middle name (or initial if it ends in a dot)"],
53               "sn": ["Surname or last name"],
54               "c": ["ISO 2 letter country code, such as US, DE, etc"],
55               "l": ["City name, State/Provice (Locality)\n e.g. Dallas, Texas"],
56               "facsimiletelephonenumber": ["Fax phone number, with area code and country code"],
57               "telephonenumber": ["Voice phone number"],
58               "postaladdress": ["Complete mailing address including postal codes and country designations\nSeperate lines using a $ character"],
59               "postalcode": ["Postal Code or Zip Code"],
60               "loginshell": ["Login shell with full path (no check is done for validity)"],
61               "emailforward": ["EMail address to send all mail to or blank to disable"],
62               "ircnick": ["IRC nickname if you use IRC"],
63               "onvacation": ["A message if on vaction, indicating the time of departure and return"],
64               "userpassword": ["The users Crypt'd password"],
65               "comment": ["Admin Comment about the account"],
66               "supplementarygid": ["Groups the user is in"],
67               "allowedhosts": ["Grant access to certain hosts"],
68               "privatesub": ["Debian-Private mailing list subscription"],
69               "member": ["LDAP Group Member for slapd ACLs"],
70               "latitude": ["XEarth latitude in ISO 6709 format - see /usr/share/zoneinfo/zone.tab or etak.com"],
71               "longitude": ["XEarth latitude in ISO 6709 format - see /usr/share/zoneinfo/zone.tab or etak.com"],
72               "dnszoneentry": ["DNS Zone fragment associated this this user"],
73               "labeledurl": ["Web home page"],
74               "icquin": ["ICQ UIN Number"]};
75
76 # Create a map of IDs to desc,value,attr
77 OrderedIndex = {};
78 for at in AttrInfo.keys():
79    if (AttrInfo[at][1] != 0):
80       OrderedIndex[AttrInfo[at][1]] = [AttrInfo[at][0], "", at];
81 OrigOrderedIndex = copy.deepcopy(OrderedIndex);
82
83 # Show shadow information
84 def PrintShadow(Attrs):
85    Changed = int(GetAttr(Attrs,"shadowlastchange","0"));
86    MinDays = int(GetAttr(Attrs,"shadowmin","0"));
87    MaxDays = int(GetAttr(Attrs,"shadowmax","0"));
88    WarnDays = int(GetAttr(Attrs,"shadowwarning","0"));
89    InactDays = int(GetAttr(Attrs,"shadowinactive","0"));
90    Expire = int(GetAttr(Attrs,"shadowexpire","0"));
91
92    print "%-24s:" % ("Password last changed"),
93    print time.strftime("%a %d/%m/%Y %Z",time.localtime(Changed*24*60*60));
94    if (Expire > 0):
95       print "%-24s:" % ("Account expires on"),
96       print time.strftime("%a %d/%m/%Y %Z",time.localtime(Expire*24*60*60));
97    if (InactDays >= 0 and MaxDays < 99999):
98       print "Account aging is active, you must change your password every", MaxDays, "days."
99
100 # Print out the automatic time stamp information
101 def PrintModTime(Attrs):
102    Stamp = GetAttr(Attrs,"modifytimestamp","");
103    if len(Stamp) >= 13:
104       Time = (int(Stamp[0:4]),int(Stamp[4:6]),int(Stamp[6:8]),
105               int(Stamp[8:10]),int(Stamp[10:12]),int(Stamp[12:14]),0,0,-1);
106       print "%-24s:" % ("Record last modified on"), time.strftime("%a %d/%m/%Y %X UTC",Time),
107       print "by",ldap.explode_dn(GetAttr(Attrs,"modifiersname"),1)[0];
108
109    Stamp = GetAttr(Attrs,"createtimestamp","");
110    if len(Stamp) >= 13:
111       Time = (int(Stamp[0:4]),int(Stamp[4:6]),int(Stamp[6:8]),
112               int(Stamp[8:10]),int(Stamp[10:12]),int(Stamp[12:14]),0,0,-1);
113       print "%-24s:" % ("Record created on"), time.strftime("%a %d/%m/%Y %X UTC",Time);
114
115 # Print the PGP key for a user
116 def PrintKeys(Attrs):
117    if Attrs[1].has_key("keyfingerprint") == 0:
118       return;
119    First = 0;
120    for x in Attrs[1]["keyfingerprint"]:
121       if First == 0:
122          print "%-24s:" % ("PGP/GPG Key Fingerprints"),
123          First = 1;
124       else:
125          print "%-24s:" % (""),
126       print FormatPGPKey(x);
127
128 # Print the SSH RSA Authentication keys for a user
129 def PrintSshRSAKeys(Attrs):
130    if Attrs[1].has_key("sshrsaauthkey") == 0:
131       return;
132    First = 0;
133    for x in Attrs[1]["sshrsaauthkey"]:
134       if First == 0:
135          print "%-24s:" % ("SSH RSA Auth Keys"),
136          First = 1;
137       else:
138          print "%-24s:" % (""),
139
140       print FormatSSHAuth(x);
141       
142 # Print the SSH RSA Authentication keys for a user
143 def PrintSshDSAKeys(Attrs):
144    if Attrs[1].has_key("sshdsaauthkey") == 0:
145       return;
146    First = 0;
147    for x in Attrs[1]["sshdsaauthkey"]:
148       if First == 0:
149          print "%-24s:" % ("SSH DSA Auth Keys"),
150          First = 1;
151       else:
152          print "%-24s:" % (""),
153
154       print FormatSSH2Auth(x);
155       
156 # Display all of the attributes in a numbered list
157 def ShowAttrs(Attrs):
158    print;
159    print EmailAddress(Attrs);   
160    PrintModTime(Attrs);
161    PrintShadow(Attrs);
162    PrintKeys(Attrs);
163    PrintSshRSAKeys(Attrs);
164    PrintSshDSAKeys(Attrs);
165
166    for at in Attrs[1].keys():
167       if AttrInfo.has_key(at):
168          if AttrInfo[at][1] == 0:
169             print "      %-18s:" % (AttrInfo[at][0]),
170             for x in Attrs[1][at]:
171                print "'%s'" % (x),
172             if at == "uid":
173                print "(id=%s, gid=%s)" % (GetAttr(Attrs,"uidnumber","-1"),GetAttr(Attrs,"gidnumber","-1")),
174             print;
175          else:
176             OrderedIndex[AttrInfo[at][1]][1] = Attrs[1][at];
177                                        
178    Keys = OrderedIndex.keys();
179    Keys.sort();
180    for at in Keys:
181       if at < 100 or RootMode != 0:
182          print " %3u) %-18s: " % (at,OrderedIndex[at][0]),
183          for x in OrderedIndex[at][1]:
184             print "'%s'" % (re.sub('[\n\r]','?',x)),
185          print;
186
187 # Change a single attribute
188 def ChangeAttr(Attrs,Attr):
189    if (Attr == "supplementarygid" or Attr == "allowedhosts" or \
190        Attr == "member" or Attr == "dnszoneentry"):
191       return MultiChangeAttr(Attrs,Attr);
192
193    print "Old value: '%s'" % (GetAttr(Attrs,Attr,""));
194    print "Press enter to leave unchanged and a single space to set to empty";
195    NewValue = raw_input("New? ");
196   
197    # Empty string
198    if (NewValue == ""):
199       print "Leaving unchanged.";
200       return;
201
202    # Single space designates delete, trap the delete error
203    if (NewValue == " "):
204       print "Deleting.",;
205       try:
206          l.modify_s(UserDn,[(ldap.MOD_DELETE,Attr,None)]);
207       except ldap.NO_SUCH_ATTRIBUTE:
208          pass;
209
210       print;
211       Attrs[1][Attr] = [""];
212       return;
213
214    # Set a new value
215    print "Setting.",;
216    l.modify_s(UserDn,[(ldap.MOD_REPLACE,Attr,NewValue)]);
217    Attrs[1][Attr] = [NewValue];
218    print;
219
220 def MultiChangeAttr(Attrs,Attr):
221    # Make sure that we have an entry
222    if not Attrs[1].has_key(Attr):
223       Attrs[1][Attr] = [];
224
225    Attrs[1][Attr].sort();
226    print "Old values: ",Attrs[1][Attr];
227
228    Mode = string.upper(raw_input("[D]elete or [A]dd? "));
229    if (Mode != 'D' and Mode != 'A'):
230       return;
231
232    NewValue = raw_input("Value? ");
233    # Empty string
234    if (NewValue == ""):
235       print "Leaving unchanged.";
236       return;
237    
238    # Delete   
239    if (Mode == "D"):
240       print "Deleting.",;
241       try:
242          l.modify_s(UserDn,[(ldap.MOD_DELETE,Attr,NewValue)]);
243       except ldap.NO_SUCH_ATTRIBUTE:
244          print "Failed";
245
246       print;
247       Attrs[1][Attr].remove(NewValue);
248       return;
249
250    # Set a new value
251    print "Setting.",;
252    l.modify_s(UserDn,[(ldap.MOD_ADD,Attr,NewValue)]);
253    Attrs[1][Attr].append(NewValue);
254    print;
255
256 # Main program starts here
257 User = pwd.getpwuid(os.getuid())[0];
258 BindUser = User;
259 # Process options
260 (options, arguments) = getopt.getopt(sys.argv[1:], "nu:c:a:r")
261 for (switch, val) in options:
262    if (switch == '-u'):
263       User = val;
264    elif (switch == '-a'):
265       BindUser = val;
266    elif (switch == '-c'):
267       BindUser = val;
268       User = val;
269    elif (switch == '-r'):
270       RootMode = 1;
271    elif (switch == '-n'):
272       BindUser = "";
273
274 if (BindUser != ""):
275    print "Accessing LDAP entry for '" + User + "'",
276 if (BindUser != User):
277    if (BindUser != ""):
278       print "as '" + BindUser + "'";
279 else:
280    print;
281 if (BindUser != ""):
282    Password = getpass(BindUser + "'s password: ");
283
284 # Connect to the ldap server
285 l = ldap.open(LDAPServer);
286 UserDn = "uid=" + BindUser + "," + BaseDn;
287 if (BindUser != ""):
288    l.simple_bind_s(UserDn,Password);
289 else:
290    l.simple_bind_s("","");
291 UserDn = "uid=" + User + "," + BaseDn;
292
293 # Enable changing of supplementary gid's
294 if (RootMode == 1):
295    # Items that root can edit
296    list = ["supplementarygid","allowedhosts","member"];
297    Count = 0;
298    for x in list:
299       AttrInfo[x][1] = 200 + Count;
300       OrderedIndex[AttrInfo[x][1]] = [AttrInfo[x][0], "",x];
301       OrigOrderedIndex[AttrInfo[x][1]] = [AttrInfo[x][0], "",x];
302       Count = Count + 1;
303
304 # Query the server for all of the attributes
305 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid=" + User);
306 if len(Attrs) == 0:
307    print "User",User,"was not found.";
308    sys.exit(0); 
309
310 # repeatedly show the account configuration
311 while(1):
312    ShowAttrs(Attrs[0]);
313    if (BindUser == ""):
314       sys.exit(0);
315
316    if RootMode == 1:
317       print "   a) Arbitary Change";
318       print "   R) Randomize Password";
319    print "   p) Change Password";
320    print "   u) Switch Users";
321    print "   x) Exit";
322    
323    # Prompt
324    Response = raw_input("Change? ");
325    if (Response == "x" or Response == "X" or Response == "q" or 
326        Response == "quit" or Response == "exit"):
327       break;
328
329    # Change who we are looking at
330    if (Response == 'u' or Response == 'U'):
331       NewUser = raw_input("User? ");
332       if NewUser == "":
333          continue;
334       NAttrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid=" + NewUser);
335       if len(NAttrs) == 0:
336          print "User",NewUser,"was not found.";
337          continue;
338       Attrs = NAttrs;
339       User = NewUser;
340       UserDn = "uid=" + User + "," + BaseDn;
341       OrderedIndex = copy.deepcopy(OrigOrderedIndex);
342       continue;
343
344    # Handle changing the password
345    if (Response == "p"):
346       print "Please enter a new password. Your password can be of unlimited length,";
347       print "contain spaces and other special characters. No checking is done on the";
348       print "strength of the passwords so pick good ones please!";
349
350       Pass1 = getpass(User + "'s new password: ");
351       Pass2 = getpass(User + "'s new password again: ");
352       if Pass1 != Pass2:
353          print "Passwords did not match";
354          raw_input("Press a key");
355          continue;
356
357       try:
358          Pass = HashPass(Pass1);
359       except:
360          print "%s: %s\n" %(sys.exc_type,sys.exc_value);
361          raw_input("Press a key");
362          continue;
363
364       print "Setting password..";
365       Pass = "{crypt}" + Pass;
366       l.modify_s(UserDn,[(ldap.MOD_REPLACE,"userpassword",Pass)]);
367       Attrs[0][1]["userpassword"] = [Pass];
368       continue;
369
370    # Randomize password
371    if Response == 'R' and RootMode == 1:
372       Resp = raw_input("Randomize Users Password? [no/yes]");
373       if Resp != "yes":
374          continue;
375          
376       # Generate a random password
377       try:
378          Password = GenPass();
379          Pass = HashPass(Password);
380       except:
381          print "%s: %s\n" %(sys.exc_type,sys.exc_value);
382          raw_input("Press a key");
383          continue;
384          
385       print "Setting password..";
386       Pass = "{crypt}" + Pass;
387       l.modify_s(UserDn,[(ldap.MOD_REPLACE,"userpassword",Pass)]);
388       Attrs[0][1]["userpassword"] = [Pass];
389       continue;
390
391    # Handle changing an arbitary value
392    if (Response == "a"):
393       Attr = raw_input("Attr? ");
394       ChangeAttr(Attrs[0],Attr);
395       continue;
396
397    # Convert the integer response
398    try:
399       ID = int(Response);
400       if (not OrderedIndex.has_key(ID) or (ID > 100 and RootMode == 0)):
401          raise ValueError;
402    except ValueError:
403       print "Invalid";
404       continue;
405
406    # Print the what to do prompt
407    print "Changing LDAP entry '%s' (%s)" % (OrderedIndex[ID][0],OrderedIndex[ID][2]);
408    print AttrPrompt[OrderedIndex[ID][2]][0];
409    ChangeAttr(Attrs[0],OrderedIndex[ID][2]);