/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

  • Committer: Teddy Hogeborn
  • Date: 2024-11-24 14:41:36 UTC
  • mfrom: (237.7.863 trunk)
  • Revision ID: teddy@recompile.se-20241124144136-0fej6fm6woitsooj
Merge from trunk

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
#!/usr/bin/python
 
1
#!/usr/bin/python3 -bbI
2
2
# -*- mode: python; coding: utf-8 -*-
3
3
#
4
4
# Mandos Monitor - Control and monitor the Mandos server
5
5
#
6
 
# Copyright © 2009-2017 Teddy Hogeborn
7
 
# Copyright © 2009-2017 Björn Påhlsson
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
 
6
# Copyright © 2009-2019 Teddy Hogeborn
 
7
# Copyright © 2009-2019 Björn Påhlsson
 
8
#
 
9
# This file is part of Mandos.
 
10
#
 
11
# Mandos is free software: you can redistribute it and/or modify it
 
12
# under the terms of the GNU General Public License as published by
11
13
# the Free Software Foundation, either version 3 of the License, or
12
14
# (at your option) any later version.
13
15
#
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
#     Mandos is distributed in the hope that it will be useful, but
 
17
#     WITHOUT ANY WARRANTY; without even the implied warranty of
16
18
#     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17
19
#     GNU General Public License for more details.
18
20
#
19
21
# 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/>.
 
22
# along with Mandos.  If not, see <http://www.gnu.org/licenses/>.
22
23
#
23
24
# Contact the authors at <mandos@recompile.se>.
24
25
#
25
 
 
26
26
from __future__ import (division, absolute_import, print_function,
27
27
                        unicode_literals)
 
28
 
28
29
try:
29
30
    from future_builtins import *
30
31
except ImportError:
31
32
    pass
32
33
 
33
34
import sys
 
35
import logging
34
36
import os
35
 
 
 
37
import warnings
36
38
import datetime
 
39
import locale
37
40
 
38
41
import urwid.curses_display
39
42
import urwid
43
46
 
44
47
import dbus
45
48
 
46
 
import locale
47
 
 
48
 
import logging
49
 
 
50
49
if sys.version_info.major == 2:
 
50
    __metaclass__ = type
51
51
    str = unicode
52
 
 
53
 
locale.setlocale(locale.LC_ALL, '')
54
 
 
55
 
logging.getLogger('dbus.proxies').setLevel(logging.CRITICAL)
 
52
    input = raw_input
 
53
 
 
54
# Show warnings by default
 
55
if not sys.warnoptions:
 
56
    warnings.simplefilter("default")
 
57
 
 
58
log = logging.getLogger(os.path.basename(sys.argv[0]))
 
59
logging.basicConfig(level="NOTSET", # Show all messages
 
60
                    format="%(message)s") # Show basic log messages
 
61
 
 
62
logging.captureWarnings(True)   # Show warnings via the logging system
 
63
 
 
64
locale.setlocale(locale.LC_ALL, "")
 
65
 
 
66
logging.getLogger("dbus.proxies").setLevel(logging.CRITICAL)
 
67
logging.getLogger("urwid").setLevel(logging.INFO)
56
68
 
57
69
# Some useful constants
58
 
domain = 'se.recompile'
59
 
server_interface = domain + '.Mandos'
60
 
client_interface = domain + '.Mandos.Client'
61
 
version = "1.7.15"
 
70
domain = "se.recompile"
 
71
server_interface = domain + ".Mandos"
 
72
client_interface = domain + ".Mandos.Client"
 
73
version = "1.8.17"
62
74
 
63
75
try:
64
76
    dbus.OBJECT_MANAGER_IFACE
83
95
                             int(fraction*1000000))  # Microseconds
84
96
 
85
97
 
86
 
class MandosClientPropertyCache(object):
 
