/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-ctl

  • Committer: Teddy Hogeborn
  • Date: 2019-03-31 09:13:31 UTC
  • Revision ID: teddy@recompile.se-20190331091331-avb4odg8uz1yb5tm
mandos-ctl: Add support for D-Bus module "pydbus"

* mandos-ctl: Try to import pydbus and gi modules.
  (main): Use pydbus if available, fall back to dbus-python.
  (pydbus_adapter): New.
  (Test_pydbus_adapter_SystemBus): - '' -
  (Test_pydbus_adapter_CachingBus): - '' -

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
1
#!/usr/bin/python
2
 
# -*- after-save-hook: (lambda () (let ((command (if (fboundp 'file-local-name) (file-local-name (buffer-file-name)) (or (file-remote-p (buffer-file-name) 'localname) (buffer-file-name))))) (if (= (progn (if (get-buffer "*Test*") (kill-buffer "*Test*")) (process-file-shell-command (format "%s --check" (shell-quote-argument command)) nil "*Test*")) 0) (let ((w (get-buffer-window "*Test*"))) (if w (delete-window w))) (progn (with-current-buffer "*Test*" (compilation-mode)) (display-buffer "*Test*" '(display-buffer-in-side-window)))))); coding: utf-8 -*-
 
2
# -*- mode: python; coding: utf-8; after-save-hook: (lambda () (let ((command (if (and (boundp 'tramp-file-name-structure) (string-match (car tramp-file-name-structure) (buffer-file-name))) (tramp-file-name-localname (tramp-dissect-file-name (buffer-file-name))) (buffer-file-name)))) (if (= (shell-command (format "%s --check" (shell-quote-argument command)) "*Test*") 0) (let ((w (get-buffer-window "*Test*"))) (if w (delete-window w)) (kill-buffer "*Test*")) (display-buffer "*Test*")))); -*-
3
3
#
4
4
# Mandos Monitor - Control and monitor the Mandos server
5
5
#
78
78
 
79
79
locale.setlocale(locale.LC_ALL, "")
80
80
 
81
 
version = "1.8.4"
 
81
version = "1.8.3"
82
82
 
83
83
 
84
84
def main():
250
250
def rfc3339_duration_to_delta(duration):
251
251
    """Parse an RFC 3339 "duration" and return a datetime.timedelta
252
252
 
253
 
    >>> rfc3339_duration_to_delta("P7D") == datetime.timedelta(7)
254
 
    True
255
 
    >>> rfc3339_duration_to_delta("PT60S") == datetime.timedelta(0, 60)
256
 
    True
257
 
    >>> rfc3339_duration_to_delta("PT60M") == datetime.timedelta(hours=1)
258
 
    True
259
 
    >>> # 60 months
260
 
    >>> rfc3339_duration_to_delta("P60M") == datetime.timedelta(1680)
261
 
    True
262
 
    >>> rfc3339_duration_to_delta("PT24H") == datetime.timedelta(1)
263
 
    True
264
 
    >>> rfc3339_duration_to_delta("P1W") == datetime.timedelta(7)
265
 
    True
266
 
    >>> rfc3339_duration_to_delta("PT5M30S") == datetime.timedelta(0, 330)
267
 
    True
268
 
    >>> rfc3339_duration_to_delta("P1DT3M20S") == datetime.timedelta(1, 200)
269
 
    True
 
253
    >>> rfc3339_duration_to_delta("P7D")
 
254
    datetime.timedelta(7)
 
255
    >>> rfc3339_duration_to_delta("PT60S")
 
256
    datetime.timedelta(0, 60)
 
257
    >>> rfc3339_duration_to_delta("PT60M")
 
258
    datetime.timedelta(0, 3600)
 
259
    >>> rfc3339_duration_to_delta("P60M")
 
260
    datetime.timedelta(1680)
 
261
    >>> rfc3339_duration_to_delta("PT24H")
 
262
    datetime.timedelta(1)
 
263
    >>> rfc3339_duration_to_delta("P1W")
 
264
    datetime.timedelta(7)
 
265
    >>> rfc3339_duration_to_delta("PT5M30S")
 
266
    datetime.timedelta(0, 330)
 
267
    >>> rfc3339_duration_to_delta("P1DT3M20S")
 
268
    datetime.timedelta(1, 200)
270
269
    >>> # Can not be empty:
271
270
    >>> rfc3339_duration_to_delta("")
272
271
    Traceback (most recent call last):
382
381
    """Parse an interval string as documented by Mandos before 1.6.1,
