/usr/sbin/mandos-monitor is in mandos 1.6.0-1.
This file is owned by root:root, with mode 0o755.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 | #!/usr/bin/python
# -*- mode: python; coding: utf-8 -*-
#
# Mandos Monitor - Control and monitor the Mandos server
#
# Copyright © 2009-2012 Teddy Hogeborn
# Copyright © 2009-2012 Björn Påhlsson
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see
# <http://www.gnu.org/licenses/>.
#
# Contact the authors at <mandos@recompile.se>.
#
from __future__ import (division, absolute_import, print_function,
unicode_literals)
from future_builtins import *
import sys
import os
import signal
import datetime
import urwid.curses_display
import urwid
from dbus.mainloop.glib import DBusGMainLoop
import gobject
import dbus
import UserList
import locale
locale.setlocale(locale.LC_ALL, '')
import logging
logging.getLogger('dbus.proxies').setLevel(logging.CRITICAL)
# Some useful constants
domain = 'se.recompile'
server_interface = domain + '.Mandos'
client_interface = domain + '.Mandos.Client'
version = "1.6.0"
# Always run in monochrome mode
urwid.curses_display.curses.has_colors = lambda : False
# Urwid doesn't support blinking, but we want it. Since we have no
# use for underline on its own, we make underline also always blink.
urwid.curses_display.curses.A_UNDERLINE |= (
urwid.curses_display.curses.A_BLINK)
def isoformat_to_datetime(iso):
"Parse an ISO 8601 date string to a datetime.datetime()"
if not iso:
return None
d, t = iso.split("T", 1)
year, month, day = d.split("-", 2)
hour, minute, second = t.split(":", 2)
second, fraction = divmod(float(second), 1)
return datetime.datetime(int(year),
int(month),
int(day),
int(hour),
int(minute),
int(second), # Whole seconds
int(fraction*1000000)) # Microseconds
class MandosClientPropertyCache(object):
"""This wraps a Mandos Client D-Bus proxy object, caches the
properties and calls a hook function when any of them are
changed.
"""
def __init__(self, proxy_object=None, properties=None, **kwargs):
self.proxy = proxy_object # Mandos Client proxy object
self.properties = dict() if properties is None else properties
self.property_changed_match = (
self.proxy.connect_to_signal("PropertyChanged",
self._property_changed,
client_interface,
byte_arrays=True))
if properties is None:
self.properties.update(
self.proxy.GetAll(client_interface,
dbus_interface
= dbus.PROPERTIES_IFACE))
super(MandosClientPropertyCache, self).__init__(**kwargs)
def _property_changed(self, property, value):
"""Helper which takes positional arguments"""
return self.property_changed(property=property, value=value)
def property_changed(self, property=None, value=None):
"""This is called whenever we get a PropertyChanged signal
It updates the changed property in the "properties" dict.
"""
# Update properties dict with new value
self.properties[property] = value
def delete(self):
self.property_changed_match.remove()
class MandosClientWidget(urwid.FlowWidget, MandosClientPropertyCache):
"""A Mandos Client which is visible on the screen.
"""
def __init__(self, server_proxy_object=None, update_hook=None,
delete_hook=None, logger=None, **kwargs):
# Called on update
self.update_hook = update_hook
# Called on delete
self.delete_hook = delete_hook
# Mandos Server proxy object
self.server_proxy_object = server_proxy_object
# Logger
self.logger = logger
self._update_timer_callback_tag = None
# The widget shown normally
self._text_widget = urwid.Text("")
# The widget shown when we have focus
self._focus_text_widget = urwid.Text("")
super(MandosClientWidget, self).__init__(**kwargs)
self.update()
self.opened = False
self.match_objects = (
self.proxy.connect_to_signal("CheckerCompleted",
self.checker_completed,
client_interface,
byte_arrays=True),
self.proxy.connect_to_signal("CheckerStarted",
self.checker_started,
client_interface,
byte_arrays=True),
self.proxy.connect_to_signal("GotSecret",
self.got_secret,
client_interface,
byte_arrays=True),
self.proxy.connect_to_signal("NeedApproval",
self.need_approval,
client_interface,
byte_arrays=True),
self.proxy.connect_to_signal("Rejected",
self.rejected,
client_interface,
byte_arrays=True))
#self.logger('Created client {0}'
# .format(self.properties["Name"]))
def using_timer(self, flag):
"""Call this method with True or False when timer should be
activated or deactivated.
"""
if flag and self._update_timer_callback_tag is None:
# Will update the shown timer value every second
self._update_timer_callback_tag = (gobject.timeout_add
(1000,
self.update_timer))
elif not (flag or self._update_timer_callback_tag is None):
gobject.source_remove(self._update_timer_callback_tag)
self._update_timer_callback_tag = None
def checker_completed(self, exitstatus, condition, command):
if exitstatus == 0:
self.update()
return
# Checker failed
if os.WIFEXITED(condition):
self.logger('Checker for client {0} (command "{1}")'
' failed with exit code {2}'
.format(self.properties["Name"], command,
os.WEXITSTATUS(condition)))
elif os.WIFSIGNALED(condition):
self.logger('Checker for client {0} (command "{1}") was'
' killed by signal {2}'
.format(self.properties["Name"], command,
os.WTERMSIG(condition)))
elif os.WCOREDUMP(condition):
self.logger('Checker for client {0} (command "{1}")'
' dumped core'
.format(self.properties["Name"], command))
else:
self.logger('Checker for client {0} completed'
' mysteriously'
.format(self.properties["Name"]))
self.update()
def checker_started(self, command):
"""Server signals that a checker started. This could be useful
to log in the future. """
#self.logger('Client {0} started checker "{1}"'
# .format(self.properties["Name"],
# unicode(command)))
pass
def got_secret(self):
self.logger('Client {0} received its secret'
.format(self.properties["Name"]))
def need_approval(self, timeout, default):
if not default:
message = 'Client {0} needs approval within {1} seconds'
else:
message = 'Client {0} will get its secret in {1} seconds'
self.logger(message.format(self.properties["Name"],
timeout/1000))
def rejected(self, reason):
self.logger('Client {0} was rejected; reason: {1}'
.format(self.properties["Name"], reason))
def selectable(self):
"""Make this a "selectable" widget.
This overrides the method from urwid.FlowWidget."""
return True
def rows(self, maxcolrow, focus=False):
"""How many rows this widget will occupy might depend on
whether we have focus or not.
This overrides the method from urwid.FlowWidget"""
return self.current_widget(focus).rows(maxcolrow, focus=focus)
def current_widget(self, focus=False):
if focus or self.opened:
return self._focus_widget
return self._widget
def update(self):
"Called when what is visible on the screen should be updated."
# How to add standout mode to a style
with_standout = { "normal": "standout",
"bold": "bold-standout",
"underline-blink":
"underline-blink-standout",
"bold-underline-blink":
"bold-underline-blink-standout",
}
# Rebuild focus and non-focus widgets using current properties
# Base part of a client. Name!
base = '{name}: '.format(name=self.properties["Name"])
if not self.properties["Enabled"]:
message = "DISABLED"
self.using_timer(False)
elif self.properties["ApprovalPending"]:
timeout = datetime.timedelta(milliseconds
= self.properties
["ApprovalDelay"])
last_approval_request = isoformat_to_datetime(
self.properties["LastApprovalRequest"])
if last_approval_request is not None:
timer = max(timeout - (datetime.datetime.utcnow()
- last_approval_request),
datetime.timedelta())
else:
timer = datetime.timedelta()
if self.properties["ApprovedByDefault"]:
message = "Approval in {0}. (d)eny?"
else:
message = "Denial in {0}. (a)pprove?"
message = message.format(unicode(timer).rsplit(".", 1)[0])
self.using_timer(True)
elif self.properties["LastCheckerStatus"] != 0:
# When checker has failed, show timer until client expires
expires = self.properties["Expires"]
if expires == "":
timer = datetime.timedelta(0)
else:
expires = (datetime.datetime.strptime
(expires, '%Y-%m-%dT%H:%M:%S.%f'))
timer = max(expires - datetime.datetime.utcnow(),
datetime.timedelta())
message = ('A checker has failed! Time until client'
' gets disabled: {0}'
.format(unicode(timer).rsplit(".", 1)[0]))
self.using_timer(True)
else:
message = "enabled"
self.using_timer(False)
self._text = "{0}{1}".format(base, message)
if not urwid.supports_unicode():
self._text = self._text.encode("ascii", "replace")
textlist = [("normal", self._text)]
self._text_widget.set_text(textlist)
self._focus_text_widget.set_text([(with_standout[text[0]],
text[1])
if isinstance(text, tuple)
else text
for text in textlist])
self._widget = self._text_widget
self._focus_widget = urwid.AttrWrap(self._focus_text_widget,
"standout")
# Run update hook, if any
if self.update_hook is not None:
self.update_hook()
def update_timer(self):
"""called by gobject. Will indefinitely loop until
gobject.source_remove() on tag is called"""
self.update()
return True # Keep calling this
def delete(self, **kwargs):
if self._update_timer_callback_tag is not None:
gobject.source_remove(self._update_timer_callback_tag)
self._update_timer_callback_tag = None
for match in self.match_objects:
match.remove()
self.match_objects = ()
if self.delete_hook is not None:
self.delete_hook(self)
return super(MandosClientWidget, self).delete(**kwargs)
def render(self, maxcolrow, focus=False):
"""Render differently if we have focus.
This overrides the method from urwid.FlowWidget"""
return self.current_widget(focus).render(maxcolrow,
focus=focus)
def keypress(self, maxcolrow, key):
"""Handle keys.
This overrides the method from urwid.FlowWidget"""
if key == "+":
self.proxy.Enable(dbus_interface = client_interface,
ignore_reply=True)
elif key == "-":
self.proxy.Disable(dbus_interface = client_interface,
ignore_reply=True)
elif key == "a":
self.proxy.Approve(dbus.Boolean(True, variant_level=1),
dbus_interface = client_interface,
ignore_reply=True)
elif key == "d":
self.proxy.Approve(dbus.Boolean(False, variant_level=1),
dbus_interface = client_interface,
ignore_reply=True)
elif key == "R" or key == "_" or key == "ctrl k":
self.server_proxy_object.RemoveClient(self.proxy
.object_path,
ignore_reply=True)
elif key == "s":
self.proxy.StartChecker(dbus_interface = client_interface,
ignore_reply=True)
elif key == "S":
self.proxy.StopChecker(dbus_interface = client_interface,
ignore_reply=True)
elif key == "C":
self.proxy.CheckedOK(dbus_interface = client_interface,
ignore_reply=True)
# xxx
# elif key == "p" or key == "=":
# self.proxy.pause()
# elif key == "u" or key == ":":
# self.proxy.unpause()
# elif key == "RET":
# self.open()
else:
return key
def property_changed(self, property=None, **kwargs):
"""Call self.update() if old value is not new value.
This overrides the method from MandosClientPropertyCache"""
property_name = unicode(property)
old_value = self.properties.get(property_name)
super(MandosClientWidget, self).property_changed(
property=property, **kwargs)
if self.properties.get(property_name) != old_value:
self.update()
class ConstrainedListBox(urwid.ListBox):
"""Like a normal urwid.ListBox, but will consume all "up" or
"down" key presses, thus not allowing any containing widgets to
use them as an excuse to shift focus away from this widget.
"""
def keypress(self, *args, **kwargs):
ret = super(ConstrainedListBox, self).keypress(*args, **kwargs)
if ret in ("up", "down"):
return
return ret
class UserInterface(object):
"""This is the entire user interface - the whole screen
with boxes, lists of client widgets, etc.
"""
def __init__(self, max_log_length=1000):
DBusGMainLoop(set_as_default=True)
self.screen = urwid.curses_display.Screen()
self.screen.register_palette((
("normal",
"default", "default", None),
("bold",
"default", "default", "bold"),
("underline-blink",
"default", "default", "underline"),
("standout",
"default", "default", "standout"),
("bold-underline-blink",
"default", "default", ("bold", "underline")),
("bold-standout",
"default", "default", ("bold", "standout")),
("underline-blink-standout",
"default", "default", ("underline", "standout")),
("bold-underline-blink-standout",
"default", "default", ("bold", "underline",
"standout")),
))
if urwid.supports_unicode():
self.divider = "─" # \u2500
#self.divider = "━" # \u2501
else:
#self.divider = "-" # \u002d
self.divider = "_" # \u005f
self.screen.start()
self.size = self.screen.get_cols_rows()
self.clients = urwid.SimpleListWalker([])
self.clients_dict = {}
# We will add Text widgets to this list
self.log = []
self.max_log_length = max_log_length
# We keep a reference to the log widget so we can remove it
# from the ListWalker without it getting destroyed
self.logbox = ConstrainedListBox(self.log)
# This keeps track of whether self.uilist currently has
# self.logbox in it or not
self.log_visible = True
self.log_wrap = "any"
self.rebuild()
self.log_message_raw(("bold",
"Mandos Monitor version " + version))
self.log_message_raw(("bold",
"q: Quit ?: Help"))
self.busname = domain + '.Mandos'
self.main_loop = gobject.MainLoop()
def client_not_found(self, fingerprint, address):
self.log_message("Client with address {0} and fingerprint"
" {1} could not be found"
.format(address, fingerprint))
def rebuild(self):
"""This rebuilds the User Interface.
Call this when the widget layout needs to change"""
self.uilist = []
#self.uilist.append(urwid.ListBox(self.clients))
self.uilist.append(urwid.Frame(ConstrainedListBox(self.
clients),
#header=urwid.Divider(),
header=None,
footer=
urwid.Divider(div_char=
self.divider)))
if self.log_visible:
self.uilist.append(self.logbox)
self.topwidget = urwid.Pile(self.uilist)
def log_message(self, message):
timestamp = datetime.datetime.now().isoformat()
self.log_message_raw(timestamp + ": " + message)
def log_message_raw(self, markup):
"""Add a log message to the log buffer."""
self.log.append(urwid.Text(markup, wrap=self.log_wrap))
if (self.max_log_length
and len(self.log) > self.max_log_length):
del self.log[0:len(self.log)-self.max_log_length-1]
self.logbox.set_focus(len(self.logbox.body.contents),
coming_from="above")
self.refresh()
def toggle_log_display(self):
"""Toggle visibility of the log buffer."""
self.log_visible = not self.log_visible
self.rebuild()
#self.log_message("Log visibility changed to: "
# + unicode(self.log_visible))
def change_log_display(self):
"""Change type of log display.
Currently, this toggles wrapping of text lines."""
if self.log_wrap == "clip":
self.log_wrap = "any"
else:
self.log_wrap = "clip"
for textwidget in self.log:
textwidget.set_wrap_mode(self.log_wrap)
#self.log_message("Wrap mode: " + self.log_wrap)
def find_and_remove_client(self, path, name):
"""Find a client by its object path and remove it.
This is connected to the ClientRemoved signal from the
Mandos server object."""
try:
client = self.clients_dict[path]
except KeyError:
# not found?
self.log_message("Unknown client {0!r} ({1!r}) removed"
.format(name, path))
return
client.delete()
def add_new_client(self, path):
client_proxy_object = self.bus.get_object(self.busname, path)
self.add_client(MandosClientWidget(server_proxy_object
=self.mandos_serv,
proxy_object
=client_proxy_object,
update_hook
=self.refresh,
delete_hook
=self.remove_client,
logger
=self.log_message),
path=path)
def add_client(self, client, path=None):
self.clients.append(client)
if path is None:
path = client.proxy.object_path
self.clients_dict[path] = client
self.clients.sort(None, lambda c: c.properties["Name"])
self.refresh()
def remove_client(self, client, path=None):
self.clients.remove(client)
if path is None:
path = client.proxy.object_path
del self.clients_dict[path]
if not self.clients_dict:
# Work around bug in Urwid 0.9.8.3 - if a SimpleListWalker
# is completely emptied, we need to recreate it.
self.clients = urwid.SimpleListWalker([])
self.rebuild()
self.refresh()
def refresh(self):
"""Redraw the screen"""
canvas = self.topwidget.render(self.size, focus=True)
self.screen.draw_screen(self.size, canvas)
def run(self):
"""Start the main loop and exit when it's done."""
self.bus = dbus.SystemBus()
mandos_dbus_objc = self.bus.get_object(
self.busname, "/", follow_name_owner_changes=True)
self.mandos_serv = dbus.Interface(mandos_dbus_objc,
dbus_interface
= server_interface)
try:
mandos_clients = (self.mandos_serv
.GetAllClientsWithProperties())
except dbus.exceptions.DBusException:
mandos_clients = dbus.Dictionary()
(self.mandos_serv
.connect_to_signal("ClientRemoved",
self.find_and_remove_client,
dbus_interface=server_interface,
byte_arrays=True))
(self.mandos_serv
.connect_to_signal("ClientAdded",
self.add_new_client,
dbus_interface=server_interface,
byte_arrays=True))
(self.mandos_serv
.connect_to_signal("ClientNotFound",
self.client_not_found,
dbus_interface=server_interface,
byte_arrays=True))
for path, client in mandos_clients.iteritems():
client_proxy_object = self.bus.get_object(self.busname,
path)
self.add_client(MandosClientWidget(server_proxy_object
=self.mandos_serv,
proxy_object
=client_proxy_object,
properties=client,
update_hook
=self.refresh,
delete_hook
=self.remove_client,
logger
=self.log_message),
path=path)
self.refresh()
self._input_callback_tag = (gobject.io_add_watch
(sys.stdin.fileno(),
gobject.IO_IN,
self.process_input))
self.main_loop.run()
# Main loop has finished, we should close everything now
gobject.source_remove(self._input_callback_tag)
self.screen.stop()
def stop(self):
self.main_loop.quit()
def process_input(self, source, condition):
keys = self.screen.get_input()
translations = { "ctrl n": "down", # Emacs
"ctrl p": "up", # Emacs
"ctrl v": "page down", # Emacs
"meta v": "page up", # Emacs
" ": "page down", # less
"f": "page down", # less
"b": "page up", # less
"j": "down", # vi
"k": "up", # vi
}
for key in keys:
try:
key = translations[key]
except KeyError: # :-)
pass
if key == "q" or key == "Q":
self.stop()
break
elif key == "window resize":
self.size = self.screen.get_cols_rows()
self.refresh()
elif key == "\f": # Ctrl-L
self.refresh()
elif key == "l" or key == "D":
self.toggle_log_display()
self.refresh()
elif key == "w" or key == "i":
self.change_log_display()
self.refresh()
elif key == "?" or key == "f1" or key == "esc":
if not self.log_visible:
self.log_visible = True
self.rebuild()
self.log_message_raw(("bold",
" ".
join(("q: Quit",
"?: Help",
"l: Log window toggle",
"TAB: Switch window",
"w: Wrap (log)"))))
self.log_message_raw(("bold",
" "
.join(("Clients:",
"+: Enable",
"-: Disable",
"R: Remove",
"s: Start new checker",
"S: Stop checker",
"C: Checker OK",
"a: Approve",
"d: Deny"))))
self.refresh()
elif key == "tab":
if self.topwidget.get_focus() is self.logbox:
self.topwidget.set_focus(0)
else:
self.topwidget.set_focus(self.logbox)
self.refresh()
#elif (key == "end" or key == "meta >" or key == "G"
# or key == ">"):
# pass # xxx end-of-buffer
#elif (key == "home" or key == "meta <" or key == "g"
# or key == "<"):
# pass # xxx beginning-of-buffer
#elif key == "ctrl e" or key == "$":
# pass # xxx move-end-of-line
#elif key == "ctrl a" or key == "^":
# pass # xxx move-beginning-of-line
#elif key == "ctrl b" or key == "meta (" or key == "h":
# pass # xxx left
#elif key == "ctrl f" or key == "meta )" or key == "l":
# pass # xxx right
#elif key == "a":
# pass # scroll up log
#elif key == "z":
# pass # scroll down log
elif self.topwidget.selectable():
self.topwidget.keypress(self.size, key)
self.refresh()
return True
ui = UserInterface()
try:
ui.run()
except KeyboardInterrupt:
ui.screen.stop()
except Exception, e:
ui.log_message(unicode(e))
ui.screen.stop()
raise
|