98
class MandosClientPropertyCache:
87
99
    """This wraps a Mandos Client D-Bus proxy object, caches the
88
100
    properties and calls a hook function when any of them are
89
101
    changed.
116
128
        self.property_changed_match.remove()
117
129
 
118
130
 
119
 
class MandosClientWidget(urwid.FlowWidget, MandosClientPropertyCache):
 
131
class MandosClientWidget(MandosClientPropertyCache, urwid.Widget):
120
132
    """A Mandos Client which is visible on the screen.
121
133
    """
122
134
 
 
135
    _sizing = frozenset(["flow"])
 
136
 
123
137
    def __init__(self, server_proxy_object=None, update_hook=None,
124
 
                 delete_hook=None, logger=None, **kwargs):
 
138
                 delete_hook=None, **kwargs):
125
139
        # Called on update
126
140
        self.update_hook = update_hook
127
141
        # Called on delete
128
142
        self.delete_hook = delete_hook
129
143
        # Mandos Server proxy object
130
144
        self.server_proxy_object = server_proxy_object
131
 
        # Logger
132
 
        self.logger = logger
133
145
 
134
146
        self._update_timer_callback_tag = None
135
147
 
162
174
                                         self.rejected,
163
175
                                         client_interface,
164
176
                                         byte_arrays=True))
165
 
        self.logger('Created client {}'
166
 
                    .format(self.properties["Name"]), level=0)
 
177
        log.debug("Created client %s", self.properties["Name"])
167
178
 
168
179
    def using_timer(self, flag):
169
180
        """Call this method with True or False when timer should be
171
182
        """
172
183
        if flag and self._update_timer_callback_tag is None:
173
184
            # Will update the shown timer value every second
174
 
            self._update_timer_callback_tag = (GLib.timeout_add
175
 
                                               (1000,
176
 
                                                self.update_timer))
 
185
            self._update_timer_callback_tag = (
 
186
                GLib.timeout_add(1000,
 
187
                                 glib_safely(self.update_timer)))
177
188
        elif not (flag or self._update_timer_callback_tag is None):
178
189
            GLib.source_remove(self._update_timer_callback_tag)
179
190
            self._update_timer_callback_tag = None
180
191
 
181
192
    def checker_completed(self, exitstatus, condition, command):
182
193
        if exitstatus == 0:
183
 
            self.logger('Checker for client {} (command "{}")'
184
 
                        ' succeeded'.format(self.properties["Name"],
185
 
                                            command), level=0)
 
194
            log.debug('Checker for client %s (command "%s")'
 
195
                      " succeeded", self.properties["Name"], command)
186
196
            self.update()
187
197
            return
188
198
        # Checker failed
189
199
        if os.WIFEXITED(condition):
190
 
            self.logger('Checker for client {} (command "{}") failed'
191
 
                        ' with exit code {}'
192
 
                        .format(self.properties["Name"], command,
193
 
                                os.WEXITSTATUS(condition)))
 
200
            log.info('Checker for client %s (command "%s") failed'
 
201
                     " with exit code %d", self.properties["Name"],
 
202
                     command, os.WEXITSTATUS(condition))
194
203
        elif os.WIFSIGNALED(condition):
195
 
            self.logger('Checker for client {} (command "{}") was'
196
 
                        ' killed by signal {}'
197
 
                        .format(self.properties["Name"], command,
198
 
                                os.WTERMSIG(condition)))
 
204
            log.info('Checker for client %s (command "%s") was'
 
205
                     " killed by signal %d", self.properties["Name"],
 
206
                     command, os.WTERMSIG(condition))
199
207
        self.update()
200
208
 
201
209
    def checker_started(self, command):
202
210
        """Server signals that a checker started."""
203
 
        self.logger('Client {} started checker "{}"'
204
 
                    .format(self.properties["Name"],
205
 
                            command), level=0)
 
211
        log.debug('Client %s started checker "%s"',
 
212
                  self.properties["Name"], command)
206
213
 
207
214
    def got_secret(self):
208
 
        self.logger('Client {} received its secret'
209
 
                    .format(self.properties["Name"]))
 
215
        log.info("Client %s received its secret",
 
216
                 self.properties["Name"])
210
217
 
211
218
    def need_approval(self, timeout, default):
212
219
        if not default:
213
 
            message = 'Client {} needs approval within {} seconds'
 
220
            message = "Client %s needs approval within %f seconds"
214
221
        else:
215
 
            message = 'Client {} will get its secret in {} seconds'
216
 
        self.logger(message.format(self.properties["Name"],
217
 
                                   timeout/1000))
 
222
            message = "Client %s will get its secret in %f seconds"
 
223
        log.info(message, self.properties["Name"], timeout/1000)
218
224
 
219
225
    def rejected(self, reason):
220
 
        self.logger('Client {} was rejected; reason: {}'
221
 
                    .format(self.properties["Name"], reason))
 
226
        log.info("Client %s was rejected; reason: %s",
 
227
                 self.properties["Name"], reason)
222
228
 
223
229
    def selectable(self):
224
230
        """Make this a "selectable" widget.
