Make ud-host do allowedGroups, exportOptions
[mirror/userdir-ldap.git] / ud-host
1 #!/usr/bin/env python
2 # -*- mode: python -*-
3
4 #   Copyright (c) 2000-2001  Jason Gunthorpe <jgg@debian.org>
5 #   Copyright (c) 2001       Ryan Murray <rmurray@debian.org>
6 #   Copyright (c) 2003       James Troup <troup@debian.org>
7 #   Copyright (c) 2004-2005  Joey Schulze <joey@infodrom.org>
8 #
9 #   This program is free software; you can redistribute it and/or modify
10 #   it under the terms of the GNU General Public License as published by
11 #   the Free Software Foundation; either version 2 of the License, or
12 #   (at your option) any later version.
13 #
14 #   This program is distributed in the hope that it will be useful,
15 #   but WITHOUT ANY WARRANTY; without even the implied warranty of
16 #   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 #   GNU General Public License for more details.
18 #
19 #   You should have received a copy of the GNU General Public License
20 #   along with this program; if not, write to the Free Software
21 #   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
22
23 # This script is an interactive way to manipulate fields in the LDAP directory.
24 # When run it connects to the directory using the current users ID and fetches
25 # all the attributes for the first machine. It then formats them nicely and
26 # allows the user to change them.
27 #
28 #  Usage: userinfo -a <user> -u <user> -c <user> -r
29 #    -a    Set the authentication user (the user whose password you are
30 #          going to enter)
31 #    -h    Set the host to display
32 #    -l    list all hosts and their status
33 #    -f    list all SSH fingerprints
34
35 import time, os, pwd, sys, getopt, ldap, crypt, readline, copy;
36 from tempfile import mktemp
37 from os import O_CREAT, O_EXCL, O_WRONLY
38 from userdir_ldap import *;
39
40 RootMode = 0;
41 AttrInfo = {"description": ["Machine Descr.", 1],
42             "hostname": ["Host names", 2],
43             "status": ["Status", 3],
44             "l": ["Location", 4],
45             "sponsor": ["Sponsors", 5],
46             "distribution": ["Distribution", 6],
47             "access": ["Access", 7],
48             "admin": ["Admin", 8],
49             "architecture": ["Architecture", 9],
50             "machine": ["Machine Hardware", 10],
51             "memory": ["Memory", 11],
52             "disk": ["Disk", 12],
53             "physicalHost": ["Physical Host", 13],
54             "sshRSAHostKey": ["SSH Host Keys", 14],
55             "bandwidth": ["Bandwidth", 15],
56             "purpose": ["Purposes", 16],
57             "allowedGroups": ["Groups", 17],
58             "exportOptions": ["Export-Opts", 18],
59             }
60
61 AttrPrompt = {"description": ["Purpose of the machine"],
62               "hostname": ["The hostnames for the box (ipv4/ipv6)"],
63               "status": ["Blank if Up, explaination if not"],
64               "l": ["Physical location"],
65               "sponsor": ["Sponsors and their URLs"],
66               "distribution": ["The distribution version"],
67               "access": ["all, developer only, restricted"],
68               "admin": ["Admin email address"],
69               "architecture": ["Debian Architecture string"],
70               "machine": ["Hardware description"],
71               "memory": ["Installed RAM"],
72               "disk": ["Disk Space, RAID levels, etc"],
73               "physicalHost": ["The box hosting this virtual server"],
74               "sshRSAHostKey": ["A copy of /etc/ssh/ssh_*host_key.pub"],
75               "bandwidth": ["Available outbound"],
76               "purpose": ["The purposes of this host"],
77               "allowedGroups": ["allowed Groups on this host"],
78               "exportOptions": ["additional export options"],
79               };
80
81 # Create a map of IDs to desc,value,attr
82 OrderedIndex = {};
83 for at in AttrInfo.keys():
84    if (AttrInfo[at][1] != 0):
85       OrderedIndex[AttrInfo[at][1]] = [AttrInfo[at][0], "", at];
86 OrigOrderedIndex = copy.deepcopy(OrderedIndex);
87
88 # Print out the automatic time stamp information
89 def PrintModTime(Attrs):
90    Stamp = GetAttr(Attrs,"modifyTimestamp","");
91    if len(Stamp) >= 13:
92       Time = (int(Stamp[0:4]),int(Stamp[4:6]),int(Stamp[6:8]),
93               int(Stamp[8:10]),int(Stamp[10:12]),int(Stamp[12:14]),0,0,-1);
94       print "%-24s:" % ("Record last modified on"), time.strftime("%a %d/%m/%Y %X UTC",Time),
95       print "by",ldap.explode_dn(GetAttr(Attrs,"modifiersName"),1)[0];
96
97    Stamp = GetAttr(Attrs,"createTimestamp","");
98    if len(Stamp) >= 13:
99       Time = (int(Stamp[0:4]),int(Stamp[4:6]),int(Stamp[6:8]),
100               int(Stamp[8:10]),int(Stamp[10:12]),int(Stamp[12:14]),0,0,-1);
101       print "%-24s:" % ("Record created on"), time.strftime("%a %d/%m/%Y %X UTC",Time);
102
103 # Display all of the attributes in a numbered list
104 def ShowAttrs(Attrs):
105    print;
106    PrintModTime(Attrs);
107
108    for at in Attrs[1].keys():
109       if AttrInfo.has_key(at):
110          if AttrInfo[at][1] == 0:
111             print "      %-18s:" % (AttrInfo[at][0]),
112             for x in Attrs[1][at]:
113                print "'%s'" % (x),
114             print;
115          else:
116             OrderedIndex[AttrInfo[at][1]][1] = Attrs[1][at];
117
118    Keys = OrderedIndex.keys();
119    Keys.sort();
120    for at in Keys:
121       if at < 100 or RootMode != 0:
122          print " %3u) %-18s: " % (at,OrderedIndex[at][0]),
123          for x in OrderedIndex[at][1]:
124             print "'%s'" % (re.sub('[\n\r]','?',x)),
125          print;
126
127 def Overview(Attrs):
128    """Display a one-line overview for a given host"""
129    for i in ['host','architecture','distribution','access','status']:
130       if i not in Attrs[1].keys():
131          Attrs[1][i] = ['']
132    print "%-12s  %-10s  %-38s  %-25s %s" % (\
133       Attrs[1]['host'][0], \
134       Attrs[1]['architecture'][0], \
135       Attrs[1]['distribution'][0], \
136       Attrs[1]['access'][0], \
137       Attrs[1]['status'][0])
138
139 # Change a single attribute
140 def ChangeAttr(Attrs,Attr):
141    if (Attr in ["sponsor", "sshRSAHostKey", "purpose", "allowedGroups", "exportOptions"]):
142       return MultiChangeAttr(Attrs,Attr);
143
144    print "Old value: '%s'" % (GetAttr(Attrs,Attr,""));
145    print "Press enter to leave unchanged and a single space to set to empty";
146    NewValue = raw_input("New? ");
147
148    # Empty string
149    if (NewValue == ""):
150       print "Leaving unchanged.";
151       return;
152
153    # Single space designates delete, trap the delete error
154    if (NewValue == " "):
155       print "Deleting.",;
156       try:
157          l.modify_s(HostDn,[(ldap.MOD_DELETE,Attr,None)]);
158       except ldap.NO_SUCH_ATTRIBUTE:
159          pass;
160
161       print;
162       Attrs[1][Attr] = [""];
163       return;
164
165    # Set a new value
166    print "Setting.",;
167    l.modify_s(HostDn,[(ldap.MOD_REPLACE,Attr,NewValue)]);
168    Attrs[1][Attr] = [NewValue];
169    print;
170
171 def MultiChangeAttr(Attrs,Attr):
172    # Make sure that we have an entry
173    if not Attrs[1].has_key(Attr):
174       Attrs[1][Attr] = [];
175
176    Attrs[1][Attr].sort();
177    print "Old values: ",Attrs[1][Attr];
178
179    Mode = raw_input("[D]elete or [A]dd? ").upper()
180    if (Mode != 'D' and Mode != 'A'):
181       return;
182
183    NewValue = raw_input("Value? ");
184    # Empty string
185    if (NewValue == ""):
186       print "Leaving unchanged.";
187       return;
188
189    # Delete
190    if (Mode == "D"):
191       print "Deleting.",;
192       try:
193          l.modify_s(HostDn,[(ldap.MOD_DELETE,Attr,NewValue)]);
194       except ldap.NO_SUCH_ATTRIBUTE:
195          print "Failed";
196
197       print;
198       Attrs[1][Attr].remove(NewValue);
199       return;
200
201    # Set a new value
202    print "Setting.",;
203    l.modify_s(HostDn,[(ldap.MOD_ADD,Attr,NewValue)]);
204    Attrs[1][Attr].append(NewValue);
205    print;
206
207 def CalcTempFile():
208    unique = 0
209    while unique == 0:
210       name = mktemp()
211       try:
212          fd = os.open(name, O_CREAT | O_EXCL | O_WRONLY, 0600)
213       except OSError:
214          continue
215       os.close(fd)
216       unique = 1
217    return name
218
219
220 # Main program starts here
221 User = pwd.getpwuid(os.getuid())[0];
222 BindUser = User;
223 ListMode = 0
224 FingerPrints = 0
225 Host = None
226 # Process options
227 try:
228    (options, arguments) = getopt.getopt(sys.argv[1:], "nh:a:rlf")
229 except getopt.GetoptError, data:
230    print data
231    sys.exit(1)
232
233 for (switch, val) in options:
234    if (switch == '-h'):
235       Host = val;
236    elif (switch == '-a'):
237       BindUser = val;
238    elif (switch == '-r'):
239       RootMode = 1;
240    elif (switch == '-n'):
241       BindUser = "";
242    elif (switch == '-l'):
243       BindUser = "";
244       ListMode = 1
245    elif (switch == '-f'):
246       BindUser = "";
247       FingerPrints = 1
248
249 if (BindUser != ""):
250    l = passwdAccessLDAP(BaseDn, BindUser)
251 else:
252    l = connectLDAP()
253    l.simple_bind_s("","")
254
255 if ListMode == 1:
256    Attrs = l.search_s(HostBaseDn,ldap.SCOPE_ONELEVEL,"host=*")
257    hosts = []
258    for hAttrs in Attrs:
259       hosts.append(hAttrs[1]['host'][0])
260    hosts.sort()
261
262    print "%-12s  %-10s  %-38s  %-25s %s" % ("Host name","Arch","Distribution","Access","Status")
263    print "-"*115
264    for host in hosts:
265       for hAttrs in Attrs:
266          if host == hAttrs[1]['host'][0]:
267             Overview(hAttrs)
268    sys.exit(0)
269 elif FingerPrints == 1:
270    if Host is not None:
271       Attrs = l.search_s(HostBaseDn,ldap.SCOPE_ONELEVEL,"host=" + Host)
272    else:
273       Attrs = l.search_s(HostBaseDn,ldap.SCOPE_ONELEVEL,"host=*")
274    hosts = []
275    for hAttrs in Attrs:
276       hosts.append(hAttrs[1]['host'][0])
277    hosts.sort()
278
279    tmpfile = CalcTempFile()
280    for host in hosts:
281       for hAttrs in Attrs:
282          if host == hAttrs[1]['host'][0]:
283             if 'sshRSAHostKey' in hAttrs[1].keys():
284                for key in hAttrs[1]['sshRSAHostKey']:
285                   tmp = open(tmpfile, 'w')
286                   tmp.write(key + '\n')
287                   tmp.close()
288                   fp = os.popen('/usr/bin/ssh-keygen -l -f ' + tmpfile, "r")
289                   input = fp.readline()
290                   fp.close()
291                   fingerprint = input.split(' ')
292                   print "%s %s root@%s" % (fingerprint[0], fingerprint[1], host)
293    os.unlink(tmpfile)
294    sys.exit(0)
295
296 HostDn = "host=" + Host + "," + HostBaseDn;
297
298 # Query the server for all of the attributes
299 Attrs = l.search_s(HostBaseDn,ldap.SCOPE_ONELEVEL,"host=" + Host);
300 if len(Attrs) == 0:
301    print "Host",Host,"was not found.";
302    sys.exit(0);
303
304 # repeatedly show the account configuration
305 while(1):
306    ShowAttrs(Attrs[0]);
307    if (BindUser == ""):
308       sys.exit(0);
309
310    if RootMode == 1:
311       print "   a) Arbitary Change";
312    print "   n) New Host";
313    print "   d) Delete Host";
314    print "   u) Switch Hosts";
315    print "   x) Exit";
316
317    # Prompt
318    Response = raw_input("Change? ");
319    if (Response == "x" or Response == "X" or Response == "q" or
320        Response == "quit" or Response == "exit"):
321       break;
322
323    # Change who we are looking at
324    if (Response == 'u' or Response == 'U'):
325       NewHost = raw_input("Host? ");
326       if NewHost == "":
327          continue;
328       NAttrs = l.search_s(HostBaseDn,ldap.SCOPE_ONELEVEL,"host=" + NewHost);
329       if len(NAttrs) == 0:
330          print "Host",NewHost,"was not found.";
331          continue;
332       Attrs = NAttrs;
333       Host = NewHost;
334       HostDn = "host=" + Host + "," + HostBaseDn;
335       OrderedIndex = copy.deepcopy(OrigOrderedIndex);
336       continue;
337
338    # Create a new entry and change to it Change who we are looking at
339    if (Response == 'n' or Response == 'N'):
340       NewHost = raw_input("Host? ");
341       if NewHost == "":
342          continue;
343       NAttrs = l.search_s(HostBaseDn,ldap.SCOPE_ONELEVEL,"host=" + NewHost);
344       if len(NAttrs) != 0:
345          print "Host",NewHost,"already exists.";
346          continue;
347       NewHostName = raw_input("Hostname? ");
348       if NewHost == "":
349          continue;
350       Dn = "host=" + NewHost + "," + HostBaseDn;
351       l.add_s(Dn,[("host", NewHost),
352                   ("hostname", NewHostName),
353                   ("objectClass", ("top", "debianServer"))]);
354
355       # Switch
356       NAttrs = l.search_s(HostBaseDn,ldap.SCOPE_ONELEVEL,"host=" + NewHost);
357       if len(NAttrs) == 0:
358          print "Host",NewHost,"was not found.";
359          continue;
360       Attrs = NAttrs;
361       Host = NewHost;
362       HostDn = "host=" + Host + "," + HostBaseDn;
363       OrderedIndex = copy.deepcopy(OrigOrderedIndex);
364       continue;
365
366    # Handle changing an arbitary value
367    if (Response == "a"):
368       Attr = raw_input("Attr? ");
369       ChangeAttr(Attrs[0],Attr);
370       continue;
371
372    if (Response == 'd'):
373       Really = raw_input("Really (type yes)? ");
374       if Really != 'yes':
375           continue;
376       print "Deleting",HostDn;
377       l.delete_s(HostDn);
378       continue;
379
380    # Convert the integer response
381    try:
382       ID = int(Response);
383       if (not OrderedIndex.has_key(ID) or (ID > 100 and RootMode == 0)):
384          raise ValueError;
385    except ValueError:
386       print "Invalid";
387       continue;
388
389    # Print the what to do prompt
390    print "Changing LDAP entry '%s' (%s)" % (OrderedIndex[ID][0],OrderedIndex[ID][2]);
391    print AttrPrompt[OrderedIndex[ID][2]][0];
392    ChangeAttr(Attrs[0],OrderedIndex[ID][2]);