/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-08-05 14:31:51 UTC
  • Revision ID: teddy@recompile.se-20190805143151-lt5d97wqif3t8250
Client: Debian package fix: Make uninstall when using dracut(8) work

Use the same logic to rebuild the initramfs image when uninstalling as
when installing the package.

* debian/mandos-client.postrm (update_initramfs): Use the same logic
  as the update_initramfs function in debian/mandos-client.postinst.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
1
#!/usr/bin/python
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*")))); -*-
 
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 -*-
3
3
#
4
4
# Mandos Monitor - Control and monitor the Mandos server
5
5
#
46
46
import tempfile
47
47
import contextlib
48
48
 
49
 
import dbus as dbus_python
 
49
try:
 
50
    import pydbus
 
51
    import gi
 
52
    dbus_python = None
 
53
except ImportError:
 
54
    import dbus as dbus_python
 
55
    pydbus = None
 
56
    class gi(object):
 
57
        """Dummy gi module, for the tests"""
 
58
        class repository(object):
 
59
            class GLib(object):
 
60
                class Error(Exception):
 
61
                    pass
50
62
 
51
63
# Show warnings by default
52
64
if not sys.warnoptions:
66
78
 
67
79
locale.setlocale(locale.LC_ALL, "")
68
80
 
69
 
version = "1.8.3"
 
81
version = "1.8.6"
70
82
 
71
83
 
72
84
def main():
81
93
    if options.debug:
82
94
        log.setLevel(logging.DEBUG)
83
95
 
84
 
    bus = dbus_python_adapter.CachingBus(dbus_python)
 
96
    if pydbus is not None:
 
97
        bus = pydbus_adapter.CachingBus(pydbus)
 
98
    else:
 
99
        bus = dbus_python_adapter.CachingBus(dbus_python)
85
100
 
86
101
    try:
87
102
        all_clients = bus.get_clients_and_properties()
235
250
def rfc3339_duration_to_delta(duration):
236
251
    """Parse an RFC 3339 "duration" and return a datetime.timedelta
237
252
 
238
 
    >>> rfc3339_duration_to_delta("P7D")
239
 
    datetime.timedelta(7)
240
 
    >>> rfc3339_duration_to_delta("PT60S")
241
 
    datetime.timedelta(0, 60)
242
 
    >>> rfc3339_duration_to_delta("PT60M")
243
 
    datetime.timedelta(0, 3600)
244
 
    >>> rfc3339_duration_to_delta("P60M")
245
 
    datetime.timedelta(1680)
246
 
    >>> rfc3339_duration_to_delta("PT24H")
247
 
    datetime.timedelta(1)
248
 
    >>> rfc3339_duration_to_delta("P1W")
249
 
    datetime.timedelta(7)
250
 
    >>> rfc3339_duration_to_delta("PT5M30S")
251
 
    datetime.timedelta(0, 330)
252
 
    >>> rfc3339_duration_to_delta("P1DT3M20S")
253
 
    datetime.timedelta(1, 200)
 
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
254
270
    >>> # Can not be empty:
255
271
    >>> rfc3339_duration_to_delta("")
256
272
    Traceback (most recent call last):
366
382
    """Parse an interval string as documented by Mandos before 1.6.1,
367
383
    and return a datetime.timedelta
368
384
 
369
 
    >>> parse_pre_1_6_1_interval('7d')
370
 
    datetime.timedelta(7)
371
 
    >>> parse_pre_1_6_1_interval('60s')
372
 
    datetime.timedelta(0, 60)
373
 
    >>> parse_pre_1_6_1_interval('60m')
374
 
    datetime.timedelta(0, 3600)
375
 
    >>> parse_pre_1_6_1_interval('24h')
376
 
    datetime.timedelta(1)
377
 
    >>> parse_pre_1_6_1_interval('1w')
378
 
    datetime.timedelta(7)
379
 
    >>> parse_pre_1_6_1_interval('5m 30s')
380
 
    datetime.timedelta(0, 330)
381
 
    >>> parse_pre_1_6_1_interval('')
382
 
    datetime.timedelta(0)
 
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
383
399
    >>> # Ignore unknown characters, allow any order and repetitions
384
 
    >>> parse_pre_1_6_1_interval('2dxy7zz11y3m5m')
385
 
    datetime.timedelta(2, 480, 18000)
 
400
    >>> parse_pre_1_6_1_interval('2dxy7zz11y3m5m') == datetime.timedelta(2, 480, 18000)
 
401
    True
386
402
 
