/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: Björn Påhlsson
  • Date: 2010-09-07 16:48:58 UTC
  • mto: (237.4.3 mandos-release)
  • mto: This revision was merged to the branch mainline in revision 421.
  • Revision ID: belorn@fukt.bsnet.se-20100907164858-tcg8hkxdj41zizac
mandos server: Added debuglevel that adjust at what level information
               should be reported.
plugin-runner, askpass-fifo, password-prompt, splasy, usplash:
               Using error instead of perror

Show diffs side-by-side

added added

removed removed

Lines of Context:
4
4
from __future__ import division, absolute_import, with_statement
5
5
 
6
6
import sys
 
7
import os
7
8
import signal
8
9
 
 
10
import datetime
 
11
 
9
12
import urwid.curses_display
10
13
import urwid
11
14
 
16
19
 
17
20
import UserList
18
21
 
 
22
import locale
 
23
 
 
24
locale.setlocale(locale.LC_ALL, u'')
 
25
 
 
26
import logging
 
27
logging.getLogger('dbus.proxies').setLevel(logging.CRITICAL)
 
28
 
19
29
# Some useful constants
20
30
domain = 'se.bsnet.fukt'
21
31
server_interface = domain + '.Mandos'
22
32
client_interface = domain + '.Mandos.Client'
23
 
version = "1.0.14"
 
33
version = "1.0.15"
24
34
 
25
35
# Always run in monochrome mode
26
36
urwid.curses_display.curses.has_colors = lambda : False
35
45
    properties and calls a hook function when any of them are
36
46
    changed.
37
47
    """
38
 
    def __init__(self, proxy_object=None, properties=None, *args,
39
 
                 **kwargs):
 
48
    def __init__(self, proxy_object=None, *args, **kwargs):
40
49
        self.proxy = proxy_object # Mandos Client proxy object
41
50
        
42
 
        if properties is None:
43
 
            self.properties = dict()
44
 
        else:
45
 
            self.properties = properties
46
 
        self.proxy.connect_to_signal("PropertyChanged",
 
51
        self.properties = dict()
 
52
        self.proxy.connect_to_signal(u"PropertyChanged",
47
53
                                     self.property_changed,
48
54
                                     client_interface,
49
55
                                     byte_arrays=True)
50
56
        
51
 
        if properties is None:
52
 
            self.properties.update(self.proxy.GetAll(client_interface,
53
 
                                                     dbus_interface =
54
 
                                                     dbus.PROPERTIES_IFACE))
55
 
        super(MandosClientPropertyCache, self).__init__(
56
 
            proxy_object=proxy_object,
57
 
            properties=properties, *args, **kwargs)
 
57
        self.properties.update(
 
58
            self.proxy.GetAll(client_interface,
 
59
                              dbus_interface = dbus.PROPERTIES_IFACE))
 
60
 
 
61
        #XXX This break good super behaviour!
 
62
#        super(MandosClientPropertyCache, self).__init__(
 
63
#            *args, **kwargs)
58
64
    
59
65
    def property_changed(self, property=None, value=None):
60
66
        """This is called whenever we get a PropertyChanged signal
