/mandos/trunk

To get this branch, use:
bzr branch http://bzr.recompile.se/loggerhead/mandos/trunk

« back to all changes in this revision

Viewing changes to mandos-monitor

  • Committer: teddy at bsnet
  • Date: 2011-03-15 19:15:24 UTC
  • Revision ID: teddy@fukt.bsnet.se-20110315191524-jc3ajgqu2za7dcly
* mandos: Use the new argparse library instead of optparse.
* debian/control (mandos): Depend on python (<=2.7) | python-argparse

Show diffs side-by-side

added added

removed removed

Lines of Context:
3
3
4
4
# Mandos Monitor - Control and monitor the Mandos server
5
5
6
 
# Copyright © 2009-2012 Teddy Hogeborn
7
 
# Copyright © 2009-2012 Björn Påhlsson
 
6
# Copyright © 2009-2011 Teddy Hogeborn
 
7
# Copyright © 2009-2011 Björn Påhlsson
8
8
9
9
# This program is free software: you can redistribute it and/or modify
10
10
# it under the terms of the GNU General Public License as published by
17
17
#     GNU General Public License for more details.
18
18
19
19
# You should have received a copy of the GNU General Public License
20
 
# along with this program.  If not, see
21
 
# <http://www.gnu.org/licenses/>.
 
20
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
22
21
23
 
# Contact the authors at <mandos@recompile.se>.
 
22
# Contact the authors at <mandos@fukt.bsnet.se>.
24
23
25
24
 
26
 
from __future__ import (division, absolute_import, print_function,
27
 
                        unicode_literals)
 
25
from __future__ import division, absolute_import, print_function, unicode_literals
28
26
 
29
27
import sys
30
28
import os
50
48
logging.getLogger('dbus.proxies').setLevel(logging.CRITICAL)
51
49
 
52
50
# Some useful constants
53
 
domain = 'se.recompile'
 
51
domain = 'se.bsnet.fukt'
54
52
server_interface = domain + '.Mandos'
55
53
client_interface = domain + '.Mandos.Client'
56
 
version = "1.5.3"
 
54
version = "1.3.0"
57
55
 
58
56
# Always run in monochrome mode
59
57
urwid.curses_display.curses.has_colors = lambda : False
88
86
        self.proxy = proxy_object # Mandos Client proxy object
89
87
        
90
88
        self.properties = dict()
91
 
        self.property_changed_match = (
92
 
            self.proxy.connect_to_signal("PropertyChanged",
93
 
                                         self.property_changed,
94
 
                                         client_interface,
95
 
                                         byte_arrays=True))
 
89
        self.proxy.connect_to_signal("PropertyChanged",
 
90
                                     self.property_changed,
 
91
                                     client_interface,
 
92
                                     byte_arrays=True)
96
93
        
97
94
        self.properties.update(
98
95
            self.proxy.GetAll(client_interface,
99
96
                              dbus_interface = dbus.PROPERTIES_IFACE))
100
97
 
101
 
        #XXX This breaks good super behaviour
 
98
        #XXX This break good super behaviour!
102
99
#        super(MandosClientPropertyCache, self).__init__(
103
100
#            *args, **kwargs)
104
101
    