387
403
    """
388
404
 
556
572
                        for key, subval in value.items()}
557
573
            return value
558
574
 
 
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)
559
583
 
560
584
    class SilenceLogger(object):
561
585
        "Simple context manager to silence a particular logger"
592
616
                return new_object
593
617
 
594
618
 
 
619
class pydbus_adapter(object):
 
620
    class SystemBus(dbus.MandosBus):
 
621
        def __init__(self, module=pydbus):
 
622
            self.pydbus = module
 
623
            self.bus = self.pydbus.SystemBus()
 
624
 
 
625
        @contextlib.contextmanager
 
626
        def convert_exception(self, exception_class=dbus.Error):
 
627
            try:
 
628
                yield
 
629
            except gi.repository.GLib.Error as e:
 
630
                # This does what "raise from" would do
 
631
                exc = exception_class(*e.args)
 
632
                exc.__cause__ = e
 
633
                raise exc
 
634
 
 
635
        def call_method(self, methodname, busname, objectpath,
 
636
                        interface, *args):
 
637
            proxy_object = self.get(busname, objectpath)
 
638
            log.debug("D-Bus: %s:%s:%s.%s(%s)", busname, objectpath,
 
639
                      interface, methodname,
 
640
                      ", ".join(repr(a) for a in args))
 
641
            method = getattr(proxy_object[interface], methodname)
 
642
            with self.convert_exception():
 
643
                return method(*args)
 
644
 
 
645
        def get(self, busname, objectpath):
 
646
            log.debug("D-Bus: Connect to: (busname=%r, path=%r)",
 
647
                      busname, objectpath)
 
648
            with self.convert_exception(dbus.ConnectFailed):
 
649
                if sys.version_info.major <= 2:
 
650
                    with warnings.catch_warnings():
 
651
                        warnings.filterwarnings(
 
652
                            "ignore", "", DeprecationWarning,
 
653
                            r"^xml\.etree\.ElementTree$")
 
654
                        return self.bus.get(busname, objectpath)
 
655
                else:
 
656
                    return self.bus.get(busname, objectpath)
 
657
 
 
658
        def set_property(self, busname, objectpath, interface, key,
 
659
                         value):
 
660
            proxy_object = self.get(busname, objectpath)
 
661
            log.debug("D-Bus: %s:%s:%s.Set(%r, %r, %r)", busname,
 
662
                      objectpath, self.properties_iface, interface,
 
663
                      key, value)
 
664
            setattr(proxy_object[interface], key, value)
 
665
 
 
666
    class CachingBus(SystemBus):
 
667
        """A caching layer for pydbus_adapter.SystemBus"""
 
668
        def __init__(self, *args, **kwargs):
 
669
            self.object_cache = {}
 
670
            super(pydbus_adapter.CachingBus,
 
671
                  self).__init__(*args, **kwargs)
 
672
        def get(self, busname, objectpath):
 
673
            try:
 
674
                return self.object_cache[(busname, objectpath)]
 
675
            except KeyError:
 
676
                new_object = (super(pydbus_adapter.CachingBus, self)
 
677
                              .get(busname, objectpath))
 
678
                self.object_cache[(busname, objectpath)]  = new_object
 
679
                return new_object
 
680
 
 
681
 
595
682
def commands_from_options(options):
596
683
 
597
684
    commands = list(options.commands)
1234
1321
                @staticmethod
1235
1322
                def get_object(busname, objectpath):
1236
1323
                    DBusObject = collections.namedtuple(
1237
 
                        "DBusObject", ("methodname",))
 
1324
                        "DBusObject", ("methodname", "Set"))
1238
1325
                    def method(*args, **kwargs):
1239
1326
                        self.assertEqual({"dbus_interface":
1240
1327
                                          "interface"},
1241
1328
                                         kwargs)
1242
1329
                        return func(*args)
1243
 
                    return DBusObject(methodname=method)
 
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)
1244
1340
            class Boolean(object):
1245
1341
                def __init__(self, value):
1246
1342
                    self.value = bool(value)
1252
1348
                pass
1253
1349
            class Dictionary(dict):
1254
1350
                pass
 
1351
            class ByteArray(bytes):
 
1352
                pass
1255
1353
        return mock_dbus_python
1256
1354
 
1257
1355
    def call_method(self, bus, methodname, busname, objectpath,
1434
1532
        # Make sure the dbus logger was suppressed
1435
1533
        self.assertEqual(0, counting_handler.count)
1436
1534
 
 
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
 
1437
1551
    def test_get_object_converts_to_correct_exception(self):
1438
1552
        bus = dbus_python_adapter.SystemBus(
1439
1553
            self.fake_dbus_python_raises_exception_on_connect)
1508
1622
        self.assertIs(obj1, obj1b)
1509
1623
 
1510
1624
 
 
1625
class Test_pydbus_adapter_SystemBus(TestCaseWithAssertLogs):
 
1626
 
 
1627
    def Stub_pydbus_func(self, func):
 
1628
        class stub_pydbus(object):
 
1629
            """stub pydbus module"""
 
1630
            class SystemBus(object):
 
1631
                @staticmethod
 
1632
                def get(busname, objectpath):
 
1633
                    DBusObject = collections.namedtuple(
 
1634
                        "DBusObject", ("methodname",))
 
1635
                    return {"interface":
 
1636
                            DBusObject(methodname=func)}
 
1637
        return stub_pydbus
 
1638
 
 
1639
    def call_method(self, bus, methodname, busname, objectpath,
 
1640
                    interface, *args):
 
1641
        with self.assertLogs(log, logging.DEBUG):
 
1642
            return bus.call_method(methodname, busname, objectpath,
 
1643
                                   interface, *args)
 
1644
 
 
1645
    def test_call_method_returns(self):
 
1646
        expected_method_return = Unique()
 
1647
        method_args = (Unique(), Unique())
 
1648
        def func(*args):
 
1649
            self.assertEqual(len(method_args), len(args))
 
1650
            for marg, arg in zip(method_args, args):
 
1651
                self.assertIs(marg, arg)
 
1652
            return expected_method_return
 
1653
        stub_pydbus = self.Stub_pydbus_func(func)
 
1654
        bus = pydbus_adapter.SystemBus(stub_pydbus)
 
1655
        ret = self.call_method(bus, "methodname", "busname",
 
1656
                               "objectpath", "interface",
 
1657
                               *method_args)
 
1658
        self.assertIs(ret, expected_method_return)
 
1659
 
 
1660
    def test_call_method_handles_exception(self):
 
1661
        dbus_logger = logging.getLogger("dbus.proxies")
 
1662
 
 
1663
        def func():
 
1664
            raise gi.repository.GLib.Error()
 
1665
 
 
1666
        stub_pydbus = self.Stub_pydbus_func(func)
 
1667
        bus = pydbus_adapter.SystemBus(stub_pydbus)
 
1668
 
 
1669
        with self.assertRaises(dbus.Error) as e:
 
1670
            self.call_method(bus, "methodname", "busname",
 
1671
                             "objectpath", "interface")
 
1672
 
 
1673
        self.assertNotIsInstance(e, dbus.ConnectFailed)
 
1674
 
 
1675
    def test_get_converts_to_correct_exception(self):
 
1676
        bus = pydbus_adapter.SystemBus(
 
1677
            self.fake_pydbus_raises_exception_on_connect)
 
1678
        with self.assertRaises(dbus.ConnectFailed):
 
1679
            self.call_method(bus, "methodname", "busname",
 
1680
                             "objectpath", "interface")
 
1681
 
 
1682
    class fake_pydbus_raises_exception_on_connect(object):
 
1683
        """fake dbus-python module"""
 
1684
        @classmethod
 
1685
        def SystemBus(cls):
 
1686
            def get(busname, objectpath):
 
1687
                raise gi.repository.GLib.Error()
 
1688
            Bus = collections.namedtuple("Bus", ["get"])
 
1689
            return Bus(get=get)
 
1690
 
 
1691
    def test_set_property_uses_setattr(self):
 
1692
        class Object(object):
 
1693
            pass
 
1694
        obj = Object()
 
1695
        class pydbus_spy(object):
 
1696
            class SystemBus(object):
 
1697
                @staticmethod
 
1698
                def get(busname, objectpath):
 
1699
                    return {"interface": obj}
 
1700
        bus = pydbus_adapter.SystemBus(pydbus_spy)
 
1701
        value = Unique()
 
1702
        bus.set_property("busname", "objectpath", "interface", "key",
 
1703
                         value)
 
1704
        self.assertIs(value, obj.key)
 
1705
 
 
1706
    def test_get_suppresses_xml_deprecation_warning(self):
 
1707
        if sys.version_info.major >= 3:
 
1708
            return
 
1709
        class stub_pydbus_get(object):
 
1710
            class SystemBus(object):
 
1711
                @staticmethod
 
1712
                def get(busname, objectpath):
 
1713
                    warnings.warn_explicit(
 
1714
                        "deprecated", DeprecationWarning,
 
1715
                        "xml.etree.ElementTree", 0)
 
1716
        bus = pydbus_adapter.SystemBus(stub_pydbus_get)
 
1717
        with warnings.catch_warnings(record=True) as w:
 
1718
            warnings.simplefilter("always")
 
1719
            bus.get("busname", "objectpath")
 
1720
            self.assertEqual(0, len(w))
 
1721
 
 
1722
 
 
1723
class Test_pydbus_adapter_CachingBus(unittest.TestCase):
 
1724
    class stub_pydbus(object):
 
1725
        """stub pydbus module"""
 
1726
        class SystemBus(object):
 
1727
            @staticmethod
 
1728
            def get(busname, objectpath):
 
1729
                return Unique()
 
1730
 
 
1731
    def setUp(self):
 
1732
        self.bus = pydbus_adapter.CachingBus(self.stub_pydbus)
 
1733
 
 
1734
    def test_returns_distinct_objectpaths(self):
 
1735
        obj1 = self.bus.get("busname", "objectpath1")
 
1736
        self.assertIsInstance(obj1, Unique)
 
1737
        obj2 = self.bus.get("busname", "objectpath2")
 
1738
        self.assertIsInstance(obj2, Unique)
 
1739
        self.assertIsNot(obj1, obj2)
 
1740
 
 
1741
    def test_returns_distinct_busnames(self):
 
1742
        obj1 = self.bus.get("busname1", "objectpath")
 
1743
        self.assertIsInstance(obj1, Unique)
 
1744
        obj2 = self.bus.get("busname2", "objectpath")
 
1745
        self.assertIsInstance(obj2, Unique)
 
1746
        self.assertIsNot(obj1, obj2)
 
1747
 
 
1748
    def test_returns_distinct_both(self):
 
1749
        obj1 = self.bus.get("busname1", "objectpath")
 
1750
        self.assertIsInstance(obj1, Unique)
 
1751
        obj2 = self.bus.get("busname2", "objectpath")
 
1752
        self.assertIsInstance(obj2, Unique)
 
1753
        self.assertIsNot(obj1, obj2)
 
1754
 
 
1755
    def test_returns_same(self):
 
1756
        obj1 = self.bus.get("busname", "objectpath")
 
1757
        self.assertIsInstance(obj1, Unique)
 
1758
        obj2 = self.bus.get("busname", "objectpath")
 
1759
        self.assertIsInstance(obj2, Unique)
 
1760
        self.assertIs(obj1, obj2)
 
1761
 
 
1762
    def test_returns_same_old(self):
 
1763
        obj1 = self.bus.get("busname1", "objectpath1")
 
1764
        self.assertIsInstance(obj1, Unique)
 
1765
        obj2 = self.bus.get("busname2", "objectpath2")
 
1766
        self.assertIsInstance(obj2, Unique)
 
1767
        obj1b = self.bus.get("busname1", "objectpath1")
 
1768
        self.assertIsInstance(obj1b, Unique)
 
1769
        self.assertIsNot(obj1, obj2)
 
1770
        self.assertIsNot(obj2, obj1b)
 
1771
        self.assertIs(obj1, obj1b)
 
1772
 
 
1773
 
1511
1774
class Test_commands_from_options(unittest.TestCase):
1512
1775
 
1513
1776
    def setUp(self):
1518
1781
        self.assert_command_from_args(["--is-enabled", "client"],
1519
1782
                                      command.IsEnabled)
1520
1783
 
1521
 
    def assert_command_from_args(self, args, command_cls,
1522
 
                                 **cmd_attrs):
 
1784
    def assert_command_from_args(self, args, command_cls, length=1,
 
1785
                                 clients=None, **cmd_attrs):
1523
1786
        """Assert that parsing ARGS should result in an instance of
1524
1787
COMMAND_CLS with (optionally) all supplied attributes (CMD_ATTRS)."""
1525
1788
        options = self.parser.parse_args(args)
1526
1789
        check_option_syntax(self.parser, options)
1527
1790
        commands = commands_from_options(options)
1528
 
        self.assertEqual(1, len(commands))
1529
 
        command = commands[0]
1530
 
        self.assertIsInstance(command, command_cls)
 
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)
1531
1799
        for key, value in cmd_attrs.items():
1532
1800
            self.assertEqual(value, getattr(command, key))
1533
1801
 
 
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
 
1534
1808
    def test_is_enabled_short(self):
1535
1809
        self.assert_command_from_args(["-V", "client"],
1536
1810
                                      command.IsEnabled)
1727
2001
                                      verbose=True)
1728
2002
 
1729
2003
 
 
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
 
1730
2035
class TestCommand(unittest.TestCase):
1731
2036
    """Abstract class for tests of command classes"""
1732
2037