69
75
    """
70
76
    
71
77
    def __init__(self, server_proxy_object=None, update_hook=None,
72
 
                 delete_hook=None, *args, **kwargs):
 
78
                 delete_hook=None, logger=None, *args, **kwargs):
73
79
        # Called on update
74
80
        self.update_hook = update_hook
75
81
        # Called on delete
76
82
        self.delete_hook = delete_hook
77
83
        # Mandos Server proxy object
78
84
        self.server_proxy_object = server_proxy_object
 
85
        # Logger
 
86
        self.logger = logger
79
87
        
80
88
        # The widget shown normally
81
 
        self._text_widget = urwid.Text("")
 
89
        self._text_widget = urwid.Text(u"")
82
90
        # The widget shown when we have focus
83
 
        self._focus_text_widget = urwid.Text("")
 
91
        self._focus_text_widget = urwid.Text(u"")
84
92
        super(MandosClientWidget, self).__init__(
85
93
            update_hook=update_hook, delete_hook=delete_hook,
86
94
            *args, **kwargs)
87
95
        self.update()
88
96
        self.opened = False
 
97
        self.proxy.connect_to_signal(u"CheckerCompleted",
 
98
                                     self.checker_completed,
 
99
                                     client_interface,
 
100
                                     byte_arrays=True)
 
101
        self.proxy.connect_to_signal(u"CheckerStarted",
 
102
                                     self.checker_started,
 
103
                                     client_interface,
 
104
                                     byte_arrays=True)
 
105
        self.proxy.connect_to_signal(u"GotSecret",
 
106
                                     self.got_secret,
 
107
                                     client_interface,
 
108
                                     byte_arrays=True)
 
109
        self.proxy.connect_to_signal(u"NeedApproval",
 
110
                                     self.need_approval,
 
111
                                     client_interface,
 
112
                                     byte_arrays=True)
 
113
        self.proxy.connect_to_signal(u"Rejected",
 
114
                                     self.rejected,
 
115
                                     client_interface,
 
116
                                     byte_arrays=True)
 
117
    
 
118
    def checker_completed(self, exitstatus, condition, command):
 
119
        if exitstatus == 0:
 
120
            #self.logger(u'Checker for client %s (command "%s")'
 
121
            #            u' was successful'
 
122
            #            % (self.properties[u"name"], command))
 
123
            return
 
124
        if os.WIFEXITED(condition):
 
125
            self.logger(u'Checker for client %s (command "%s")'
 
126
                        u' failed with exit code %s'
 
127
                        % (self.properties[u"name"], command,
 
128
                           os.WEXITSTATUS(condition)))
 
129
            return
 
130
        if os.WIFSIGNALED(condition):
 
131
            self.logger(u'Checker for client %s (command "%s")'
 
132
                        u' was killed by signal %s'
 
133
                        % (self.properties[u"name"], command,
 
134
                           os.WTERMSIG(condition)))
 
135
            return
 
136
        if os.WCOREDUMP(condition):
 
137
            self.logger(u'Checker for client %s (command "%s")'
 
138
                        u' dumped core'
 
139
                        % (self.properties[u"name"], command))
 
140
        self.logger(u'Checker for client %s completed mysteriously')
 
141
    
 
142
    def checker_started(self, command):
 
143
        #self.logger(u'Client %s started checker "%s"'
 
144
        #            % (self.properties[u"name"], unicode(command)))
 
145
        pass
 
146
    
 
147
    def got_secret(self):
 
148
        self.logger(u'Client %s received its secret'
 
149
                    % self.properties[u"name"])
 
150
    
 
151
    def need_approval(self, timeout, default):
 
152
        if not default:
 
153
            message = u'Client %s needs approval within %s seconds'
 
154
        else:
 
155
            message = u'Client %s will get its secret in %s seconds'
 
156
        self.logger(message
 
157
                    % (self.properties[u"name"], timeout/1000))
 
158
    
 
159
    def rejected(self, reason):
 
160
        self.logger(u'Client %s was rejected; reason: %s'
 
161
                    % (self.properties[u"name"], reason))
89
162
    
90
163
    def selectable(self):
91
164
        """Make this a "selectable" widget.
113
186
                          u"bold-underline-blink":
114
187
                              u"bold-underline-blink-standout",
115
188
                          }
116
 
        
 
189
 
117
190
        # Rebuild focus and non-focus widgets using current properties
118
 
        self._text = (u'name="%(name)s", enabled=%(enabled)s'
119
 
                      % self.properties)
 
191
 
 
192
        # Base part of a client. Name!
 
193
        self._text = (u'%(name)s: '
 
194
                      % {u"name": self.properties[u"name"]})
 
195
 
 
196
        if self.properties[u"approved_pending"]:
 
197
            if self.properties[u"approved_by_default"]:
 
198
                self._text += u"Connection established to client. (d)eny?"
 
199
            else:
 
200
                self._text += u"Seeks approval to send secret. (a)pprove?"
 
201
        else:
 
202
            self._text += (u'%(enabled)s'
 
203
                           % {u"enabled":
 
204
                               (u"enabled"
 
205
                                if self.properties[u"enabled"]
 
206
                                else u"DISABLED")})
120
207
        if not urwid.supports_unicode():
121
208
            self._text = self._text.encode("ascii", "replace")
122
 
        textlist = [(u"normal", u"BLARGH: "), (u"bold", self._text)]
 
209
        textlist = [(u"normal", self._text)]
123
210
        self._text_widget.set_text(textlist)