108
105
        """
109
106
        # Update properties dict with new value
110
107
        self.properties[property] = value
111
 
    
112
 
    def delete(self, *args, **kwargs):
113
 
        self.property_changed_match.remove()
114
 
        super(MandosClientPropertyCache, self).__init__(
115
 
            *args, **kwargs)
116
108
 
117
109
 
118
110
class MandosClientWidget(urwid.FlowWidget, MandosClientPropertyCache):
132
124
        
133
125
        self._update_timer_callback_tag = None
134
126
        self._update_timer_callback_lock = 0
 
127
        self.last_checker_failed = False
135
128
        
136
129
        # The widget shown normally
137
130
        self._text_widget = urwid.Text("")
145
138
        
146
139
        last_checked_ok = isoformat_to_datetime(self.properties
147
140
                                                ["LastCheckedOK"])
 
141
        if last_checked_ok is None:
 
142
            self.last_checker_failed = True
 
143
        else:
 
144
            self.last_checker_failed = ((datetime.datetime.utcnow()
 
145
                                         - last_checked_ok)
 
146
                                        > datetime.timedelta
 
147
                                        (milliseconds=
 
148
                                         self.properties
 
149
                                         ["Interval"]))
148
150
        
149
 
        if self.properties ["LastCheckerStatus"] != 0:
 
151
        if self.last_checker_failed:
150
152
            self.using_timer(True)
151
153
        
152
154
        if self.need_approval:
153
155
            self.using_timer(True)
154
156
        
155
 
        self.match_objects = (
156
 
            self.proxy.connect_to_signal("CheckerCompleted",
157
 
                                         self.checker_completed,
158
 
                                         client_interface,
159
 
                                         byte_arrays=True),
160
 
            self.proxy.connect_to_signal("CheckerStarted",
161
 
                                         self.checker_started,
162
 
                                         client_interface,
163
 
                                         byte_arrays=True),
164
 
            self.proxy.connect_to_signal("GotSecret",
165
 
                                         self.got_secret,
166
 
                                         client_interface,
167
 
                                         byte_arrays=True),
168
 
            self.proxy.connect_to_signal("NeedApproval",
169
 
                                         self.need_approval,
170
 
                                         client_interface,
171
 
                                         byte_arrays=True),
172
 
            self.proxy.connect_to_signal("Rejected",
173
 
                                         self.rejected,
174
 
                                         client_interface,
175
 
                                         byte_arrays=True))
176
 
        #self.logger('Created client {0}'
177
 
        #            .format(self.properties["Name"]))
 
157
        self.proxy.connect_to_signal("CheckerCompleted",
 
158
                                     self.checker_completed,
 
159
                                     client_interface,
 
160
                                     byte_arrays=True)
 
161
        self.proxy.connect_to_signal("CheckerStarted",
 
162
                                     self.checker_started,
 
163
                                     client_interface,
 
164
                                     byte_arrays=True)
 
165
        self.proxy.connect_to_signal("GotSecret",
 
166
                                     self.got_secret,
 
167
                                     client_interface,
 
168
                                     byte_arrays=True)
 
169
        self.proxy.connect_to_signal("NeedApproval",
 
170
                                     self.need_approval,
 
171
                                     client_interface,
 
172
                                     byte_arrays=True)
 
173
        self.proxy.connect_to_signal("Rejected",
 
174
                                     self.rejected,
 
175
                                     client_interface,
 
176
                                     byte_arrays=True)
178
177
    
179
178
    def property_changed(self, property=None, value=None):
180
179
        super(self, MandosClientWidget).property_changed(property,
181
180
                                                         value)
182
181
        if property == "ApprovalPending":
183
182
            using_timer(bool(value))
184
 
        if property == "LastCheckerStatus":
185
 
            using_timer(value != 0)
186
 
            #self.logger('Checker for client {0} (command "{1}") was '
187
 
            #            ' successful'.format(self.properties["Name"],
188
 
            #                                 command))
189
 
    
 
183
        
190
184
    def using_timer(self, flag):
191
185
        """Call this method with True or False when timer should be
192
186
        activated or deactivated.
197
191
        else:
198
192
            self._update_timer_callback_lock -= 1
199
193
        if old == 0 and self._update_timer_callback_lock:
200
 
            # Will update the shown timer value every second
201
194
            self._update_timer_callback_tag = (gobject.timeout_add
202
195
                                               (1000,
203
196
                                                self.update_timer))
207
200
    
208
201
    def checker_completed(self, exitstatus, condition, command):
209
202
        if exitstatus == 0:
 
203
            if self.last_checker_failed:
 
204
                self.last_checker_failed = False
 
205
                self.using_timer(False)
 
206
            #self.logger('Checker for client %s (command "%s")'
 
207
            #            ' was successful'
 
208
            #            % (self.properties["Name"], command))
210
209
            self.update()
211
210
            return
212
211
        # Checker failed
 
212
        if not self.last_checker_failed:
 
213
            self.last_checker_failed = True
 
214
            self.using_timer(True)
213
215
        if os.WIFEXITED(condition):
214
 
            self.logger('Checker for client {0} (command "{1}")'
215
 
                        ' failed with exit code {2}'
216
 
                        .format(self.properties["Name"], command,
217
 
                                os.WEXITSTATUS(condition)))
 
216
            self.logger('Checker for client %s (command "%s")'
 
217
                        ' failed with exit code %s'
 
218
                        % (self.properties["Name"], command,
 
219
                           os.WEXITSTATUS(condition)))
218
220
        elif os.WIFSIGNALED(condition):
219
 
            self.logger('Checker for client {0} (command "{1}") was'
220
 
                        ' killed by signal {2}'
221
 
                        .format(self.properties["Name"], command,
222
 
                                os.WTERMSIG(condition)))
 
221
            self.logger('Checker for client %s (command "%s")'
 
222
                        ' was killed by signal %s'
 
223
                        % (self.properties["Name"], command,
 
224
                           os.WTERMSIG(condition)))