383
382
    and return a datetime.timedelta
384
383
 
385
 
    >>> parse_pre_1_6_1_interval('7d') == datetime.timedelta(days=7)
386
 
    True
387
 
    >>> parse_pre_1_6_1_interval('60s') == datetime.timedelta(0, 60)
388
 
    True
389
 
    >>> parse_pre_1_6_1_interval('60m') == datetime.timedelta(hours=1)
390
 
    True
391
 
    >>> parse_pre_1_6_1_interval('24h') == datetime.timedelta(days=1)
392
 
    True
393
 
    >>> parse_pre_1_6_1_interval('1w') == datetime.timedelta(days=7)
394
 
    True
395
 
    >>> parse_pre_1_6_1_interval('5m 30s') == datetime.timedelta(0, 330)
396
 
    True
397
 
    >>> parse_pre_1_6_1_interval('') == datetime.timedelta(0)
398
 
    True
 
384
    >>> parse_pre_1_6_1_interval('7d')
 
385
    datetime.timedelta(7)
 
386
    >>> parse_pre_1_6_1_interval('60s')
 
387
    datetime.timedelta(0, 60)
 
388
    >>> parse_pre_1_6_1_interval('60m')
 
389
    datetime.timedelta(0, 3600)
 
390
    >>> parse_pre_1_6_1_interval('24h')
 
391
    datetime.timedelta(1)
 
392
    >>> parse_pre_1_6_1_interval('1w')
 
393
    datetime.timedelta(7)
 
394
    >>> parse_pre_1_6_1_interval('5m 30s')
 
395
    datetime.timedelta(0, 330)
 
396
    >>> parse_pre_1_6_1_interval('')
 
397
    datetime.timedelta(0)
399
398
    >>> # Ignore unknown characters, allow any order and repetitions
400
 
    >>> parse_pre_1_6_1_interval('2dxy7zz11y3m5m') == datetime.timedelta(2, 480, 18000)
401
 
    True
 
399
    >>> parse_pre_1_6_1_interval('2dxy7zz11y3m5m')
 
400
    datetime.timedelta(2, 480, 18000)
402
401
 
403
402
    """
404
403
 
572
571
                        for key, subval in value.items()}
573
572
            return value
574
573
 
575
 
        def set_client_property(self, objectpath, key, value):
576
 
            if key == "Secret":
577
 
                if not isinstance(value, bytes):
578
 
                    value = value.encode("utf-8")
579
 
                value = self.dbus_python.ByteArray(value)
580
 
            return self.set_property(self.busname, objectpath,
581
 
                                     self.client_interface, key,
582
 
                                     value)
583
574
 
584
575
    class SilenceLogger(object):
585
576
        "Simple context manager to silence a particular logger"
1321
1312
                @staticmethod
1322
1313
                def get_object(busname, objectpath):
1323
1314
                    DBusObject = collections.namedtuple(
1324
 
                        "DBusObject", ("methodname", "Set"))
 
1315
                        "DBusObject", ("methodname",))
1325
1316
                    def method(*args, **kwargs):
1326
1317
                        self.assertEqual({"dbus_interface":
1327
1318
                                          "interface"},
1328
1319
                                         kwargs)
1329
1320
                        return func(*args)
1330
 
                    def set_property(interface, key, value,
1331
 
                                     dbus_interface=None):
1332
 
                        self.assertEqual(
1333
 
                            "org.freedesktop.DBus.Properties",
1334
 
                            dbus_interface)
1335
 
                        self.assertEqual("Secret", key)
1336
 
                        return func(interface, key, value,
1337
 
                                    dbus_interface=dbus_interface)
1338
 
                    return DBusObject(methodname=method,
1339
 
                                      Set=set_property)
 
1321
                    return DBusObject(methodname=method)
1340
1322
            class Boolean(object):
1341
1323
                def __init__(self, value):
1342
1324
                    self.value = bool(value)
1348
1330
                pass
1349
1331
            class Dictionary(dict):
1350
1332
                pass
1351
 
            class ByteArray(bytes):
1352
 
                pass
1353
1333
        return mock_dbus_python
1354
1334
 
1355
1335
    def call_method(self, bus, methodname, busname, objectpath,
1532
1512
        # Make sure the dbus logger was suppressed
1533
1513
        self.assertEqual(0, counting_handler.count)
1534
1514
 
1535
 
    def test_Set_Secret_sends_bytearray(self):
1536
 
        ret = [None]
1537
 
        def func(*args, **kwargs):
1538
 
            ret[0] = (args, kwargs)
1539
 
        mock_dbus_python = self.MockDBusPython_func(func)
1540
 
        bus = dbus_python_adapter.SystemBus(mock_dbus_python)
1541
 
        bus.set_client_property("objectpath", "Secret", "value")
1542
 
        expected_call = (("se.recompile.Mandos.Client", "Secret",
1543
 
                          mock_dbus_python.ByteArray(b"value")),
1544
 
                         {"dbus_interface":
1545
 
                          "org.freedesktop.DBus.Properties"})
1546
 
        self.assertEqual(expected_call, ret[0])
1547
 
        if sys.version_info.major == 2:
1548
 
            self.assertIsInstance(ret[0][0][-1],
1549
 
                                  mock_dbus_python.ByteArray)
1550
 
 
1551
1515
    def test_get_object_converts_to_correct_exception(self):
1552
1516
        bus = dbus_python_adapter.SystemBus(
1553
1517
            self.fake_dbus_python_raises_exception_on_connect)
1781
1745
        self.assert_command_from_args(["--is-enabled", "client"],
1782
1746
                                      command.IsEnabled)
1783
1747
 
1784
 
    def assert_command_from_args(self, args, command_cls, length=1,
1785
 
                                 clients=None, **cmd_attrs):
 
1748
    def assert_command_from_args(self, args, command_cls,
 
1749
                                 **cmd_attrs):
1786
1750
        """Assert that parsing ARGS should result in an instance of
