479
479
if options.is_enabled:
480
commands.append(IsEnabledCmd())
480
commands.append(command.IsEnabled())
482
482
if options.approve:
483
commands.append(ApproveCmd())
483
commands.append(command.Approve())
486
commands.append(DenyCmd())
486
commands.append(command.Deny())
488
488
if options.remove:
489
commands.append(RemoveCmd())
489
commands.append(command.Remove())
491
491
if options.dump_json:
492
commands.append(DumpJSONCmd())
492
commands.append(command.DumpJSON())
494
494
if options.enable:
495
commands.append(EnableCmd())
495
commands.append(command.Enable())
497
497
if options.disable:
498
commands.append(DisableCmd())
498
commands.append(command.Disable())
500
500
if options.bump_timeout:
501
commands.append(BumpTimeoutCmd())
501
commands.append(command.BumpTimeout())
503
503
if options.start_checker:
504
commands.append(StartCheckerCmd())
504
commands.append(command.StartChecker())
506
506
if options.stop_checker:
507
commands.append(StopCheckerCmd())
507
commands.append(command.StopChecker())
509
509
if options.approved_by_default is not None:
510
510
if options.approved_by_default:
511
commands.append(ApproveByDefaultCmd())
511
commands.append(command.ApproveByDefault())
513
commands.append(DenyByDefaultCmd())
513
commands.append(command.DenyByDefault())
515
515
if options.checker is not None:
516
commands.append(SetCheckerCmd(options.checker))
516
commands.append(command.SetChecker(options.checker))
518
518
if options.host is not None:
519
commands.append(SetHostCmd(options.host))
519
commands.append(command.SetHost(options.host))
521
521
if options.secret is not None:
522
commands.append(SetSecretCmd(options.secret))
522
commands.append(command.SetSecret(options.secret))
524
524
if options.timeout is not None:
525
commands.append(SetTimeoutCmd(options.timeout))
525
commands.append(command.SetTimeout(options.timeout))
527
527
if options.extended_timeout:
529
SetExtendedTimeoutCmd(options.extended_timeout))
529
command.SetExtendedTimeout(options.extended_timeout))
531
531
if options.interval is not None:
532
commands.append(SetIntervalCmd(options.interval))
532
commands.append(command.SetInterval(options.interval))
534
534
if options.approval_delay is not None:
535
commands.append(SetApprovalDelayCmd(options.approval_delay))
536
command.SetApprovalDelay(options.approval_delay))
537
538
if options.approval_duration is not None:
539
SetApprovalDurationCmd(options.approval_duration))
540
command.SetApprovalDuration(options.approval_duration))
541
542
# If no command option has been given, show table of clients,
542
543
# optionally verbosely
544
commands.append(PrintTableCmd(verbose=options.verbose))
545
commands.append(command.PrintTable(verbose=options.verbose))
549
class Command(object):
550
"""Abstract class for commands"""
551
def run(self, clients, bus=None, mandos=None):
552
"""Normal commands should implement run_on_one_client(), but
553
commands which want to operate on all clients at the same time
554
can override this run() method instead."""
556
for clientpath, properties in clients.items():
557
log.debug("D-Bus: Connect to: (busname=%r, path=%r)",
558
dbus_busname, str(clientpath))
559
client = bus.get_object(dbus_busname, clientpath)
560
self.run_on_one_client(client, properties)
563
class IsEnabledCmd(Command):
564
def run(self, clients, bus=None, mandos=None):
565
client, properties = next(iter(clients.items()))
566
if self.is_enabled(client, properties):
569
def is_enabled(self, client, properties):
570
return properties["Enabled"]
573
class ApproveCmd(Command):
574
def run_on_one_client(self, client, properties):
575
log.debug("D-Bus: %s:%s:%s.Approve(True)", dbus_busname,
576
client.__dbus_object_path__, client_dbus_interface)
577
client.Approve(dbus.Boolean(True),
578
dbus_interface=client_dbus_interface)
581
class DenyCmd(Command):
582
def run_on_one_client(self, client, properties):
583
log.debug("D-Bus: %s:%s:%s.Approve(False)", dbus_busname,
584
client.__dbus_object_path__, client_dbus_interface)
585
client.Approve(dbus.Boolean(False),
586
dbus_interface=client_dbus_interface)
589
class RemoveCmd(Command):
590
def run_on_one_client(self, client, properties):
591
log.debug("D-Bus: %s:%s:%s.RemoveClient(%r)", dbus_busname,
592
server_dbus_path, server_dbus_interface,
593
str(client.__dbus_object_path__))
594
self.mandos.RemoveClient(client.__dbus_object_path__)
597
class OutputCmd(Command):
598
"""Abstract class for commands outputting client details"""
599
all_keywords = ("Name", "Enabled", "Timeout", "LastCheckedOK",
600
"Created", "Interval", "Host", "KeyID",
601
"Fingerprint", "CheckerRunning", "LastEnabled",
602
"ApprovalPending", "ApprovedByDefault",
603
"LastApprovalRequest", "ApprovalDelay",
604
"ApprovalDuration", "Checker", "ExtendedTimeout",
605
"Expires", "LastCheckerStatus")
607
def run(self, clients, bus=None, mandos=None):
608
print(self.output(clients.values()))
610
def output(self, clients):
611
raise NotImplementedError()
614
class DumpJSONCmd(OutputCmd):
615
def output(self, clients):
616
data = {client["Name"]:
617
{key: self.dbus_boolean_to_bool(client[key])
618
for key in self.all_keywords}
619
for client in clients}
620
return json.dumps(data, indent=4, separators=(',', ': '))
623
def dbus_boolean_to_bool(value):
624
if isinstance(value, dbus.Boolean):
629
class PrintTableCmd(OutputCmd):
630
def __init__(self, verbose=False):
631
self.verbose = verbose
633
def output(self, clients):
634
default_keywords = ("Name", "Enabled", "Timeout",
636
keywords = default_keywords
638
keywords = self.all_keywords
639
return str(self.TableOfClients(clients, keywords))
641
class TableOfClients(object):
644
"Enabled": "Enabled",
645
"Timeout": "Timeout",
646
"LastCheckedOK": "Last Successful Check",
647
"LastApprovalRequest": "Last Approval Request",
648
"Created": "Created",
649
"Interval": "Interval",
651
"Fingerprint": "Fingerprint",
653
"CheckerRunning": "Check Is Running",
654
"LastEnabled": "Last Enabled",
655
"ApprovalPending": "Approval Is Pending",
656
"ApprovedByDefault": "Approved By Default",
657
"ApprovalDelay": "Approval Delay",
658
"ApprovalDuration": "Approval Duration",
659
"Checker": "Checker",
660
"ExtendedTimeout": "Extended Timeout",
661
"Expires": "Expires",
662
"LastCheckerStatus": "Last Checker Status",
665
def __init__(self, clients, keywords):
666
self.clients = clients
667
self.keywords = keywords
670
return "\n".join(self.rows())
672
if sys.version_info.major == 2:
673
__unicode__ = __str__
550
class command(object):
551
"""A namespace for command classes"""
554
"""Abstract base class for commands"""
555
def run(self, clients, bus=None, mandos=None):
556
"""Normal commands should implement run_on_one_client(),
557
but commands which want to operate on all clients at the same time can
558
override this run() method instead.
561
for clientpath, properties in clients.items():
562
log.debug("D-Bus: Connect to: (busname=%r, path=%r)",
563
dbus_busname, str(clientpath))
564
client = bus.get_object(dbus_busname, clientpath)
565
self.run_on_one_client(client, properties)
568
class IsEnabled(Base):
569
def run(self, clients, bus=None, mandos=None):
570
client, properties = next(iter(clients.items()))
571
if self.is_enabled(client, properties):
574
def is_enabled(self, client, properties):
575
return properties["Enabled"]
579
def run_on_one_client(self, client, properties):
580
log.debug("D-Bus: %s:%s:%s.Approve(True)", dbus_busname,
581
client.__dbus_object_path__,
582
client_dbus_interface)
583
client.Approve(dbus.Boolean(True),
584
dbus_interface=client_dbus_interface)
588
def run_on_one_client(self, client, properties):
589
log.debug("D-Bus: %s:%s:%s.Approve(False)", dbus_busname,
590
client.__dbus_object_path__,
591
client_dbus_interface)
592
client.Approve(dbus.Boolean(False),
593
dbus_interface=client_dbus_interface)
597
def run_on_one_client(self, client, properties):
598
log.debug("D-Bus: %s:%s:%s.RemoveClient(%r)",
599
dbus_busname, server_dbus_path,
600
server_dbus_interface,
601
str(client.__dbus_object_path__))
602
self.mandos.RemoveClient(client.__dbus_object_path__)
606
"""Abstract class for commands outputting client details"""
607
all_keywords = ("Name", "Enabled", "Timeout", "LastCheckedOK",
608
"Created", "Interval", "Host", "KeyID",
609
"Fingerprint", "CheckerRunning",
610
"LastEnabled", "ApprovalPending",
611
"ApprovedByDefault", "LastApprovalRequest",
612
"ApprovalDelay", "ApprovalDuration",
613
"Checker", "ExtendedTimeout", "Expires",
616
def run(self, clients, bus=None, mandos=None):
617
print(self.output(clients.values()))
619
def output(self, clients):
620
raise NotImplementedError()
623
class DumpJSON(Output):
624
def output(self, clients):
625
data = {client["Name"]:
626
{key: self.dbus_boolean_to_bool(client[key])
627
for key in self.all_keywords}
628
for client in clients}
629
return json.dumps(data, indent=4, separators=(',', ': '))
632
def dbus_boolean_to_bool(value):
633
if isinstance(value, dbus.Boolean):
638
class PrintTable(Output):
639
def __init__(self, verbose=False):
640
self.verbose = verbose
642
def output(self, clients):
643
default_keywords = ("Name", "Enabled", "Timeout",
645
keywords = default_keywords
647
keywords = self.all_keywords
648
return str(self.TableOfClients(clients, keywords))
650
class TableOfClients(object):
653
"Enabled": "Enabled",
654
"Timeout": "Timeout",
655
"LastCheckedOK": "Last Successful Check",
656
"LastApprovalRequest": "Last Approval Request",
657
"Created": "Created",
658
"Interval": "Interval",
660
"Fingerprint": "Fingerprint",
662
"CheckerRunning": "Check Is Running",
663
"LastEnabled": "Last Enabled",
664
"ApprovalPending": "Approval Is Pending",
665
"ApprovedByDefault": "Approved By Default",
666
"ApprovalDelay": "Approval Delay",
667
"ApprovalDuration": "Approval Duration",
668
"Checker": "Checker",
669
"ExtendedTimeout": "Extended Timeout",
670
"Expires": "Expires",
671
"LastCheckerStatus": "Last Checker Status",
674
def __init__(self, clients, keywords):
675
self.clients = clients
676
self.keywords = keywords
674
678
def __str__(self):
675
return str(self).encode(locale.getpreferredencoding())
678
format_string = self.row_formatting_string()
679
rows = [self.header_line(format_string)]
680
rows.extend(self.client_line(client, format_string)
681
for client in self.clients)
684
def row_formatting_string(self):
685
"Format string used to format table rows"
686
return " ".join("{{{key}:{width}}}".format(
687
width=max(len(self.tableheaders[key]),
688
*(len(self.string_from_client(client, key))
689
for client in self.clients)),
691
for key in self.keywords)
693
def string_from_client(self, client, key):
694
return self.valuetostring(client[key], key)
697
def valuetostring(cls, value, keyword):
698
if isinstance(value, dbus.Boolean):
699
return "Yes" if value else "No"
700
if keyword in ("Timeout", "Interval", "ApprovalDelay",
701
"ApprovalDuration", "ExtendedTimeout"):
702
return cls.milliseconds_to_string(value)
705
def header_line(self, format_string):
706
return format_string.format(**self.tableheaders)
708
def client_line(self, client, format_string):
709
return format_string.format(
710
**{key: self.string_from_client(client, key)
711
for key in self.keywords})
714
def milliseconds_to_string(ms):
715
td = datetime.timedelta(0, 0, 0, ms)
716
return ("{days}{hours:02}:{minutes:02}:{seconds:02}"
717
.format(days="{}T".format(td.days)
719
hours=td.seconds // 3600,
720
minutes=(td.seconds % 3600) // 60,
721
seconds=td.seconds % 60))
724
class PropertyCmd(Command):
725
"""Abstract class for Actions for setting one client property"""
727
def run_on_one_client(self, client, properties):
728
"""Set the Client's D-Bus property"""
729
log.debug("D-Bus: %s:%s:%s.Set(%r, %r, %r)", dbus_busname,
730
client.__dbus_object_path__,
731
dbus.PROPERTIES_IFACE, client_dbus_interface,
732
self.propname, self.value_to_set
733
if not isinstance(self.value_to_set, dbus.Boolean)
734
else bool(self.value_to_set))
735
client.Set(client_dbus_interface, self.propname,
737
dbus_interface=dbus.PROPERTIES_IFACE)
741
raise NotImplementedError()
744
class EnableCmd(PropertyCmd):
746
value_to_set = dbus.Boolean(True)
749
class DisableCmd(PropertyCmd):
751
value_to_set = dbus.Boolean(False)
754
class BumpTimeoutCmd(PropertyCmd):
755
propname = "LastCheckedOK"
759
class StartCheckerCmd(PropertyCmd):
760
propname = "CheckerRunning"
761
value_to_set = dbus.Boolean(True)
764
class StopCheckerCmd(PropertyCmd):
765
propname = "CheckerRunning"
766
value_to_set = dbus.Boolean(False)
769
class ApproveByDefaultCmd(PropertyCmd):
770
propname = "ApprovedByDefault"
771
value_to_set = dbus.Boolean(True)
774
class DenyByDefaultCmd(PropertyCmd):
775
propname = "ApprovedByDefault"
776
value_to_set = dbus.Boolean(False)
779
class PropertyValueCmd(PropertyCmd):
780
"""Abstract class for PropertyCmd recieving a value as argument"""
781
def __init__(self, value):
782
self.value_to_set = value
785
class SetCheckerCmd(PropertyValueCmd):
789
class SetHostCmd(PropertyValueCmd):
793
class SetSecretCmd(PropertyValueCmd):
797
def value_to_set(self):
801
def value_to_set(self, value):
802
"""When setting, read data from supplied file object"""
803
self._vts = value.read()
807
class MillisecondsPropertyValueArgumentCmd(PropertyValueCmd):
808
"""Abstract class for PropertyValueCmd taking a value argument as
679
return "\n".join(self.rows())
681
if sys.version_info.major == 2:
682
__unicode__ = __str__
684
return str(self).encode(
685
locale.getpreferredencoding())
688
format_string = self.row_formatting_string()
689
rows = [self.header_line(format_string)]
690
rows.extend(self.client_line(client, format_string)
691
for client in self.clients)
694
def row_formatting_string(self):
695
"Format string used to format table rows"
696
return " ".join("{{{key}:{width}}}".format(
697
width=max(len(self.tableheaders[key]),
698
*(len(self.string_from_client(client,
700
for client in self.clients)),
702
for key in self.keywords)
704
def string_from_client(self, client, key):
705
return self.valuetostring(client[key], key)
708
def valuetostring(cls, value, keyword):
709
if isinstance(value, dbus.Boolean):
710
return "Yes" if value else "No"
711
if keyword in ("Timeout", "Interval", "ApprovalDelay",
712
"ApprovalDuration", "ExtendedTimeout"):
713
return cls.milliseconds_to_string(value)
716
def header_line(self, format_string):
717
return format_string.format(**self.tableheaders)
719
def client_line(self, client, format_string):
720
return format_string.format(
721
**{key: self.string_from_client(client, key)
722
for key in self.keywords})
725
def milliseconds_to_string(ms):
726
td = datetime.timedelta(0, 0, 0, ms)
727
return ("{days}{hours:02}:{minutes:02}:{seconds:02}"
728
.format(days="{}T".format(td.days)
730
hours=td.seconds // 3600,
731
minutes=(td.seconds % 3600) // 60,
732
seconds=td.seconds % 60))
735
class Property(Base):
736
"Abstract class for Actions for setting one client property"
738
def run_on_one_client(self, client, properties):
739
"""Set the Client's D-Bus property"""
740
log.debug("D-Bus: %s:%s:%s.Set(%r, %r, %r)", dbus_busname,
741
client.__dbus_object_path__,
742
dbus.PROPERTIES_IFACE, client_dbus_interface,
743
self.propname, self.value_to_set
744
if not isinstance(self.value_to_set,
746
else bool(self.value_to_set))
747
client.Set(client_dbus_interface, self.propname,
749
dbus_interface=dbus.PROPERTIES_IFACE)
753
raise NotImplementedError()
756
class Enable(Property):
758
value_to_set = dbus.Boolean(True)
761
class Disable(Property):
763
value_to_set = dbus.Boolean(False)
766
class BumpTimeout(Property):
767
propname = "LastCheckedOK"
771
class StartChecker(Property):
772
propname = "CheckerRunning"
773
value_to_set = dbus.Boolean(True)
776
class StopChecker(Property):
777
propname = "CheckerRunning"
778
value_to_set = dbus.Boolean(False)
781
class ApproveByDefault(Property):
782
propname = "ApprovedByDefault"
783
value_to_set = dbus.Boolean(True)
786
class DenyByDefault(Property):
787
propname = "ApprovedByDefault"
788
value_to_set = dbus.Boolean(False)
791
class PropertyValue(Property):
792
"Abstract class for Property recieving a value as argument"
793
def __init__(self, value):
794
self.value_to_set = value
797
class SetChecker(PropertyValue):
801
class SetHost(PropertyValue):
805
class SetSecret(PropertyValue):
809
def value_to_set(self):
813
def value_to_set(self, value):
814
"""When setting, read data from supplied file object"""
815
self._vts = value.read()
819
class MillisecondsPropertyValueArgument(PropertyValue):
820
"""Abstract class for PropertyValue taking a value argument as
809
821
a datetime.timedelta() but should store it as milliseconds."""
812
def value_to_set(self):
816
def value_to_set(self, value):
817
"""When setting, convert value from a datetime.timedelta"""
818
self._vts = int(round(value.total_seconds() * 1000))
821
class SetTimeoutCmd(MillisecondsPropertyValueArgumentCmd):
825
class SetExtendedTimeoutCmd(MillisecondsPropertyValueArgumentCmd):
826
propname = "ExtendedTimeout"
829
class SetIntervalCmd(MillisecondsPropertyValueArgumentCmd):
830
propname = "Interval"
833
class SetApprovalDelayCmd(MillisecondsPropertyValueArgumentCmd):
834
propname = "ApprovalDelay"
837
class SetApprovalDurationCmd(MillisecondsPropertyValueArgumentCmd):
838
propname = "ApprovalDuration"
824
def value_to_set(self):
828
def value_to_set(self, value):
829
"When setting, convert value from a datetime.timedelta"
830
self._vts = int(round(value.total_seconds() * 1000))
833
class SetTimeout(MillisecondsPropertyValueArgument):
837
class SetExtendedTimeout(MillisecondsPropertyValueArgument):
838
propname = "ExtendedTimeout"
841
class SetInterval(MillisecondsPropertyValueArgument):
842
propname = "Interval"
845
class SetApprovalDelay(MillisecondsPropertyValueArgument):
846
propname = "ApprovalDelay"
849
class SetApprovalDuration(MillisecondsPropertyValueArgument):
850
propname = "ApprovalDuration"
1484
1502
def RemoveClient(self, dbus_path):
1485
1503
self.calls.append(("RemoveClient", (dbus_path,)))
1486
1504
mandos = MockMandos()
1487
super(TestRemoveCmd, self).setUp()
1488
RemoveCmd().run(self.clients, self.bus, mandos)
1505
super(TestBaseCommands, self).setUp()
1506
command.Remove().run(self.clients, self.bus, mandos)
1489
1507
self.assertEqual(len(mandos.calls), 2)
1490
1508
for clientpath in self.clients:
1491
1509
self.assertIn(("RemoveClient", (clientpath,)),
1495
class TestDumpJSONCmd(TestCmd):
1497
self.expected_json = {
1500
"KeyID": ("92ed150794387c03ce684574b1139a65"
1501
"94a34f895daaaf09fd8ea90a27cddb12"),
1502
"Host": "foo.example.org",
1505
"LastCheckedOK": "2019-02-03T00:00:00",
1506
"Created": "2019-01-02T00:00:00",
1508
"Fingerprint": ("778827225BA7DE539C5A"
1509
"7CFA59CFF7CDBD9A5920"),
1510
"CheckerRunning": False,
1511
"LastEnabled": "2019-01-03T00:00:00",
1512
"ApprovalPending": False,
1513
"ApprovedByDefault": True,
1514
"LastApprovalRequest": "",
1516
"ApprovalDuration": 1000,
1517
"Checker": "fping -q -- %(host)s",
1518
"ExtendedTimeout": 900000,
1519
"Expires": "2019-02-04T00:00:00",
1520
"LastCheckerStatus": 0,
1524
"KeyID": ("0558568eedd67d622f5c83b35a115f79"
1525
"6ab612cff5ad227247e46c2b020f441c"),
1526
"Host": "192.0.2.3",
1529
"LastCheckedOK": "2019-02-04T00:00:00",
1530
"Created": "2019-01-03T00:00:00",
1532
"Fingerprint": ("3E393AEAEFB84C7E89E2"
1533
"F547B3A107558FCA3A27"),
1534
"CheckerRunning": True,
1535
"LastEnabled": "2019-01-04T00:00:00",
1536
"ApprovalPending": False,
1537
"ApprovedByDefault": False,
1538
"LastApprovalRequest": "2019-01-03T00:00:00",
1539
"ApprovalDelay": 30000,
1540
"ApprovalDuration": 93785000,
1542
"ExtendedTimeout": 900000,
1543
"Expires": "2019-02-05T00:00:00",
1544
"LastCheckerStatus": -2,
1547
return super(TestDumpJSONCmd, self).setUp()
1549
def test_normal(self):
1550
output = DumpJSONCmd().output(self.clients.values())
1515
"KeyID": ("92ed150794387c03ce684574b1139a65"
1516
"94a34f895daaaf09fd8ea90a27cddb12"),
1517
"Host": "foo.example.org",
1520
"LastCheckedOK": "2019-02-03T00:00:00",
1521
"Created": "2019-01-02T00:00:00",
1523
"Fingerprint": ("778827225BA7DE539C5A"
1524
"7CFA59CFF7CDBD9A5920"),
1525
"CheckerRunning": False,
1526
"LastEnabled": "2019-01-03T00:00:00",
1527
"ApprovalPending": False,
1528
"ApprovedByDefault": True,
1529
"LastApprovalRequest": "",
1531
"ApprovalDuration": 1000,
1532
"Checker": "fping -q -- %(host)s",
1533
"ExtendedTimeout": 900000,
1534
"Expires": "2019-02-04T00:00:00",
1535
"LastCheckerStatus": 0,
1539
"KeyID": ("0558568eedd67d622f5c83b35a115f79"
1540
"6ab612cff5ad227247e46c2b020f441c"),
1541
"Host": "192.0.2.3",
1544
"LastCheckedOK": "2019-02-04T00:00:00",
1545
"Created": "2019-01-03T00:00:00",
1547
"Fingerprint": ("3E393AEAEFB84C7E89E2"
1548
"F547B3A107558FCA3A27"),
1549
"CheckerRunning": True,
1550
"LastEnabled": "2019-01-04T00:00:00",
1551
"ApprovalPending": False,
1552
"ApprovedByDefault": False,
1553
"LastApprovalRequest": "2019-01-03T00:00:00",
1554
"ApprovalDelay": 30000,
1555
"ApprovalDuration": 93785000,
1557
"ExtendedTimeout": 900000,
1558
"Expires": "2019-02-05T00:00:00",
1559
"LastCheckerStatus": -2,
1563
def test_DumpJSON_normal(self):
1564
output = command.DumpJSON().output(self.clients.values())
1551
1565
json_data = json.loads(output)
1552
1566
self.assertDictEqual(json_data, self.expected_json)
1554
def test_one_client(self):
1555
output = DumpJSONCmd().output(self.one_client.values())
1568
def test_DumpJSON_one_client(self):
1569
output = command.DumpJSON().output(self.one_client.values())
1556
1570
json_data = json.loads(output)
1557
1571
expected_json = {"foo": self.expected_json["foo"]}
1558
1572
self.assertDictEqual(json_data, expected_json)
1561
class TestPrintTableCmd(TestCmd):
1562
def test_normal(self):
1563
output = PrintTableCmd().output(self.clients.values())
1574
def test_PrintTable_normal(self):
1575
output = command.PrintTable().output(self.clients.values())
1564
1576
expected_output = "\n".join((
1565
1577
"Name Enabled Timeout Last Successful Check",
1566
1578
"foo Yes 00:05:00 2019-02-03T00:00:00 ",