/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 Hogeborn
  • Date: 2010-09-25 21:24:49 UTC
  • Revision ID: teddy@fukt.bsnet.se-20100925212449-h9hpy9n406tkkakb
* mandos.xml (APPROVAL): New section.

Show diffs side-by-side

added added

removed removed

Lines of Context:
23
23
 
24
24
locale.setlocale(locale.LC_ALL, u'')
25
25
 
 
26
import logging
 
27
logging.getLogger('dbus.proxies').setLevel(logging.CRITICAL)
 
28
 
26
29
# Some useful constants
27
30
domain = 'se.bsnet.fukt'
28
31
server_interface = domain + '.Mandos'
29
32
client_interface = domain + '.Mandos.Client'
30
 
version = "1.0.14"
 
33
version = "1.0.15"
31
34
 
32
35
# Always run in monochrome mode
33
36
urwid.curses_display.curses.has_colors = lambda : False
37
40
urwid.curses_display.curses.A_UNDERLINE |= (
38
41
    urwid.curses_display.curses.A_BLINK)
39
42
 
 
43
def isoformat_to_datetime(iso):
 
44
    "Parse an ISO 8601 date string to a datetime.datetime()"
 
45
    if not iso:
 
46
        return None
 
47
    d, t = iso.split(u"T", 1)
 
48
    year, month, day = d.split(u"-", 2)
 
49
    hour, minute, second = t.split(u":", 2)
 
50
    second, fraction = divmod(float(second), 1)
 
51
    return datetime.datetime(int(year),
 
52
                             int(month),
 
53
                             int(day),
 
54
                             int(hour),
 
55
                             int(minute),
 
56
                             int(second),           # Whole seconds
 
57
                             int(fraction*1000000)) # Microseconds
 
58
 
40
59
class MandosClientPropertyCache(object):
41
60
    """This wraps a Mandos Client D-Bus proxy object, caches the
42
61
    properties and calls a hook function when any of them are
50
69
                                     self.property_changed,
51
70
                                     client_interface,
52
71
                                     byte_arrays=True)
53
 
 
 
72
        
54
73
        self.properties.update(
55
74
            self.proxy.GetAll(client_interface,
56
75
                              dbus_interface = dbus.PROPERTIES_IFACE))
57
 
        super(MandosClientPropertyCache, self).__init__(
58
 
            proxy_object=proxy_object, *args, **kwargs)
 
76
 
 
77
        #XXX This break good super behaviour!
 
78
#        super(MandosClientPropertyCache, self).__init__(
 
79
#            *args, **kwargs)
59
80
    
60
81
    def property_changed(self, property=None, value=None):
61
82
        """This is called whenever we get a PropertyChanged signal
80
101
        # Logger
81
102
        self.logger = logger
82
103
        
 
104
        self._update_timer_callback_tag = None
 
105
        self.last_checker_failed = False
 
106
        
83
107
        # The widget shown normally
84
108
        self._text_widget = urwid.Text(u"")
85
109
        # The widget shown when we have focus
101
125
                                     self.got_secret,
102
126
                                     client_interface,
103
127
                                     byte_arrays=True)
 
128
        self.proxy.connect_to_signal(u"NeedApproval",
 
129
                                     self.need_approval,
 
130
                                     client_interface,
 
131
                                     byte_arrays=True)
104
132
        self.proxy.connect_to_signal(u"Rejected",
105
133
                                     self.rejected,
106
134
                                     client_interface,
107
135
                                     byte_arrays=True)
 
136
        last_checked_ok = isoformat_to_datetime(self.properties
 
137
                                                [u"LastCheckedOK"])
 
138
        if last_checked_ok is None:
 
139
            self.last_checker_failed = True
 
140
        else:
 
141
            self.last_checker_failed = ((datetime.datetime.utcnow()
 
142
                                         - last_checked_ok)
 
143
                                        > datetime.timedelta
 
144
                                        (milliseconds=
 
145
                                         self.properties
 
146
                                         [u"Interval"]))
 
147
        if self.last_checker_failed:
 
148
            self._update_timer_callback_tag = (gobject.timeout_add
 
149
                                               (1000,
 
150
                                                self.update_timer))
108
151
    
109
152
    def checker_completed(self, exitstatus, condition, command):
110
153
        if exitstatus == 0:
111
 
            self.logger(u'Checker for client %s (command "%s")'
112
 
                        u' was successful'
113
 
                        % (self.properties[u"name"], command))
 
154
            if self.last_checker_failed:
 
155
                self.last_checker_failed = False
 
156
                gobject.source_remove(self._update_timer_callback_tag)
 
157
                self._update_timer_callback_tag = None
 
158
            #self.logger(u'Checker for client %s (command "%s")'
 
159
            #            u' was successful'
 
160
            #            % (self.properties[u"Name"], command))
 
161
            self.update()
114
162
            return
 
163
        # Checker failed
 
164
        if not self.last_checker_failed:
 
165
            self.last_checker_failed = True
 
166
            self._update_timer_callback_tag = (gobject.timeout_add
 
167
                                               (1000,
 
168
                                                self.update_timer))