225
 
        This overrides the method from urwid.FlowWidget."""
 
231
        This overrides the method from urwid.Widget."""
226
232
        return True
227
233
 
228
234
    def rows(self, maxcolrow, focus=False):
229
235
        """How many rows this widget will occupy might depend on
230
236
        whether we have focus or not.
231
 
        This overrides the method from urwid.FlowWidget"""
 
237
        This overrides the method from urwid.Widget"""
232
238
        return self.current_widget(focus).rows(maxcolrow, focus=focus)
233
239
 
234
240
    def current_widget(self, focus=False):
250
256
        # Rebuild focus and non-focus widgets using current properties
251
257
 
252
258
        # Base part of a client. Name!
253
 
        base = '{name}: '.format(name=self.properties["Name"])
 
259
        base = "{name}: ".format(name=self.properties["Name"])
254
260
        if not self.properties["Enabled"]:
255
261
            message = "DISABLED"
256
262
            self.using_timer(False)
278
284
                timer = datetime.timedelta(0)
279
285
            else:
280
286
                expires = (datetime.datetime.strptime
281
 
                           (expires, '%Y-%m-%dT%H:%M:%S.%f'))
 
287
                           (expires, "%Y-%m-%dT%H:%M:%S.%f"))
282
288
                timer = max(expires - datetime.datetime.utcnow(),
283
289
                            datetime.timedelta())
284
 
            message = ('A checker has failed! Time until client'
285
 
                       ' gets disabled: {}'
 
290
            message = ("A checker has failed! Time until client"
 
291
                       " gets disabled: {}"
286
292
                       .format(str(timer).rsplit(".", 1)[0]))
287
293
            self.using_timer(True)
288
294
        else:
326
332
 
327
333
    def render(self, maxcolrow, focus=False):
328
334
        """Render differently if we have focus.
329
 
        This overrides the method from urwid.FlowWidget"""
 
335
        This overrides the method from urwid.Widget"""
330
336
        return self.current_widget(focus).render(maxcolrow,
331
337
                                                 focus=focus)
332
338
 
333
339
    def keypress(self, maxcolrow, key):
334
340
        """Handle keys.
335
 
        This overrides the method from urwid.FlowWidget"""
 
341
        This overrides the method from urwid.Widget"""
336
342
        if key == "+":
337
343
            self.proxy.Set(client_interface, "Enabled",
338
344
                           dbus.Boolean(True), ignore_reply=True,
386
392
            self.update()
387
393
 
388
394
 
 
395
def glib_safely(func, retval=True):
 
396
    def safe_func(*args, **kwargs):
 
397
        try:
 
398
            return func(*args, **kwargs)
 
399
        except Exception:
 
400
            log.exception("")
 
401
            return retval
 
402
    return safe_func
 
403
 
 
404
 
389
405
class ConstrainedListBox(urwid.ListBox):
390
406
    """Like a normal urwid.ListBox, but will consume all "up" or
