/mandos/release

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

« back to all changes in this revision

Viewing changes to mandos-monitor

* initramfs-tools-script: Abort if plugin-runner is missing.  Removed
                          workaround for Debian bug #633582; the
                          workaround required getopt, which can not be
                          guaranteed.
* plugin-runner.c (main): Work around Debian bug #633582.
* plugins.d/mandos-client.c (main): - '' -

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