115
169
        if os.WIFEXITED(condition):
116
170
            self.logger(u'Checker for client %s (command "%s")'
117
171
                        u' failed with exit code %s'
118
 
                        % (self.properties[u"name"], command,
 
172
                        % (self.properties[u"Name"], command,
119
173
                           os.WEXITSTATUS(condition)))
120
 
            return
121
 
        if os.WIFSIGNALED(condition):
 
174
        elif os.WIFSIGNALED(condition):
122
175
            self.logger(u'Checker for client %s (command "%s")'
123
176
                        u' was killed by signal %s'
124
 
                        % (self.properties[u"name"], command,
 
177
                        % (self.properties[u"Name"], command,
125
178
                           os.WTERMSIG(condition)))
126
 
            return
127
 
        if os.WCOREDUMP(condition):
 
179
        elif os.WCOREDUMP(condition):
128
180
            self.logger(u'Checker for client %s (command "%s")'
129
181
                        u' dumped core'
130
 
                        % (self.properties[u"name"], command))
131
 
        self.logger(u'Checker for client %s completed mysteriously')
 
182
                        % (self.properties[u"Name"], command))
 
183
        else:
 
184
            self.logger(u'Checker for client %s completed'
 
185
                        u' mysteriously')
 
186
        self.update()
132
187
    
133
188
    def checker_started(self, command):
134
 
        self.logger(u'Client %s started checker "%s"'
135
 
                    % (self.properties[u"name"], unicode(command)))
 
189
        #self.logger(u'Client %s started checker "%s"'
 
190
        #            % (self.properties[u"Name"], unicode(command)))
 
191
        pass
136
192
    
137
193
    def got_secret(self):
 
194
        self.last_checker_failed = False
138
195
        self.logger(u'Client %s received its secret'
139
 
                    % self.properties[u"name"])
140
 
    
141
 
    def rejected(self):
142
 
        self.logger(u'Client %s was rejected'
143
 
                    % self.properties[u"name"])
 
196
                    % self.properties[u"Name"])
 
197
    
 
198
    def need_approval(self, timeout, default):
 
199
        if not default:
 
200
            message = u'Client %s needs approval within %s seconds'
 
201
        else:
 
202
            message = u'Client %s will get its secret in %s seconds'
 
203
        self.logger(message
 
204
                    % (self.properties[u"Name"], timeout/1000))
 
205
    
 
206
    def rejected(self, reason):
 
207
        self.logger(u'Client %s was rejected; reason: %s'
 
208
                    % (self.properties[u"Name"], reason))
144
209
    
145
210
    def selectable(self):
146
211
        """Make this a "selectable" widget.
168
233
                          u"bold-underline-blink":
169
234
                              u"bold-underline-blink-standout",
170
235
                          }
171
 
        
 
236
 
172
237
        # Rebuild focus and non-focus widgets using current properties
173
 
        self._text = (u'%(name)s: %(enabled)s'
174
 
                      % { u"name": self.properties[u"name"],
175
 
                          u"enabled":
176
 
                              (u"enabled"
177
 
                               if self.properties[u"enabled"]
178
 
                               else u"DISABLED")})
 
238
 
 
239
        # Base part of a client. Name!
 
240
        base = (u'%(name)s: '
 
241
                      % {u"name": self.properties[u"Name"]})
 
242
        if not self.properties[u"Enabled"]:
 
243
            message = u"DISABLED"
 
244
        elif self.properties[u"ApprovalPending"]:
 
245
            if self.properties[u"ApprovedByDefault"]:
 
246
                message = u"Connection established to client. (d)eny?"
 
247
            else:
 
248
                message = u"Seeks approval to send secret. (a)pprove?"
 
249
        elif self.last_checker_failed:
 
250
            timeout = datetime.timedelta(milliseconds
 
251
                                         = self.properties
 
252
                                         [u"Timeout"])
 
253
            last_ok = isoformat_to_datetime(
 
254
                max((self.properties[u"LastCheckedOK"]
 
255
                     or self.properties[u"Created"]),
 
256
                    self.properties[u"LastEnabled"]))
 
257
            timer = timeout - (datetime.datetime.utcnow() - last_ok)
 
258
            message = (u'A checker has failed! Time until client'
 
259
                       u' gets diabled: %s'
 
260
                           % unicode(timer).rsplit(".", 1)[0])
 
261
        else:
 
262
            message = u"enabled"
 
263
        self._text = "%s%s" % (base, message)
 
264
            
179
265
        if not urwid.supports_unicode():
180
266
            self._text = self._text.encode("ascii", "replace")
181
267
        textlist = [(u"normal", self._text)]
192
278
        if self.update_hook is not None:
193
279
            self.update_hook()
194
280
    
 
281
    def update_timer(self):
 
282
        "called by gobject"
 
283
        self.update()
 
284
        return True             # Keep calling this
 
285
    
195
286
    def delete(self):
 
287
        if self._update_timer_callback_tag is not None:
 
288
            gobject.source_remove(self._update_timer_callback_tag)
 
289
            self._update_timer_callback_tag = None
196
290
        if self.delete_hook is not None:
197
291
            self.delete_hook(self)
198
292
    
205
299
    def keypress(self, (maxcol,), key):
206
300
        """Handle keys.