223
225
        elif os.WCOREDUMP(condition):
224
 
            self.logger('Checker for client {0} (command "{1}")'
 
226
            self.logger('Checker for client %s (command "%s")'
225
227
                        ' dumped core'
226
 
                        .format(self.properties["Name"], command))
 
228
                        % (self.properties["Name"], command))
227
229
        else:
228
 
            self.logger('Checker for client {0} completed'
229
 
                        ' mysteriously'
230
 
                        .format(self.properties["Name"]))
 
230
            self.logger('Checker for client %s completed'
 
231
                        ' mysteriously')
231
232
        self.update()
232
233
    
233
234
    def checker_started(self, command):
234
 
        """Server signals that a checker started. This could be useful
235
 
           to log in the future. """
236
 
        #self.logger('Client {0} started checker "{1}"'
237
 
        #            .format(self.properties["Name"],
238
 
        #                    unicode(command)))
 
235
        #self.logger('Client %s started checker "%s"'
 
236
        #            % (self.properties["Name"], unicode(command)))
239
237
        pass
240
238
    
241
239
    def got_secret(self):
242
 
        self.logger('Client {0} received its secret'
243
 
                    .format(self.properties["Name"]))
 
240
        self.last_checker_failed = False
 
241
        self.logger('Client %s received its secret'
 
242
                    % self.properties["Name"])
244
243
    
245
244
    def need_approval(self, timeout, default):
246
245
        if not default:
247
 
            message = 'Client {0} needs approval within {1} seconds'
 
246
            message = 'Client %s needs approval within %s seconds'
248
247
        else:
249
 
            message = 'Client {0} will get its secret in {1} seconds'
250
 
        self.logger(message.format(self.properties["Name"],
251
 
                                   timeout/1000))
 
248
            message = 'Client %s will get its secret in %s seconds'
 
249
        self.logger(message
 
250
                    % (self.properties["Name"], timeout/1000))
252
251
        self.using_timer(True)
253
252
    
254
253
    def rejected(self, reason):
255
 
        self.logger('Client {0} was rejected; reason: {1}'
256
 
                    .format(self.properties["Name"], reason))
 
254
        self.logger('Client %s was rejected; reason: %s'
 
255
                    % (self.properties["Name"], reason))
257
256
    
258
257
    def selectable(self):
259
258
        """Make this a "selectable" widget.
285
284
        # Rebuild focus and non-focus widgets using current properties
286
285
 
287
286
        # Base part of a client. Name!
288
 
        base = '{name}: '.format(name=self.properties["Name"])
 
287
        base = ('%(name)s: '
 
288
                      % {"name": self.properties["Name"]})
289
289
        if not self.properties["Enabled"]:
290
290
            message = "DISABLED"
291
291
        elif self.properties["ApprovalPending"]:
300
300
            else:
301
301
                timer = datetime.timedelta()
302
302
            if self.properties["ApprovedByDefault"]:
303
 
                message = "Approval in {0}. (d)eny?"
304
 
            else:
305
 
                message = "Denial in {0}. (a)pprove?"
306
 
            message = message.format(unicode(timer).rsplit(".", 1)[0])
307
 
        elif self.properties["LastCheckerStatus"] != 0:
308
 
            # When checker has failed, show timer until client expires
309
 
            expires = self.properties["Expires"]
310
 
            if expires == "":
311
 
                timer = datetime.timedelta(0)
312
 
            else:
313
 
                expires = (datetime.datetime.strptime
314
 
                           (expires, '%Y-%m-%dT%H:%M:%S.%f'))
315
 
                timer = expires - datetime.datetime.utcnow()
 
303
                message = "Approval in %s. (d)eny?"
 
304
            else:
 
305
                message = "Denial in %s. (a)pprove?"
 
306
            message = message % unicode(timer).rsplit(".", 1)[0]
 
307
        elif self.last_checker_failed:
 
308
            timeout = datetime.timedelta(milliseconds
 
309
                                         = self.properties
 
310
                                         ["Timeout"])
 
311
            last_ok = isoformat_to_datetime(
 
312
                max((self.properties["LastCheckedOK"]
 
313
                     or self.properties["Created"]),
 
314
                    self.properties["LastEnabled"]))
 
315
            timer = timeout - (datetime.datetime.utcnow() - last_ok)
316
316
            message = ('A checker has failed! Time until client'
317
 
                       ' gets disabled: {0}'
318
 
                       .format(unicode(timer).rsplit(".", 1)[0]))
 
317
                       ' gets disabled: %s'
 
318
                           % unicode(timer).rsplit(".", 1)[0])
319
319
        else:
320
320
            message = "enabled"
321
 
        self._text = "{0}{1}".format(base, message)
 
321
        self._text = "%s%s" % (base, message)
322
322
            
323
323
        if not urwid.supports_unicode():
324
324
            self._text = self._text.encode("ascii", "replace")
337
337
            self.update_hook()
338
338
    
339
339
    def update_timer(self):
340
 
        """called by gobject. Will indefinitely loop until