124
211
        self._focus_text_widget.set_text([(with_standout[text[0]],
125
212
                                           text[1])
146
233
    def keypress(self, (maxcol,), key):
147
234
        """Handle keys.
148
235
        This overrides the method from urwid.FlowWidget"""
149
 
        if key == u"e" or key == u"+":
150
 
            self.proxy.Enable()
151
 
        elif key == u"d" or key == u"-":
152
 
            self.proxy.Disable()
153
 
        elif key == u"r" or key == u"_":
 
236
        if key == u"+":
 
237
            self.proxy.Enable(dbus_interface = client_interface)
 
238
        elif key == u"-":
 
239
            self.proxy.Disable(dbus_interface = client_interface)
 
240
        elif key == u"a":
 
241
            self.proxy.Approve(dbus.Boolean(True, variant_level=1),
 
242
                               dbus_interface = client_interface)
 
243
        elif key == u"d":
 
244
            self.proxy.Approve(dbus.Boolean(False, variant_level=1),
 
245
                                  dbus_interface = client_interface)
 
246
        elif key == u"r" or key == u"_" or key == u"ctrl k":
154
247
            self.server_proxy_object.RemoveClient(self.proxy
155
248
                                                  .object_path)
156
249
        elif key == u"s":
157
 
            self.proxy.StartChecker()
158
 
        elif key == u"c":
159
 
            self.proxy.StopChecker()
 
250
            self.proxy.StartChecker(dbus_interface = client_interface)
160
251
        elif key == u"S":
161
 
            self.proxy.CheckedOK()
 
252
            self.proxy.StopChecker(dbus_interface = client_interface)
 
253
        elif key == u"C":
 
254
            self.proxy.CheckedOK(dbus_interface = client_interface)
162
255
        # xxx
163
256
#         elif key == u"p" or key == "=":
164
257
#             self.proxy.pause()
166
259
#             self.proxy.unpause()
167
260
#         elif key == u"RET":
168
261
#             self.open()
 
262
#        elif key == u"+":
 
263
#            self.proxy.Approve(True)
 
264
#        elif key == u"-":
 
265
#            self.proxy.Approve(False)
169
266
        else:
170
267
            return key
171
268
    
223
320
                ))
224
321
        
225
322
        if urwid.supports_unicode():
226
 
            #self.divider = u"─" # \u2500
227
 
            self.divider = u"━" # \u2501
 
323
            self.divider = u"─" # \u2500
 
324
            #self.divider = u"━" # \u2501
228
325
        else:
229
326
            #self.divider = u"-" # \u002d
230
327
            self.divider = u"_" # \u005f
250
347
        self.log_wrap = u"any"
251
348
        
252
349
        self.rebuild()
253
 
        self.log_message(u"Message")
254
 
        self.log_message(u"Message0 Message1 Message2 Message3 Message4 Message5 Message6 Message7 Message8 Message9")
255
 
        self.log_message(u"Message10 Message11 Message12 Message13 Message14 Message15 Message16 Message17 Message18 Message19")
256
 
        self.log_message(u"Message20 Message21 Message22 Message23 Message24 Message25 Message26 Message27 Message28 Message29")
 
350
        self.log_message_raw((u"bold",
 
351
                              u"Mandos Monitor version " + version))
 
352
        self.log_message_raw((u"bold",
 
353
                              u"q: Quit  ?: Help"))
257
354
        
258
355
        self.busname = domain + '.Mandos'
259
356
        self.main_loop = gobject.MainLoop()
270
367
            mandos_clients = dbus.Dictionary()
271
368
        
272
369
        (self.mandos_serv
273
 
         .connect_to_signal("ClientRemoved",
 
370
         .connect_to_signal(u"ClientRemoved",
274
371
                            self.find_and_remove_client,
275
372
                            dbus_interface=server_interface,
276
373
                            byte_arrays=True))
277
374
        (self.mandos_serv
278
 
         .connect_to_signal("ClientAdded",
 
375
         .connect_to_signal(u"ClientAdded",
279
376
                            self.add_new_client,
280
377
                            dbus_interface=server_interface,
281
378
                            byte_arrays=True))
 
379
        (self.mandos_serv
 
380
         .connect_to_signal(u"ClientNotFound",
 
381
                            self.client_not_found,
 
382
                            dbus_interface=server_interface,
 
383
                            byte_arrays=True))
282
384
        for path, client in mandos_clients.iteritems():
283
385
            client_proxy_object = self.bus.get_object(self.busname,
284
386
                                                      path)
290
392
                                               update_hook
291
393
                                               =self.refresh,
292
394
                                               delete_hook
293
 
                                               =self.remove_client),
 
395
                                               =self.remove_client,
 
396
                                               logger
 
397
                                               =self.log_message),
294
398
                            path=path)
295
399
    
 
400
    def client_not_found(self, fingerprint, address):
 
401
        self.log_message((u"Client with address %s and fingerprint %s"
 
402
                          u" could not be found" % (address,
 
403
                                                    fingerprint)))
 
404
    
296
405
    def rebuild(self):
297
406
        """This rebuilds the User Interface.
298
407
        Call this when the widget layout needs to change"""
307
416
            pass
308
417
        self.topwidget = urwid.Pile(self.uilist)
309
418
    
310
 
    def log_message(self, markup):
 
419
    def log_message(self, message):
 
420
        timestamp = datetime.datetime.now().isoformat()
 
421
        self.log_message_raw(timestamp + u": " + message)
 
422
    
 
423
    def log_message_raw(self, markup):
311
424
        """Add a log message to the log buffer."""
312
425
        self.log.append(urwid.Text(markup, wrap=self.log_wrap))
313
426
        if (self.max_log_length
314
427
            and len(self.log) > self.max_log_length):
315
428
            del self.log[0:len(self.log)-self.max_log_length-1]
 