1787
1751
COMMAND_CLS with (optionally) all supplied attributes (CMD_ATTRS)."""
1788
1752
        options = self.parser.parse_args(args)
1789
1753
        check_option_syntax(self.parser, options)
1790
1754
        commands = commands_from_options(options)
1791
 
        self.assertEqual(length, len(commands))
1792
 
        for command in commands:
1793
 
            if isinstance(command, command_cls):
1794
 
                break
1795
 
        else:
1796
 
            self.assertIsInstance(command, command_cls)
1797
 
        if clients is not None:
1798
 
            self.assertEqual(clients, options.client)
 
1755
        self.assertEqual(1, len(commands))
 
1756
        command = commands[0]
 
1757
        self.assertIsInstance(command, command_cls)
1799
1758
        for key, value in cmd_attrs.items():
1800
1759
            self.assertEqual(value, getattr(command, key))
1801
1760
 
1802
 
    def assert_commands_from_args(self, args, commands, clients=None):
1803
 
        for cmd in commands:
1804
 
            self.assert_command_from_args(args, cmd,
1805
 
                                          length=len(commands),
1806
 
                                          clients=clients)
1807
 
 
1808
1761
    def test_is_enabled_short(self):
1809
1762
        self.assert_command_from_args(["-V", "client"],
1810
1763
                                      command.IsEnabled)
2001
1954
                                      verbose=True)
2002
1955
 
2003
1956
 
2004
 
    def test_manual_page_example_1(self):
2005
 
        self.assert_command_from_args("",
2006
 
                                      command.PrintTable,
2007
 
                                      clients=[],
2008
 
                                      verbose=False)
2009
 
 
2010
 
    def test_manual_page_example_2(self):
2011
 
        self.assert_command_from_args(
2012
 
            "--verbose foo1.example.org foo2.example.org".split(),
2013
 
            command.PrintTable, clients=["foo1.example.org",
2014
 
                                         "foo2.example.org"],
2015
 
            verbose=True)
2016
 
 
2017
 
    def test_manual_page_example_3(self):
2018
 
        self.assert_command_from_args("--enable --all".split(),
2019
 
                                      command.Enable,
2020
 
                                      clients=[])
2021
 
 
2022
 
    def test_manual_page_example_4(self):
2023
 
        self.assert_commands_from_args(
2024
 
            ("--timeout=PT5M --interval=PT1M foo1.example.org"
2025
 
             " foo2.example.org").split(),
2026
 
            [command.SetTimeout, command.SetInterval],
2027
 
            clients=["foo1.example.org", "foo2.example.org"])
2028
 
 
2029
 
    def test_manual_page_example_5(self):
2030
 
        self.assert_command_from_args("--approve --all".split(),
2031
 
                                      command.Approve,
2032
 
                                      clients=[])
2033
 
 
2034
 
 
2035
1957
class TestCommand(unittest.TestCase):
2036
1958
    """Abstract class for tests of command classes"""
2037
1959