341
 
        gobject.source_remove() on tag is called"""
 
340
        "called by gobject"
342
341
        self.update()
343
342
        return True             # Keep calling this
344
343
    
345
 
    def delete(self, *args, **kwargs):
 
344
    def delete(self):
346
345
        if self._update_timer_callback_tag is not None:
347
346
            gobject.source_remove(self._update_timer_callback_tag)
348
347
            self._update_timer_callback_tag = None
349
 
        for match in self.match_objects:
350
 
            match.remove()
351
 
        self.match_objects = ()
352
348
        if self.delete_hook is not None:
353
349
            self.delete_hook(self)
354
 
        return super(MandosClientWidget, self).delete(*args, **kwargs)
355
350
    
356
351
    def render(self, maxcolrow, focus=False):
357
352
        """Render differently if we have focus.
363
358
        """Handle keys.
364
359
        This overrides the method from urwid.FlowWidget"""
365
360
        if key == "+":
366
 
            self.proxy.Enable(dbus_interface = client_interface,
367
 
                              ignore_reply=True)
 
361
            self.proxy.Enable(dbus_interface = client_interface)
368
362
        elif key == "-":
369
 
            self.proxy.Disable(dbus_interface = client_interface,
370
 
                               ignore_reply=True)
 
363
            self.proxy.Disable(dbus_interface = client_interface)
371
364
        elif key == "a":
372
365
            self.proxy.Approve(dbus.Boolean(True, variant_level=1),
373
 
                               dbus_interface = client_interface,
374
 
                               ignore_reply=True)
 
366
                               dbus_interface = client_interface)
375
367
        elif key == "d":
376
368
            self.proxy.Approve(dbus.Boolean(False, variant_level=1),
377
 
                                  dbus_interface = client_interface,
378
 
                               ignore_reply=True)
 
369
                                  dbus_interface = client_interface)
379
370
        elif key == "R" or key == "_" or key == "ctrl k":
380
371
            self.server_proxy_object.RemoveClient(self.proxy
381
 
                                                  .object_path,
382
 
                                                  ignore_reply=True)
 
372
                                                  .object_path)
383
373
        elif key == "s":
384
 
            self.proxy.StartChecker(dbus_interface = client_interface,
385
 
                                    ignore_reply=True)
 
374
            self.proxy.StartChecker(dbus_interface = client_interface)
386
375
        elif key == "S":
387
 
            self.proxy.StopChecker(dbus_interface = client_interface,
388
 
                                   ignore_reply=True)
 
376
            self.proxy.StopChecker(dbus_interface = client_interface)
389
377
        elif key == "C":
390
 
            self.proxy.CheckedOK(dbus_interface = client_interface,
391
 
                                 ignore_reply=True)
 
378
            self.proxy.CheckedOK(dbus_interface = client_interface)
392
379
        # xxx
393
380
#         elif key == "p" or key == "=":
394
381
#             self.proxy.pause()
487
474
        
488
475
        self.busname = domain + '.Mandos'
489
476
        self.main_loop = gobject.MainLoop()
 
477
        self.bus = dbus.SystemBus()
 
478
        mandos_dbus_objc = self.bus.get_object(
 
479
            self.busname, "/", follow_name_owner_changes=True)
 
480
        self.mandos_serv = dbus.Interface(mandos_dbus_objc,
 
481
                                          dbus_interface
 
482
                                          = server_interface)
 
483
        try:
 
484
            mandos_clients = (self.mandos_serv
 
485
                              .GetAllClientsWithProperties())
 
486
        except dbus.exceptions.DBusException:
 
487
            mandos_clients = dbus.Dictionary()
 
488
        
 
489
        (self.mandos_serv
 
490
         .connect_to_signal("ClientRemoved",
 
491
                            self.find_and_remove_client,
 
492
                            dbus_interface=server_interface,
 
493
                            byte_arrays=True))
 
494
        (self.mandos_serv
 
495
         .connect_to_signal("ClientAdded",
 
496
                            self.add_new_client,
 
497
                            dbus_interface=server_interface,
 
498
                            byte_arrays=True))
 