429
        self.logbox.set_focus(len(self.logbox.body.contents),
 
430
                              coming_from=u"above")
 
431
        self.refresh()
316
432
    
317
433
    def toggle_log_display(self):
318
434
        """Toggle visibility of the log buffer."""
344
460
            return
345
461
        self.remove_client(client, path)
346
462
    
347
 
    def add_new_client(self, path, properties):
 
463
    def add_new_client(self, path):
348
464
        client_proxy_object = self.bus.get_object(self.busname, path)
349
465
        self.add_client(MandosClientWidget(server_proxy_object
350
466
                                           =self.mandos_serv,
351
467
                                           proxy_object
352
468
                                           =client_proxy_object,
353
 
                                           properties=properties,
354
469
                                           update_hook
355
470
                                           =self.refresh,
356
471
                                           delete_hook
357
 
                                           =self.remove_client),
 
472
                                           =self.remove_client,
 
473
                                           logger
 
474
                                           =self.log_message),
358
475
                        path=path)
359
476
    
360
477
    def add_client(self, client, path=None):
429
546
            elif key == u"w" or key == u"i":
430
547
                self.change_log_display()
431
548
                self.refresh()
432
 
            elif key == u"?" or key == u"f1":
433
 
                self.log_message(u"Help!")
 
549
            elif key == u"?" or key == u"f1" or key == u"esc":
 
550
                if not self.log_visible:
 
551
                    self.log_visible = True
 
552
                    self.rebuild()
 
553
                self.log_message_raw((u"bold",
 
554
                                      u"  ".
 
555
                                      join((u"q: Quit",
 
556
                                            u"?: Help",
 
557
                                            u"l: Log window toggle",
 
558
                                            u"TAB: Switch window",
 
559
                                            u"w: Wrap (log)"))))
 
560
                self.log_message_raw((u"bold",
 
561
                                      u"  "
 
562
                                      .join((u"Clients:",
 
563
                                             u"+: Enable",
 
564
                                             u"-: Disable",
 
565
                                             u"r: Remove",
 
566
                                             u"s: Start new checker",
 
567
                                             u"S: Stop checker",
 
568
                                             u"C: Checker OK",
 
569
                                             u"a: Approve",
 
570
                                             u"d: Deny"))))
434
571
                self.refresh()
435
572
            elif key == u"tab":
436
573
                if self.topwidget.get_focus() is self.logbox:
438
575
                else:
439
576
                    self.topwidget.set_focus(self.logbox)
440
577
                self.refresh()
441
 
            elif (key == u"end" or key == u"meta >" or key == u"G"
442
 
                  or key == u">"):
443
 
                pass            # xxx end-of-buffer
444
 
            elif (key == u"home" or key == u"meta <" or key == u"g"
445
 
                  or key == u"<"):
446
 
                pass            # xxx beginning-of-buffer
447
 
            elif key == u"ctrl e" or key == u"$":
448
 
                pass            # xxx move-end-of-line
449
 
            elif key == u"ctrl a" or key == u"^":
450
 
                pass            # xxx move-beginning-of-line
451
 
            elif key == u"ctrl b" or key == u"meta (" or key == u"h":
452
 
                pass            # xxx left
453
 
            elif key == u"ctrl f" or key == u"meta )" or key == u"l":
454
 
                pass            # xxx right
455
 
            elif key == u"a":
456
 
                pass            # scroll up log
457
 
            elif key == u"z":
458
 
                pass            # scroll down log
 
578
            #elif (key == u"end" or key == u"meta >" or key == u"G"
 
579
            #      or key == u">"):
 
580
            #    pass            # xxx end-of-buffer
 
581
            #elif (key == u"home" or key == u"meta <" or key == u"g"
 
582
            #      or key == u"<"):
 
583
            #    pass            # xxx beginning-of-buffer
 
584
            #elif key == u"ctrl e" or key == u"$":
 
585
            #    pass            # xxx move-end-of-line
 
586
            #elif key == u"ctrl a" or key == u"^":
 
587
            #    pass            # xxx move-beginning-of-line
 
588
            #elif key == u"ctrl b" or key == u"meta (" or key == u"h":
 
589
            #    pass            # xxx left
 
590
            #elif key == u"ctrl f" or key == u"meta )" or key == u"l":
 
591
            #    pass            # xxx right
 
592
            #elif key == u"a":
 
593
            #    pass            # scroll up log
 
594
            #elif key == u"z":
 
595
            #    pass            # scroll down log
459
596
            elif self.topwidget.selectable():
460
597
                self.topwidget.keypress(self.size, key)
461
598
                self.refresh()
464
601
ui = UserInterface()
465
602
try:
466
603
    ui.run()
467
 
except:
 
604
except Exception, e:
 
605
    ui.log_message(unicode(e))
468
606
    ui.screen.stop()
469
607
    raise