207
301
        This overrides the method from urwid.FlowWidget"""
208
 
        if key == u"e" or key == u"+":
209
 
            self.proxy.Enable()
210
 
        elif key == u"d" or key == u"-":
211
 
            self.proxy.Disable()
 
302
        if key == u"+":
 
303
            self.proxy.Enable(dbus_interface = client_interface)
 
304
        elif key == u"-":
 
305
            self.proxy.Disable(dbus_interface = client_interface)
 
306
        elif key == u"a":
 
307
            self.proxy.Approve(dbus.Boolean(True, variant_level=1),
 
308
                               dbus_interface = client_interface)
 
309
        elif key == u"d":
 
310
            self.proxy.Approve(dbus.Boolean(False, variant_level=1),
 
311
                                  dbus_interface = client_interface)
212
312
        elif key == u"r" or key == u"_" or key == u"ctrl k":
213
313
            self.server_proxy_object.RemoveClient(self.proxy
214
314
                                                  .object_path)
215
315
        elif key == u"s":
216
 
            self.proxy.StartChecker()
 
316
            self.proxy.StartChecker(dbus_interface = client_interface)
217
317
        elif key == u"S":
218
 
            self.proxy.StopChecker()
 
318
            self.proxy.StopChecker(dbus_interface = client_interface)
219
319
        elif key == u"C":
220
 
            self.proxy.CheckedOK()
 
320
            self.proxy.CheckedOK(dbus_interface = client_interface)
221
321
        # xxx
222
322
#         elif key == u"p" or key == "=":
223
323
#             self.proxy.pause()
246
346
    use them as an excuse to shift focus away from this widget.
247
347
    """
248
348
    def keypress(self, (maxcol, maxrow), key):
249
 
        ret = super(ConstrainedListBox, self).keypress((maxcol, maxrow), key)
 
349
        ret = super(ConstrainedListBox, self).keypress((maxcol,
 
350
                                                        maxrow), key)
250
351
        if ret in (u"up", u"down"):
251
352
            return
252
353
        return ret
369
470
        Call this when the widget layout needs to change"""
370
471
        self.uilist = []
371
472
        #self.uilist.append(urwid.ListBox(self.clients))
372
 
        self.uilist.append(urwid.Frame(ConstrainedListBox(self.clients),
 
473
        self.uilist.append(urwid.Frame(ConstrainedListBox(self.
 
474
                                                          clients),
373
475
                                       #header=urwid.Divider(),
374
476
                                       header=None,
375
 
                                       footer=urwid.Divider(div_char=self.divider)))
 
477
                                       footer=
 
478
                                       urwid.Divider(div_char=
 
479
                                                     self.divider)))
376
480
        if self.log_visible:
377
481
            self.uilist.append(self.logbox)
378
482
            pass
396
500
        """Toggle visibility of the log buffer."""
397
501
        self.log_visible = not self.log_visible
398
502
        self.rebuild()
399
 
        self.log_message(u"Log visibility changed to: "
400
 
                         + unicode(self.log_visible))
 
503
        #self.log_message(u"Log visibility changed to: "
 
504
        #                 + unicode(self.log_visible))
401
505
    
402
506
    def change_log_display(self):
403
507
        """Change type of log display.
408
512
            self.log_wrap = u"clip"
409
513
        for textwidget in self.log:
410
514
            textwidget.set_wrap_mode(self.log_wrap)
411
 
        self.log_message(u"Wrap mode: " + self.log_wrap)
 
515
        #self.log_message(u"Wrap mode: " + self.log_wrap)
412
516
    
413
517
    def find_and_remove_client(self, path, name):
414
518
        """Find an client from its object path and remove it.
441
545
        if path is None:
442
546
            path = client.proxy.object_path
443
547
        self.clients_dict[path] = client
444
 
        self.clients.sort(None, lambda c: c.properties[u"name"])
 
548
        self.clients.sort(None, lambda c: c.properties[u"Name"])
445
549
        self.refresh()
446
550
    
447
551
    def remove_client(self, client, path=None):
522
626
                self.log_message_raw((u"bold",
523
627
                                      u"  "
524
628
                                      .join((u"Clients:",
525
 
                                             u"e: Enable",
526
 
                                             u"d: Disable",
 
629
                                             u"+: Enable",
 
630
                                             u"-: Disable",
527
631
                                             u"r: Remove",
528
632
                                             u"s: Start new checker",
529
633
                                             u"S: Stop checker",
530
 
                                             u"C: Checker OK"))))
 
634
                                             u"C: Checker OK",
 
635
                                             u"a: Approve",
 
636
                                             u"d: Deny"))))
531
637
                self.refresh()
532
638
            elif key == u"tab":
533
639
                if self.topwidget.get_focus() is self.logbox:
561
667
ui = UserInterface()
562
668
try:
563
669
    ui.run()
 
670
except KeyboardInterrupt:
 
671
    ui.screen.stop()
564
672
except Exception, e:
565
673
    ui.log_message(unicode(e))
566
674
    ui.screen.stop()