391
407
    "down" key presses, thus not allowing any containing widgets to
399
415
        return ret
400
416
 
401
417
 
402
 
class UserInterface(object):
 
418
class UserInterface:
403
419
    """This is the entire user interface - the whole screen
404
420
    with boxes, lists of client widgets, etc.
405
421
    """
406
 
    def __init__(self, max_log_length=1000, log_level=1):
 
422
    def __init__(self, max_log_length=1000):
407
423
        DBusGMainLoop(set_as_default=True)
408
424
 
409
425
        self.screen = urwid.curses_display.Screen()
443
459
        self.clients_dict = {}
444
460
 
445
461
        # We will add Text widgets to this list
446
 
        self.log = []
 
462
        self.log = urwid.SimpleListWalker([])
447
463
        self.max_log_length = max_log_length
448
464
 
449
 
        self.log_level = log_level
450
 
 
451
465
        # We keep a reference to the log widget so we can remove it
452
466
        # from the ListWalker without it getting destroyed
453
467
        self.logbox = ConstrainedListBox(self.log)
457
471
        self.log_visible = True
458
472
        self.log_wrap = "any"
459
473
 
 
474
        self.loghandler = UILogHandler(self)
 
475
 
460
476
        self.rebuild()
461
 
        self.log_message_raw(("bold",
462
 
                              "Mandos Monitor version " + version))
463
 
        self.log_message_raw(("bold",
464
 
                              "q: Quit  ?: Help"))
 
477
        self.add_log_line(("bold",
 
478
                           "Mandos Monitor version " + version))
 
479
        self.add_log_line(("bold", "q: Quit  ?: Help"))
465
480
 
466
 
        self.busname = domain + '.Mandos'
 
481
        self.busname = domain + ".Mandos"
467
482
        self.main_loop = GLib.MainLoop()
468
483
 
469
 
    def client_not_found(self, fingerprint, address):
470
 
        self.log_message("Client with address {} and fingerprint {}"
471
 
                         " could not be found"
472
 
                         .format(address, fingerprint))
 
484
    def client_not_found(self, key_id, address):
 
485
        log.info("Client with address %s and key ID %s could"
 
486
                 " not be found", address, key_id)
473
487
 
474
488
    def rebuild(self):
475
489
        """This rebuilds the User Interface.
486
500
            self.uilist.append(self.logbox)
487
501
        self.topwidget = urwid.Pile(self.uilist)
488
502
 
489
 
    def log_message(self, message, level=1):
490
 
        """Log message formatted with timestamp"""
491
 
        if level < self.log_level:
492
 
            return
493
 
        timestamp = datetime.datetime.now().isoformat()
494
 
        self.log_message_raw("{}: {}".format(timestamp, message),
495
 
                             level=level)
496
 
 
497
 
    def log_message_raw(self, markup, level=1):
498
 
        """Add a log message to the log buffer."""
499
 
        if level < self.log_level:
500
 
            return
 
503
    def add_log_line(self, markup):
501
504
        self.log.append(urwid.Text(markup, wrap=self.log_wrap))
502
505
        if self.max_log_length:
503
506
            if len(self.log) > self.max_log_length:
504
 
                del self.log[0:len(self.log)-self.max_log_length-1]
505
 
        self.logbox.set_focus(len(self.logbox.body.contents),
 
507
                del self.log[0:(len(self.log) - self.max_log_length)]
 
508
        self.logbox.set_focus(len(self.logbox.body.contents)-1,
506
509
                              coming_from="above")
507
510
        self.refresh()
508
511
 
510
513
        """Toggle visibility of the log buffer."""
511
514
        self.log_visible = not self.log_visible
512
515
        self.rebuild()
513
 
        self.log_message("Log visibility changed to: {}"
514
 
                         .format(self.log_visible), level=0)
 
516
        log.debug("Log visibility changed to: %s", self.log_visible)
515
517
 
516
518
    def change_log_display(self):
517
519
        """Change type of log display.