499
        (self.mandos_serv
 
500
         .connect_to_signal("ClientNotFound",
 
501
                            self.client_not_found,
 
502
                            dbus_interface=server_interface,
 
503
                            byte_arrays=True))
 
504
        for path, client in mandos_clients.iteritems():
 
505
            client_proxy_object = self.bus.get_object(self.busname,
 
506
                                                      path)
 
507
            self.add_client(MandosClientWidget(server_proxy_object
 
508
                                               =self.mandos_serv,
 
509
                                               proxy_object
 
510
                                               =client_proxy_object,
 
511
                                               properties=client,
 
512
                                               update_hook
 
513
                                               =self.refresh,
 
514
                                               delete_hook
 
515
                                               =self.remove_client,
 
516
                                               logger
 
517
                                               =self.log_message),
 
518
                            path=path)
490
519
    
491
520
    def client_not_found(self, fingerprint, address):
492
 
        self.log_message("Client with address {0} and fingerprint"
493
 
                         " {1} could not be found"
494
 
                         .format(address, fingerprint))
 
521
        self.log_message(("Client with address %s and fingerprint %s"
 
522
                          " could not be found" % (address,
 
523
                                                    fingerprint)))
495
524
    
496
525
    def rebuild(self):
497
526
        """This rebuilds the User Interface.
507
536
                                                     self.divider)))
508
537
        if self.log_visible:
509
538
            self.uilist.append(self.logbox)
 
539
            pass
510
540
        self.topwidget = urwid.Pile(self.uilist)
511
541
    
512
542
    def log_message(self, message):
542
572
        #self.log_message("Wrap mode: " + self.log_wrap)
543
573
    
544
574
    def find_and_remove_client(self, path, name):
545
 
        """Find a client by its object path and remove it.
 
575
        """Find an client from its object path and remove it.
546
576
        
547
577
        This is connected to the ClientRemoved signal from the
548
578
        Mandos server object."""
550
580
            client = self.clients_dict[path]
551
581
        except KeyError:
552
582
            # not found?
553
 
            self.log_message("Unknown client {0!r} ({1!r}) removed"
554
 
                             .format(name, path))
555
583
            return
556
 
        client.delete()
 
584
        self.remove_client(client, path)
557
585
    
558
586
    def add_new_client(self, path):
559
587
        client_proxy_object = self.bus.get_object(self.busname, path)
596
624
    
597
625
    def run(self):
598
626
        """Start the main loop and exit when it's done."""
599
 
        self.bus = dbus.SystemBus()
600
 
        mandos_dbus_objc = self.bus.get_object(
601
 
            self.busname, "/", follow_name_owner_changes=True)
602
 
        self.mandos_serv = dbus.Interface(mandos_dbus_objc,
603
 
                                          dbus_interface
604
 
                                          = server_interface)
605
 
        try:
606
 
            mandos_clients = (self.mandos_serv
607
 
                              .GetAllClientsWithProperties())
608
 
        except dbus.exceptions.DBusException:
609
 
            mandos_clients = dbus.Dictionary()
610
 
        
611
 
        (self.mandos_serv
612
 
         .connect_to_signal("ClientRemoved",
613
 
                            self.find_and_remove_client,
614
 
                            dbus_interface=server_interface,
615
 
                            byte_arrays=True))
616
 
        (self.mandos_serv
617
 
         .connect_to_signal("ClientAdded",
618
 
                            self.add_new_client,
619
 
                            dbus_interface=server_interface,
620
 
                            byte_arrays=True))
621
 
        (self.mandos_serv
622
 
         .connect_to_signal("ClientNotFound",
623
 
                            self.client_not_found,
624
 
                            dbus_interface=server_interface,
625
 
                            byte_arrays=True))
626
 
        for path, client in mandos_clients.iteritems():
627
 
            client_proxy_object = self.bus.get_object(self.busname,
628
 
                                                      path)
629
 
            self.add_client(MandosClientWidget(server_proxy_object
630
 
                                               =self.mandos_serv,
631
 
                                               proxy_object
632
 
                                               =client_proxy_object,
633
 
                                               properties=client,
634
 
                                               update_hook
635
 
                                               =self.refresh,
636
 
                                               delete_hook
637
 
                                               =self.remove_client,
638
 
                                               logger
639
 
                                               =self.log_message),
640
 
                            path=path)
641
 
 
642
627
        self.refresh()
643
628
        self._input_callback_tag = (gobject.io_add_watch
644
629
                                    (sys.stdin.fileno(),