522
524
            self.log_wrap = "clip"
523
525
        for textwidget in self.log:
524
526
            textwidget.set_wrap_mode(self.log_wrap)
525
 
        self.log_message("Wrap mode: {}".format(self.log_wrap),
526
 
                         level=0)
 
527
        log.debug("Wrap mode: %s", self.log_wrap)
527
528
 
528
529
    def find_and_remove_client(self, path, interfaces):
529
530
        """Find a client by its object path and remove it.
537
538
            client = self.clients_dict[path]
538
539
        except KeyError:
539
540
            # not found?
540
 
            self.log_message("Unknown client {!r} removed"
541
 
                             .format(path))
 
541
            log.warning("Unknown client %s removed", path)
542
542
            return
543
543
        client.delete()
544
544
 
557
557
            proxy_object=client_proxy_object,
558
558
            update_hook=self.refresh,
559
559
            delete_hook=self.remove_client,
560
 
            logger=self.log_message,
561
560
            properties=dict(ifs_and_props[client_interface])),
562
561
                        path=path)
563
562
 
583
582
 
584
583
    def run(self):
585
584
        """Start the main loop and exit when it's done."""
 
585
        log.addHandler(self.loghandler)
 
586
        self.orig_log_propagate = log.propagate
 
587
        log.propagate = False
 
588
        self.orig_log_level = log.level
 
589
        log.setLevel("INFO")
586
590
        self.bus = dbus.SystemBus()
587
591
        mandos_dbus_objc = self.bus.get_object(
588
592
            self.busname, "/", follow_name_owner_changes=True)
592
596
            mandos_clients = (self.mandos_serv
593
597
                              .GetAllClientsWithProperties())
594
598
            if not mandos_clients:
595
 
                self.log_message_raw(("bold",
596
 
                                      "Note: Server has no clients."))
 
599
                log.warning("Note: Server has no clients.")
597
600
        except dbus.exceptions.DBusException:
598
 
            self.log_message_raw(("bold",
599
 
                                  "Note: No Mandos server running."))
 
601
            log.warning("Note: No Mandos server running.")
600
602
            mandos_clients = dbus.Dictionary()
601
603
 
602
604
        (self.mandos_serv
622
624
                proxy_object=client_proxy_object,
623
625
                properties=client,
624
626
                update_hook=self.refresh,
625
 
                delete_hook=self.remove_client,
626
 
                logger=self.log_message),
 
627
                delete_hook=self.remove_client),
627
628
                            path=path)
628
629
 
629
630
        self.refresh()
630
 
        self._input_callback_tag = (GLib.io_add_watch
631
 
                                    (sys.stdin.fileno(),
632
 
                                     GLib.IO_IN,
633
 
                                     self.process_input))
 
631
        self._input_callback_tag = (
 
632
            GLib.io_add_watch(
 
633
                GLib.IOChannel.unix_new(sys.stdin.fileno()),
 
634
                GLib.PRIORITY_DEFAULT, GLib.IO_IN,
 
635
                glib_safely(self.process_input)))
634
636
        self.main_loop.run()
635
637
        # Main loop has finished, we should close everything now
636
638
        GLib.source_remove(self._input_callback_tag)
637
 
        self.screen.stop()
 
639
        with warnings.catch_warnings():
 
640
            warnings.simplefilter("ignore", BytesWarning)
 
641
            self.screen.stop()
638
642
 
639
643
    def stop(self):
640
644
        self.main_loop.quit()
 
645
        log.removeHandler(self.loghandler)
 
646
        log.propagate = self.orig_log_propagate
641
647
 
642
648
    def process_input(self, source, condition):
643
649
        keys = self.screen.get_input()
676
682
                if not self.log_visible:
677
683
                    self.log_visible = True
678
684
                    self.rebuild()
679
 
                self.log_message_raw(("bold",
680
 
                                      "  ".
681
 
                                      join(("q: Quit",
682
 
                                            "?: Help",
683
 
                                            "l: Log window toggle",
684
 
                                            "TAB: Switch window",
685
 
                                            "w: Wrap (log lines)",
686
 
                                            "v: Toggle verbose log",
687
 
                                            ))))
688
 
                self.log_message_raw(("bold",
689
 
                                      "  "
690
 
                                      .join(("Clients:",
691
 
                                             "+: Enable",
692
 
                                             "-: Disable",
693
 
                                             "R: Remove",
694
 
                                             "s: Start new checker",
695
 
                                             "S: Stop checker",
696
 
                                             "C: Checker OK",
697
 
                                             "a: Approve",
698
 
                                             "d: Deny"))))
 
685
                self.add_log_line(("bold",
 
686
                                   "  ".join(("q: Quit",
 
687
                                              "?: Help",
 
688
                                              "l: Log window toggle",
 
689
                                              "TAB: Switch window",
 
690
                                              "w: Wrap (log lines)",
 
691
                                              "v: Toggle verbose log",
 
692
                                   ))))
 
693
                self.add_log_line(("bold",
 
694
                                   "  ".join(("Clients:",
 
695
                                              "+: Enable",
 
696
                                              "-: Disable",
 
697
                                              "R: Remove",
 
698
                                              "s: Start new checker",
 
699
                                              "S: Stop checker",
 
700
                                              "C: Checker OK",
 
701
                                              "a: Approve",
 
702
                                              "d: Deny",
 
703
                                   ))))
699
704
                self.refresh()
700
705
            elif key == "tab":
701
706
                if self.topwidget.get_focus() is self.logbox:
704
709
                    self.topwidget.set_focus(self.logbox)
705
710
                self.refresh()
706
711
            elif key == "v":
707
 
                if self.log_level == 0:
708
 
                    self.log_level = 1
709
 
                    self.log_message("Verbose mode: Off")
 
712
                if log.level < logging.INFO:
 
713
                    log.setLevel(logging.INFO)
 
714
                    log.info("Verbose mode: Off")
710
715
                else:
711
 
                    self.log_level = 0
712
 
                    self.log_message("Verbose mode: On")
 
716
                    log.setLevel(logging.NOTSET)
 
717
                    log.info("Verbose mode: On")
713
718
            # elif (key == "end" or key == "meta >" or key == "G"
714
719
            #       or key == ">"):
715
720
            #     pass            # xxx end-of-buffer
734
739
        return True
735
740
 
736
741
 
 
742
class UILogHandler(logging.Handler):
 
743
    def __init__(self, ui, *args, **kwargs):
 
744
        self.ui = ui
 
745
        super(UILogHandler, self).__init__(*args, **kwargs)
 
746
        self.setFormatter(
 
747
            logging.Formatter("%(asctime)s: %(message)s"))
 
748
    def emit(self, record):
 
749
        msg = self.format(record)
 
750
        if record.levelno > logging.INFO:
 
751
            msg = ("bold", msg)
 
752
        self.ui.add_log_line(msg)
 
753
 
 
754
 
737
755
ui = UserInterface()
738
756
try:
739
757
    ui.run()
740
758
except KeyboardInterrupt:
741
 
    ui.screen.stop()
742
 
except Exception as e:
743
 
    ui.log_message(str(e))
744
 
    ui.screen.stop()
 
759
    with warnings.catch_warnings():
 
760
        warnings.filterwarnings("ignore", "", BytesWarning)
 
761
        ui.screen.stop()
 
762
except Exception:
 
763
    with warnings.catch_warnings():
 
764
        warnings.filterwarnings("ignore", "", BytesWarning)
 
765
        ui.screen.stop()
745
766
    raise