274
## Classes for commands.
276
# Abstract classes first
277
class Command(object):
278
"""Abstract class for commands"""
279
def run(self, mandos, clients):
280
"""Normal commands should implement run_on_one_client(), but
281
commands which want to operate on all clients at the same time
282
can override this run() method instead."""
284
for client, properties in clients.items():
285
self.run_on_one_client(client, properties)
287
class PrintCmd(Command):
288
"""Abstract class for commands printing client details"""
289
all_keywords = ("Name", "Enabled", "Timeout", "LastCheckedOK",
290
"Created", "Interval", "Host", "KeyID",
291
"Fingerprint", "CheckerRunning", "LastEnabled",
292
"ApprovalPending", "ApprovedByDefault",
293
"LastApprovalRequest", "ApprovalDelay",
294
"ApprovalDuration", "Checker", "ExtendedTimeout",
295
"Expires", "LastCheckerStatus")
296
def run(self, mandos, clients):
297
print(self.output(clients))
299
class PropertyCmd(Command):
300
"""Abstract class for Actions for setting one client property"""
301
def run_on_one_client(self, client, properties):
302
"""Set the Client's D-Bus property"""
303
client.Set(client_interface, self.property, self.value_to_set,
304
dbus_interface=dbus.PROPERTIES_IFACE)
306
class ValueArgumentMixIn(object):
307
"""Mixin class for commands taking a value as argument"""
308
def __init__(self, value):
309
self.value_to_set = value
311
class MillisecondsValueArgumentMixIn(ValueArgumentMixIn):
312
"""Mixin class for commands taking a value argument as
315
def value_to_set(self):
318
def value_to_set(self, value):
319
"""When setting, convert value to a datetime.timedelta"""
320
self._vts = int(round(value.total_seconds() * 1000))
322
# Actual (non-abstract) command classes
324
class PrintTableCmd(PrintCmd):
325
def __init__(self, verbose=False):
326
self.verbose = verbose
328
def output(self, clients):
329
default_keywords = ("Name", "Enabled", "Timeout", "LastCheckedOK")
330
keywords = default_keywords
332
keywords = self.all_keywords
333
return str(self.TableOfClients(clients.values(), keywords))
335
class TableOfClients(object):
338
"Enabled": "Enabled",
339
"Timeout": "Timeout",
340
"LastCheckedOK": "Last Successful Check",
341
"LastApprovalRequest": "Last Approval Request",
342
"Created": "Created",
343
"Interval": "Interval",
345
"Fingerprint": "Fingerprint",
347
"CheckerRunning": "Check Is Running",
348
"LastEnabled": "Last Enabled",
349
"ApprovalPending": "Approval Is Pending",
350
"ApprovedByDefault": "Approved By Default",
351
"ApprovalDelay": "Approval Delay",
352
"ApprovalDuration": "Approval Duration",
353
"Checker": "Checker",
354
"ExtendedTimeout": "Extended Timeout",
355
"Expires": "Expires",
356
"LastCheckerStatus": "Last Checker Status",
359
def __init__(self, clients, keywords, tableheaders=None):
360
self.clients = clients
361
self.keywords = keywords
362
if tableheaders is not None:
363
self.tableheaders = tableheaders
366
return "\n".join(self.rows())
368
if sys.version_info.major == 2:
369
__unicode__ = __str__
371
return str(self).encode(locale.getpreferredencoding())
374
format_string = self.row_formatting_string()
375
rows = [self.header_line(format_string)]
376
rows.extend(self.client_line(client, format_string)
377
for client in self.clients)
380
def row_formatting_string(self):
381
"Format string used to format table rows"
382
return " ".join("{{{key}:{width}}}".format(
383
width=max(len(self.tableheaders[key]),
384
*(len(self.string_from_client(client, key))
385
for client in self.clients)),
387
for key in self.keywords)
389
def string_from_client(self, client, key):
390
return self.valuetostring(client[key], key)
393
def valuetostring(value, keyword):
394
if isinstance(value, dbus.Boolean):
395
return "Yes" if value else "No"
396
if keyword in ("Timeout", "Interval", "ApprovalDelay",
397
"ApprovalDuration", "ExtendedTimeout"):
398
return milliseconds_to_string(value)
401
def header_line(self, format_string):
402
return format_string.format(**self.tableheaders)
404
def client_line(self, client, format_string):
405
return format_string.format(
406
**{key: self.string_from_client(client, key)
407
for key in self.keywords})
411
class DumpJSONCmd(PrintCmd):
412
def output(self, clients):
413
data = {client["Name"]:
414
{key: self.dbus_boolean_to_bool(client[key])
415
for key in self.all_keywords}
416
for client in clients.values()}
417
return json.dumps(data, indent=4, separators=(',', ': '))
419
def dbus_boolean_to_bool(value):
420
if isinstance(value, dbus.Boolean):
424
class IsEnabledCmd(Command):
425
def run_on_one_client(self, client, properties):
426
if self.is_enabled(client, properties):
429
def is_enabled(self, client, properties):
430
return bool(properties["Enabled"])
432
class RemoveCmd(Command):
433
def run_on_one_client(self, client, properties):
434
self.mandos.RemoveClient(client.__dbus_object_path__)
436
class ApproveCmd(Command):
437
def run_on_one_client(self, client, properties):
438
client.Approve(dbus.Boolean(True),
439
dbus_interface=client_interface)
441
class DenyCmd(Command):
442
def run_on_one_client(self, client, properties):
443
client.Approve(dbus.Boolean(False),
444
dbus_interface=client_interface)
446
class EnableCmd(PropertyCmd):
448
value_to_set = dbus.Boolean(True)
450
class DisableCmd(PropertyCmd):
452
value_to_set = dbus.Boolean(False)
454
class BumpTimeoutCmd(PropertyCmd):
455
property = "LastCheckedOK"
458
class StartCheckerCmd(PropertyCmd):
459
property = "CheckerRunning"
460
value_to_set = dbus.Boolean(True)
462
class StopCheckerCmd(PropertyCmd):
463
property = "CheckerRunning"
464
value_to_set = dbus.Boolean(False)
466
class ApproveByDefaultCmd(PropertyCmd):
467
property = "ApprovedByDefault"
468
value_to_set = dbus.Boolean(True)
470
class DenyByDefaultCmd(PropertyCmd):
471
property = "ApprovedByDefault"
472
value_to_set = dbus.Boolean(False)
474
class SetCheckerCmd(PropertyCmd, ValueArgumentMixIn):
477
class SetHostCmd(PropertyCmd, ValueArgumentMixIn):
480
class SetSecretCmd(PropertyCmd, ValueArgumentMixIn):
482
def value_to_set(self):
485
def value_to_set(self, value):
486
"""When setting, read data from supplied file object"""
487
self._vts = value.read()
491
class SetTimeoutCmd(PropertyCmd, MillisecondsValueArgumentMixIn):
494
class SetExtendedTimeoutCmd(PropertyCmd,
495
MillisecondsValueArgumentMixIn):
496
property = "ExtendedTimeout"
498
class SetIntervalCmd(PropertyCmd, MillisecondsValueArgumentMixIn):
499
property = "Interval"
501
class SetApprovalDelayCmd(PropertyCmd,
502
MillisecondsValueArgumentMixIn):
503
property = "ApprovalDelay"
505
class SetApprovalDurationCmd(PropertyCmd,
506
MillisecondsValueArgumentMixIn):
507
property = "ApprovalDuration"
509
def add_command_line_options(parser):
235
def print_clients(clients, keywords):
236
def valuetostring(value, keyword):
237
if type(value) is dbus.Boolean:
238
return "Yes" if value else "No"
239
if keyword in ("Timeout", "Interval", "ApprovalDelay",
240
"ApprovalDuration", "ExtendedTimeout"):
241
return milliseconds_to_string(value)
244
# Create format string to print table rows
245
format_string = " ".join("{{{key}:{width}}}".format(
246
width=max(len(tablewords[key]),
247
max(len(valuetostring(client[key], key))
248
for client in clients)),
252
print(format_string.format(**tablewords))
253
for client in clients:
255
.format(**{key: valuetostring(client[key], key)
256
for key in keywords}))
259
def has_actions(options):
260
return any((options.enable,
262
options.bump_timeout,
263
options.start_checker,
264
options.stop_checker,
267
options.checker is not None,
268
options.timeout is not None,
269
options.extended_timeout is not None,
270
options.interval is not None,
271
options.approved_by_default is not None,
272
options.approval_delay is not None,
273
options.approval_duration is not None,
274
options.host is not None,
275
options.secret is not None,
281
parser = argparse.ArgumentParser()
510
282
parser.add_argument("--version", action="version",
511
283
version="%(prog)s {}".format(version),
512
284
help="show version number and exit")
516
288
help="Print all fields")
517
289
parser.add_argument("-j", "--dump-json", action="store_true",
518
290
help="Dump client data in JSON format")
519
enable_disable = parser.add_mutually_exclusive_group()
520
enable_disable.add_argument("-e", "--enable", action="store_true",
521
help="Enable client")
522
enable_disable.add_argument("-d", "--disable",
524
help="disable client")
291
parser.add_argument("-e", "--enable", action="store_true",
292
help="Enable client")
293
parser.add_argument("-d", "--disable", action="store_true",
294
help="disable client")
525
295
parser.add_argument("-b", "--bump-timeout", action="store_true",
526
296
help="Bump timeout for client")
527
start_stop_checker = parser.add_mutually_exclusive_group()
528
start_stop_checker.add_argument("--start-checker",
530
help="Start checker for client")
531
start_stop_checker.add_argument("--stop-checker",
533
help="Stop checker for client")
297
parser.add_argument("--start-checker", action="store_true",
298
help="Start checker for client")
299
parser.add_argument("--stop-checker", action="store_true",
300
help="Stop checker for client")
534
301
parser.add_argument("-V", "--is-enabled", action="store_true",
535
302
help="Check if client is enabled")
536
303
parser.add_argument("-r", "--remove", action="store_true",
537
304
help="Remove client")
538
305
parser.add_argument("-c", "--checker",
539
306
help="Set checker command for client")
540
parser.add_argument("-t", "--timeout", type=string_to_delta,
307
parser.add_argument("-t", "--timeout",
541
308
help="Set timeout for client")
542
parser.add_argument("--extended-timeout", type=string_to_delta,
309
parser.add_argument("--extended-timeout",
543
310
help="Set extended timeout for client")
544
parser.add_argument("-i", "--interval", type=string_to_delta,
311
parser.add_argument("-i", "--interval",
545
312
help="Set checker interval for client")
546
approve_deny_default = parser.add_mutually_exclusive_group()
547
approve_deny_default.add_argument(
548
"--approve-by-default", action="store_true",
549
default=None, dest="approved_by_default",
550
help="Set client to be approved by default")
551
approve_deny_default.add_argument(
552
"--deny-by-default", action="store_false",
553
dest="approved_by_default",
554
help="Set client to be denied by default")
555
parser.add_argument("--approval-delay", type=string_to_delta,
313
parser.add_argument("--approve-by-default", action="store_true",
314
default=None, dest="approved_by_default",
315
help="Set client to be approved by default")
316
parser.add_argument("--deny-by-default", action="store_false",
317
dest="approved_by_default",
318
help="Set client to be denied by default")
319
parser.add_argument("--approval-delay",
556
320
help="Set delay before client approve/deny")
557
parser.add_argument("--approval-duration", type=string_to_delta,
321
parser.add_argument("--approval-duration",
558
322
help="Set duration of one client approval")
559
323
parser.add_argument("-H", "--host", help="Set host for client")
560
324
parser.add_argument("-s", "--secret",
561
325
type=argparse.FileType(mode="rb"),
562
326
help="Set password blob (file) for client")
563
approve_deny = parser.add_mutually_exclusive_group()
564
approve_deny.add_argument(
565
"-A", "--approve", action="store_true",
566
help="Approve any current client request")
567
approve_deny.add_argument("-D", "--deny", action="store_true",
568
help="Deny any current client request")
327
parser.add_argument("-A", "--approve", action="store_true",
328
help="Approve any current client request")
329
parser.add_argument("-D", "--deny", action="store_true",
330
help="Deny any current client request")
569
331
parser.add_argument("--check", action="store_true",
570
332
help="Run self-test")
571
333
parser.add_argument("client", nargs="*", help="Client name")
574
def commands_from_options(options):
578
if options.dump_json:
579
commands.append(DumpJSONCmd())
582
commands.append(EnableCmd())
585
commands.append(DisableCmd())
587
if options.bump_timeout:
588
commands.append(BumpTimeoutCmd())
590
if options.start_checker:
591
commands.append(StartCheckerCmd())
593
if options.stop_checker:
594
commands.append(StopCheckerCmd())
596
if options.is_enabled:
597
commands.append(IsEnabledCmd())
600
commands.append(RemoveCmd())
602
if options.checker is not None:
603
commands.append(SetCheckerCmd(options.checker))
605
if options.timeout is not None:
606
commands.append(SetTimeoutCmd(options.timeout))
608
if options.extended_timeout:
610
SetExtendedTimeoutCmd(options.extended_timeout))
612
if options.interval is not None:
613
commands.append(SetIntervalCmd(options.interval))
615
if options.approved_by_default is not None:
616
if options.approved_by_default:
617
commands.append(ApproveByDefaultCmd())
619
commands.append(DenyByDefaultCmd())
621
if options.approval_delay is not None:
622
commands.append(SetApprovalDelayCmd(options.approval_delay))
624
if options.approval_duration is not None:
626
SetApprovalDurationCmd(options.approval_duration))
628
if options.host is not None:
629
commands.append(SetHostCmd(options.host))
631
if options.secret is not None:
632
commands.append(SetSecretCmd(options.secret))
635
commands.append(ApproveCmd())
638
commands.append(DenyCmd())
640
# If no command option has been given, show table of clients,
641
# optionally verbosely
643
commands.append(PrintTableCmd(verbose=options.verbose))
648
def check_option_syntax(parser, options):
649
"""Apply additional restrictions on options, not expressible in
652
def has_actions(options):
653
return any((options.enable,
655
options.bump_timeout,
656
options.start_checker,
657
options.stop_checker,
660
options.checker is not None,
661
options.timeout is not None,
662
options.extended_timeout is not None,
663
options.interval is not None,
664
options.approved_by_default is not None,
665
options.approval_delay is not None,
666
options.approval_duration is not None,
667
options.host is not None,
668
options.secret is not None,
334
options = parser.parse_args()
672
336
if has_actions(options) and not (options.client or options.all):
673
337
parser.error("Options require clients names or --all.")
705
360
mandos_serv_object_manager = dbus.Interface(
706
361
mandos_dbus_objc, dbus_interface=dbus.OBJECT_MANAGER_IFACE)
708
# Filter out log message from dbus module
709
dbus_logger = logging.getLogger("dbus.proxies")
710
class NullFilter(logging.Filter):
711
def filter(self, record):
713
dbus_filter = NullFilter()
363
# block stderr since dbus library prints to stderr
364
null = os.open(os.path.devnull, os.O_RDWR)
365
stderrcopy = os.dup(sys.stderr.fileno())
366
os.dup2(null, sys.stderr.fileno())
715
dbus_logger.addFilter(dbus_filter)
716
mandos_clients = {path: ifs_and_props[client_interface]
717
for path, ifs_and_props in
718
mandos_serv_object_manager
719
.GetManagedObjects().items()
720
if client_interface in ifs_and_props}
370
mandos_clients = {path: ifs_and_props[client_interface]
371
for path, ifs_and_props in
372
mandos_serv_object_manager
373
.GetManagedObjects().items()
374
if client_interface in ifs_and_props}
377
os.dup2(stderrcopy, sys.stderr.fileno())
721
379
except dbus.exceptions.DBusException as e:
722
log.critical("Failed to access Mandos server through D-Bus:"
380
print("Access denied: "
381
"Accessing mandos server through D-Bus: {}".format(e),
726
# restore dbus logger
727
dbus_logger.removeFilter(dbus_filter)
729
385
# Compile dict of (clients: properties) to process
388
if options.all or not options.client:
733
389
clients = {bus.get_object(busname, path): properties
734
390
for path, properties in mandos_clients.items()}
736
for name in clientnames:
392
for name in options.client:
737
393
for path, client in mandos_clients.items():
738
394
if client["Name"] == name:
739
395
client_objc = bus.get_object(busname, path)
740
396
clients[client_objc] = client
743
log.critical("Client not found on server: %r", name)
399
print("Client not found on server: {!r}"
400
.format(name), file=sys.stderr)
746
# Run all commands on clients
747
commands = commands_from_options(options)
748
for command in commands:
749
command.run(mandos_serv, clients)
752
class Test_milliseconds_to_string(unittest.TestCase):
754
self.assertEqual(milliseconds_to_string(93785000),
756
def test_no_days(self):
757
self.assertEqual(milliseconds_to_string(7385000), "02:03:05")
758
def test_all_zero(self):
759
self.assertEqual(milliseconds_to_string(0), "00:00:00")
760
def test_no_fractional_seconds(self):
761
self.assertEqual(milliseconds_to_string(400), "00:00:00")
762
self.assertEqual(milliseconds_to_string(900), "00:00:00")
763
self.assertEqual(milliseconds_to_string(1900), "00:00:01")
765
class Test_string_to_delta(unittest.TestCase):
766
def test_handles_basic_rfc3339(self):
767
self.assertEqual(string_to_delta("PT0S"),
768
datetime.timedelta())
769
self.assertEqual(string_to_delta("P0D"),
770
datetime.timedelta())
771
self.assertEqual(string_to_delta("PT1S"),
772
datetime.timedelta(0, 1))
773
self.assertEqual(string_to_delta("PT2H"),
774
datetime.timedelta(0, 7200))
775
def test_falls_back_to_pre_1_6_1_with_warning(self):
776
# assertLogs only exists in Python 3.4
777
if hasattr(self, "assertLogs"):
778
with self.assertLogs(log, logging.WARNING):
779
value = string_to_delta("2h")
781
class WarningFilter(logging.Filter):
782
"""Don't show, but record the presence of, warnings"""
783
def filter(self, record):
784
is_warning = record.levelno >= logging.WARNING
785
self.found = is_warning or getattr(self, "found",
787
return not is_warning
788
warning_filter = WarningFilter()
789
log.addFilter(warning_filter)
791
value = string_to_delta("2h")
793
log.removeFilter(warning_filter)
794
self.assertTrue(getattr(warning_filter, "found", False))
795
self.assertEqual(value, datetime.timedelta(0, 7200))
798
class TestCmd(unittest.TestCase):
799
"""Abstract class for tests of command classes"""
802
class MockClient(object):
803
def __init__(self, name, **attributes):
804
self.__dbus_object_path__ = "objpath_{}".format(name)
805
self.attributes = attributes
806
self.attributes["Name"] = name
808
def Set(self, interface, property, value, dbus_interface):
809
testcase.assertEqual(interface, client_interface)
810
testcase.assertEqual(dbus_interface,
811
dbus.PROPERTIES_IFACE)
812
self.attributes[property] = value
813
def Get(self, interface, property, dbus_interface):
814
testcase.assertEqual(interface, client_interface)
815
testcase.assertEqual(dbus_interface,
816
dbus.PROPERTIES_IFACE)
817
return self.attributes[property]
818
def Approve(self, approve, dbus_interface):
819
testcase.assertEqual(dbus_interface, client_interface)
820
self.calls.append(("Approve", (approve,
822
self.client = MockClient(
824
KeyID=("92ed150794387c03ce684574b1139a65"
825
"94a34f895daaaf09fd8ea90a27cddb12"),
827
Host="foo.example.org",
828
Enabled=dbus.Boolean(True),
830
LastCheckedOK="2019-02-03T00:00:00",
831
Created="2019-01-02T00:00:00",
833
Fingerprint=("778827225BA7DE539C5A"
834
"7CFA59CFF7CDBD9A5920"),
835
CheckerRunning=dbus.Boolean(False),
836
LastEnabled="2019-01-03T00:00:00",
837
ApprovalPending=dbus.Boolean(False),
838
ApprovedByDefault=dbus.Boolean(True),
839
LastApprovalRequest="",
841
ApprovalDuration=1000,
842
Checker="fping -q -- %(host)s",
843
ExtendedTimeout=900000,
844
Expires="2019-02-04T00:00:00",
846
self.other_client = MockClient(
848
KeyID=("0558568eedd67d622f5c83b35a115f79"
849
"6ab612cff5ad227247e46c2b020f441c"),
852
Enabled=dbus.Boolean(True),
854
LastCheckedOK="2019-02-04T00:00:00",
855
Created="2019-01-03T00:00:00",
857
Fingerprint=("3E393AEAEFB84C7E89E2"
858
"F547B3A107558FCA3A27"),
859
CheckerRunning=dbus.Boolean(True),
860
LastEnabled="2019-01-04T00:00:00",
861
ApprovalPending=dbus.Boolean(False),
862
ApprovedByDefault=dbus.Boolean(False),
863
LastApprovalRequest="2019-01-03T00:00:00",
865
ApprovalDuration=1000,
867
ExtendedTimeout=900000,
868
Expires="2019-02-05T00:00:00",
869
LastCheckerStatus=-2)
870
self.clients = collections.OrderedDict(
872
(self.client, self.client.attributes),
873
(self.other_client, self.other_client.attributes),
875
self.one_client = {self.client: self.client.attributes}
877
class TestPrintTableCmd(TestCmd):
878
def test_normal(self):
879
output = PrintTableCmd().output(self.clients)
880
expected_output = """
881
Name Enabled Timeout Last Successful Check
882
foo Yes 00:05:00 2019-02-03T00:00:00
883
barbar Yes 00:05:00 2019-02-04T00:00:00
885
self.assertEqual(output, expected_output)
886
def test_verbose(self):
887
output = PrintTableCmd(verbose=True).output(self.clients)
888
expected_output = """
889
Name Enabled Timeout Last Successful Check Created Interval Host Key ID Fingerprint Check Is Running Last Enabled Approval Is Pending Approved By Default Last Approval Request Approval Delay Approval Duration Checker Extended Timeout Expires Last Checker Status
890
foo Yes 00:05:00 2019-02-03T00:00:00 2019-01-02T00:00:00 00:02:00 foo.example.org 92ed150794387c03ce684574b1139a6594a34f895daaaf09fd8ea90a27cddb12 778827225BA7DE539C5A7CFA59CFF7CDBD9A5920 No 2019-01-03T00:00:00 No Yes 00:00:00 00:00:01 fping -q -- %(host)s 00:15:00 2019-02-04T00:00:00 0
891
barbar Yes 00:05:00 2019-02-04T00:00:00 2019-01-03T00:00:00 00:02:00 192.0.2.3 0558568eedd67d622f5c83b35a115f796ab612cff5ad227247e46c2b020f441c 3E393AEAEFB84C7E89E2F547B3A107558FCA3A27 Yes 2019-01-04T00:00:00 No No 2019-01-03T00:00:00 00:00:30 00:00:01 : 00:15:00 2019-02-05T00:00:00 -2
893
self.assertEqual(output, expected_output)
894
def test_one_client(self):
895
output = PrintTableCmd().output(self.one_client)
896
expected_output = """
897
Name Enabled Timeout Last Successful Check
898
foo Yes 00:05:00 2019-02-03T00:00:00
900
self.assertEqual(output, expected_output)
902
class TestDumpJSONCmd(TestCmd):
904
self.expected_json = {
907
"KeyID": ("92ed150794387c03ce684574b1139a65"
908
"94a34f895daaaf09fd8ea90a27cddb12"),
909
"Host": "foo.example.org",
912
"LastCheckedOK": "2019-02-03T00:00:00",
913
"Created": "2019-01-02T00:00:00",
915
"Fingerprint": ("778827225BA7DE539C5A"
916
"7CFA59CFF7CDBD9A5920"),
917
"CheckerRunning": False,
918
"LastEnabled": "2019-01-03T00:00:00",
919
"ApprovalPending": False,
920
"ApprovedByDefault": True,
921
"LastApprovalRequest": "",
923
"ApprovalDuration": 1000,
924
"Checker": "fping -q -- %(host)s",
925
"ExtendedTimeout": 900000,
926
"Expires": "2019-02-04T00:00:00",
927
"LastCheckerStatus": 0,
931
"KeyID": ("0558568eedd67d622f5c83b35a115f79"
932
"6ab612cff5ad227247e46c2b020f441c"),
936
"LastCheckedOK": "2019-02-04T00:00:00",
937
"Created": "2019-01-03T00:00:00",
939
"Fingerprint": ("3E393AEAEFB84C7E89E2"
940
"F547B3A107558FCA3A27"),
941
"CheckerRunning": True,
942
"LastEnabled": "2019-01-04T00:00:00",
943
"ApprovalPending": False,
944
"ApprovedByDefault": False,
945
"LastApprovalRequest": "2019-01-03T00:00:00",
946
"ApprovalDelay": 30000,
947
"ApprovalDuration": 1000,
949
"ExtendedTimeout": 900000,
950
"Expires": "2019-02-05T00:00:00",
951
"LastCheckerStatus": -2,
954
return super(TestDumpJSONCmd, self).setUp()
955
def test_normal(self):
956
json_data = json.loads(DumpJSONCmd().output(self.clients))
957
self.assertDictEqual(json_data, self.expected_json)
958
def test_one_client(self):
959
clients = self.one_client
960
json_data = json.loads(DumpJSONCmd().output(clients))
961
expected_json = {"foo": self.expected_json["foo"]}
962
self.assertDictEqual(json_data, expected_json)
964
class TestIsEnabledCmd(TestCmd):
965
def test_is_enabled(self):
966
self.assertTrue(all(IsEnabledCmd().is_enabled(client, properties)
967
for client, properties in self.clients.items()))
968
def test_is_enabled_run_exits_successfully(self):
969
with self.assertRaises(SystemExit) as e:
970
IsEnabledCmd().run(None, self.one_client)
971
if e.exception.code is not None:
972
self.assertEqual(e.exception.code, 0)
974
self.assertIsNone(e.exception.code)
975
def test_is_enabled_run_exits_with_failure(self):
976
self.client.attributes["Enabled"] = dbus.Boolean(False)
977
with self.assertRaises(SystemExit) as e:
978
IsEnabledCmd().run(None, self.one_client)
979
if isinstance(e.exception.code, int):
980
self.assertNotEqual(e.exception.code, 0)
982
self.assertIsNotNone(e.exception.code)
984
class TestRemoveCmd(TestCmd):
985
def test_remove(self):
986
class MockMandos(object):
989
def RemoveClient(self, dbus_path):
990
self.calls.append(("RemoveClient", (dbus_path,)))
991
mandos = MockMandos()
992
super(TestRemoveCmd, self).setUp()
993
RemoveCmd().run(mandos, self.clients)
994
self.assertEqual(len(mandos.calls), 2)
995
for client in self.clients:
996
self.assertIn(("RemoveClient",
997
(client.__dbus_object_path__,)),
1000
class TestApproveCmd(TestCmd):
1001
def test_approve(self):
1002
ApproveCmd().run(None, self.clients)
1003
for client in self.clients:
1004
self.assertIn(("Approve", (True, client_interface)),
1007
class TestDenyCmd(TestCmd):
1008
def test_deny(self):
1009
DenyCmd().run(None, self.clients)
1010
for client in self.clients:
1011
self.assertIn(("Approve", (False, client_interface)),
1014
class TestEnableCmd(TestCmd):
1015
def test_enable(self):
1016
for client in self.clients:
1017
client.attributes["Enabled"] = False
1019
EnableCmd().run(None, self.clients)
1021
for client in self.clients:
1022
self.assertTrue(client.attributes["Enabled"])
1024
class TestDisableCmd(TestCmd):
1025
def test_disable(self):
1026
DisableCmd().run(None, self.clients)
1028
for client in self.clients:
1029
self.assertFalse(client.attributes["Enabled"])
1031
class Unique(object):
1032
"""Class for objects which exist only to be unique objects, since
1033
unittest.mock.sentinel only exists in Python 3.3"""
1035
class TestPropertyCmd(TestCmd):
1036
"""Abstract class for tests of PropertyCmd classes"""
1038
if not hasattr(self, "command"):
1040
values_to_get = getattr(self, "values_to_get",
1042
for value_to_set, value_to_get in zip(self.values_to_set,
1044
for client in self.clients:
1045
old_value = client.attributes[self.property]
1046
self.assertNotIsInstance(old_value, Unique)
1047
client.attributes[self.property] = Unique()
1048
self.run_command(value_to_set, self.clients)
1049
for client in self.clients:
1050
value = client.attributes[self.property]
1051
self.assertNotIsInstance(value, Unique)
1052
self.assertEqual(value, value_to_get)
1053
def run_command(self, value, clients):
1054
self.command().run(None, clients)
1056
class TestBumpTimeoutCmd(TestPropertyCmd):
1057
command = BumpTimeoutCmd
1058
property = "LastCheckedOK"
1059
values_to_set = [""]
1061
class TestStartCheckerCmd(TestPropertyCmd):
1062
command = StartCheckerCmd
1063
property = "CheckerRunning"
1064
values_to_set = [dbus.Boolean(True)]
1066
class TestStopCheckerCmd(TestPropertyCmd):
1067
command = StopCheckerCmd
1068
property = "CheckerRunning"
1069
values_to_set = [dbus.Boolean(False)]
1071
class TestApproveByDefaultCmd(TestPropertyCmd):
1072
command = ApproveByDefaultCmd
1073
property = "ApprovedByDefault"
1074
values_to_set = [dbus.Boolean(True)]
1076
class TestDenyByDefaultCmd(TestPropertyCmd):
1077
command = DenyByDefaultCmd
1078
property = "ApprovedByDefault"
1079
values_to_set = [dbus.Boolean(False)]
1081
class TestValueArgumentPropertyCmd(TestPropertyCmd):
1082
"""Abstract class for tests of PropertyCmd classes using the
1083
ValueArgumentMixIn"""
1085
if type(self) is TestValueArgumentPropertyCmd:
1087
return super(TestValueArgumentPropertyCmd, self).runTest()
1088
def run_command(self, value, clients):
1089
self.command(value).run(None, clients)
1091
class TestSetCheckerCmd(TestValueArgumentPropertyCmd):
1092
command = SetCheckerCmd
1093
property = "Checker"
1094
values_to_set = ["", ":", "fping -q -- %s"]
1096
class TestSetHostCmd(TestValueArgumentPropertyCmd):
1097
command = SetHostCmd
1099
values_to_set = ["192.0.2.3", "foo.example.org"]
1101
class TestSetSecretCmd(TestValueArgumentPropertyCmd):
1102
command = SetSecretCmd
1104
values_to_set = [open("/dev/null", "rb"),
1105
io.BytesIO(b"secret\0xyzzy\nbar")]
1106
values_to_get = [b"", b"secret\0xyzzy\nbar"]
1108
class TestSetTimeoutCmd(TestValueArgumentPropertyCmd):
1109
command = SetTimeoutCmd
1110
property = "Timeout"
1111
values_to_set = [datetime.timedelta(),
1112
datetime.timedelta(minutes=5),
1113
datetime.timedelta(seconds=1),
1114
datetime.timedelta(weeks=1),
1115
datetime.timedelta(weeks=52)]
1116
values_to_get = [0, 300000, 1000, 604800000, 31449600000]
1118
class TestSetExtendedTimeoutCmd(TestValueArgumentPropertyCmd):
1119
command = SetExtendedTimeoutCmd
1120
property = "ExtendedTimeout"
1121
values_to_set = [datetime.timedelta(),
1122
datetime.timedelta(minutes=5),
1123
datetime.timedelta(seconds=1),
1124
datetime.timedelta(weeks=1),
1125
datetime.timedelta(weeks=52)]
1126
values_to_get = [0, 300000, 1000, 604800000, 31449600000]
1128
class TestSetIntervalCmd(TestValueArgumentPropertyCmd):
1129
command = SetIntervalCmd
1130
property = "Interval"
1131
values_to_set = [datetime.timedelta(),
1132
datetime.timedelta(minutes=5),
1133
datetime.timedelta(seconds=1),
1134
datetime.timedelta(weeks=1),
1135
datetime.timedelta(weeks=52)]
1136
values_to_get = [0, 300000, 1000, 604800000, 31449600000]
1138
class TestSetApprovalDelayCmd(TestValueArgumentPropertyCmd):
1139
command = SetApprovalDelayCmd
1140
property = "ApprovalDelay"
1141
values_to_set = [datetime.timedelta(),
1142
datetime.timedelta(minutes=5),
1143
datetime.timedelta(seconds=1),
1144
datetime.timedelta(weeks=1),
1145
datetime.timedelta(weeks=52)]
1146
values_to_get = [0, 300000, 1000, 604800000, 31449600000]
1148
class TestSetApprovalDurationCmd(TestValueArgumentPropertyCmd):
1149
command = SetApprovalDurationCmd
1150
property = "ApprovalDuration"
1151
values_to_set = [datetime.timedelta(),
1152
datetime.timedelta(minutes=5),
1153
datetime.timedelta(seconds=1),
1154
datetime.timedelta(weeks=1),
1155
datetime.timedelta(weeks=52)]
1156
values_to_get = [0, 300000, 1000, 604800000, 31449600000]
1158
class Test_command_from_options(unittest.TestCase):
1160
self.parser = argparse.ArgumentParser()
1161
add_command_line_options(self.parser)
1162
def assert_command_from_args(self, args, command_cls, **cmd_attrs):
1163
"""Assert that parsing ARGS should result in an instance of
1164
COMMAND_CLS with (optionally) all supplied attributes (CMD_ATTRS)."""
1165
options = self.parser.parse_args(args)
1166
check_option_syntax(self.parser, options)
1167
commands = commands_from_options(options)
1168
self.assertEqual(len(commands), 1)
1169
command = commands[0]
1170
self.assertIsInstance(command, command_cls)
1171
for key, value in cmd_attrs.items():
1172
self.assertEqual(getattr(command, key), value)
1173
def test_print_table(self):
1174
self.assert_command_from_args([], PrintTableCmd,
1177
def test_print_table_verbose(self):
1178
self.assert_command_from_args(["--verbose"], PrintTableCmd,
1181
def test_print_table_verbose_short(self):
1182
self.assert_command_from_args(["-v"], PrintTableCmd,
1185
def test_enable(self):
1186
self.assert_command_from_args(["--enable", "foo"], EnableCmd)
1188
def test_enable_short(self):
1189
self.assert_command_from_args(["-e", "foo"], EnableCmd)
1191
def test_disable(self):
1192
self.assert_command_from_args(["--disable", "foo"],
1195
def test_disable_short(self):
1196
self.assert_command_from_args(["-d", "foo"], DisableCmd)
1198
def test_bump_timeout(self):
1199
self.assert_command_from_args(["--bump-timeout", "foo"],
1202
def test_bump_timeout_short(self):
1203
self.assert_command_from_args(["-b", "foo"], BumpTimeoutCmd)
1205
def test_start_checker(self):
1206
self.assert_command_from_args(["--start-checker", "foo"],
1209
def test_stop_checker(self):
1210
self.assert_command_from_args(["--stop-checker", "foo"],
1213
def test_remove(self):
1214
self.assert_command_from_args(["--remove", "foo"],
1217
def test_remove_short(self):
1218
self.assert_command_from_args(["-r", "foo"], RemoveCmd)
1220
def test_checker(self):
1221
self.assert_command_from_args(["--checker", ":", "foo"],
1222
SetCheckerCmd, value_to_set=":")
1224
def test_checker_empty(self):
1225
self.assert_command_from_args(["--checker", "", "foo"],
1226
SetCheckerCmd, value_to_set="")
1228
def test_checker_short(self):
1229
self.assert_command_from_args(["-c", ":", "foo"],
1230
SetCheckerCmd, value_to_set=":")
1232
def test_timeout(self):
1233
self.assert_command_from_args(["--timeout", "PT5M", "foo"],
1235
value_to_set=300000)
1237
def test_timeout_short(self):
1238
self.assert_command_from_args(["-t", "PT5M", "foo"],
1240
value_to_set=300000)
1242
def test_extended_timeout(self):
1243
self.assert_command_from_args(["--extended-timeout", "PT15M",
1245
SetExtendedTimeoutCmd,
1246
value_to_set=900000)
1248
def test_interval(self):
1249
self.assert_command_from_args(["--interval", "PT2M", "foo"],
1251
value_to_set=120000)
1253
def test_interval_short(self):
1254
self.assert_command_from_args(["-i", "PT2M", "foo"],
1256
value_to_set=120000)
1258
def test_approve_by_default(self):
1259
self.assert_command_from_args(["--approve-by-default", "foo"],
1260
ApproveByDefaultCmd)
1262
def test_deny_by_default(self):
1263
self.assert_command_from_args(["--deny-by-default", "foo"],
1266
def test_approval_delay(self):
1267
self.assert_command_from_args(["--approval-delay", "PT30S",
1268
"foo"], SetApprovalDelayCmd,
1271
def test_approval_duration(self):
1272
self.assert_command_from_args(["--approval-duration", "PT1S",
1273
"foo"], SetApprovalDurationCmd,
1276
def test_host(self):
1277
self.assert_command_from_args(["--host", "foo.example.org",
1279
value_to_set="foo.example.org")
1281
def test_host_short(self):
1282
self.assert_command_from_args(["-H", "foo.example.org",
1284
value_to_set="foo.example.org")
1286
def test_secret_devnull(self):
1287
self.assert_command_from_args(["--secret", os.path.devnull,
1288
"foo"], SetSecretCmd,
1291
def test_secret_tempfile(self):
1292
with tempfile.NamedTemporaryFile(mode="r+b") as f:
1293
value = b"secret\0xyzzy\nbar"
1296
self.assert_command_from_args(["--secret", f.name,
1297
"foo"], SetSecretCmd,
1300
def test_secret_devnull_short(self):
1301
self.assert_command_from_args(["-s", os.path.devnull, "foo"],
1302
SetSecretCmd, value_to_set=b"")
1304
def test_secret_tempfile_short(self):
1305
with tempfile.NamedTemporaryFile(mode="r+b") as f:
1306
value = b"secret\0xyzzy\nbar"
1309
self.assert_command_from_args(["-s", f.name, "foo"],
1313
def test_approve(self):
1314
self.assert_command_from_args(["--approve", "foo"],
1317
def test_approve_short(self):
1318
self.assert_command_from_args(["-A", "foo"], ApproveCmd)
1320
def test_deny(self):
1321
self.assert_command_from_args(["--deny", "foo"], DenyCmd)
1323
def test_deny_short(self):
1324
self.assert_command_from_args(["-D", "foo"], DenyCmd)
1326
def test_dump_json(self):
1327
self.assert_command_from_args(["--dump-json"], DumpJSONCmd)
1329
def test_is_enabled(self):
1330
self.assert_command_from_args(["--is-enabled", "foo"],
1333
def test_is_enabled_short(self):
1334
self.assert_command_from_args(["-V", "foo"], IsEnabledCmd)
1337
class Test_check_option_syntax(unittest.TestCase):
1338
# This mostly corresponds to the definition from has_actions() in
1339
# check_option_syntax()
1341
# The actual values set here are not that important, but we do
1342
# at least stick to the correct types, even though they are
1346
"bump_timeout": True,
1347
"start_checker": True,
1348
"stop_checker": True,
1352
"timeout": datetime.timedelta(),
1353
"extended_timeout": datetime.timedelta(),
1354
"interval": datetime.timedelta(),
1355
"approved_by_default": True,
1356
"approval_delay": datetime.timedelta(),
1357
"approval_duration": datetime.timedelta(),
1359
"secret": io.BytesIO(b"x"),
1365
self.parser = argparse.ArgumentParser()
1366
add_command_line_options(self.parser)
1368
@contextlib.contextmanager
1369
def assertParseError(self):
1370
with self.assertRaises(SystemExit) as e:
1371
with self.temporarily_suppress_stderr():
1373
# Exit code from argparse is guaranteed to be "2". Reference:
1374
# https://docs.python.org/3/library/argparse.html#exiting-methods
1375
self.assertEqual(e.exception.code, 2)
1378
@contextlib.contextmanager
1379
def temporarily_suppress_stderr():
1380
null = os.open(os.path.devnull, os.O_RDWR)
1381
stderrcopy = os.dup(sys.stderr.fileno())
1382
os.dup2(null, sys.stderr.fileno())
1388
os.dup2(stderrcopy, sys.stderr.fileno())
1389
os.close(stderrcopy)
1391
def check_option_syntax(self, options):
1392
check_option_syntax(self.parser, options)
1394
def test_actions_requires_client_or_all(self):
1395
for action, value in self.actions.items():
1396
options = self.parser.parse_args()
1397
setattr(options, action, value)
1398
with self.assertParseError():
1399
self.check_option_syntax(options)
1401
def test_actions_conflicts_with_verbose(self):
1402
for action, value in self.actions.items():
1403
options = self.parser.parse_args()
1404
setattr(options, action, value)
1405
options.verbose = True
1406
with self.assertParseError():
1407
self.check_option_syntax(options)
1409
def test_dump_json_conflicts_with_verbose(self):
1410
options = self.parser.parse_args()
1411
options.dump_json = True
1412
options.verbose = True
1413
with self.assertParseError():
1414
self.check_option_syntax(options)
1416
def test_dump_json_conflicts_with_action(self):
1417
for action, value in self.actions.items():
1418
options = self.parser.parse_args()
1419
setattr(options, action, value)
1420
options.dump_json = True
1421
with self.assertParseError():
1422
self.check_option_syntax(options)
1424
def test_all_can_not_be_alone(self):
1425
options = self.parser.parse_args()
1427
with self.assertParseError():
1428
self.check_option_syntax(options)
1430
def test_all_is_ok_with_any_action(self):
1431
for action, value in self.actions.items():
1432
options = self.parser.parse_args()
1433
setattr(options, action, value)
1435
self.check_option_syntax(options)
1437
def test_is_enabled_fails_without_client(self):
1438
options = self.parser.parse_args()
1439
options.is_enabled = True
1440
with self.assertParseError():
1441
self.check_option_syntax(options)
1443
def test_is_enabled_works_with_one_client(self):
1444
options = self.parser.parse_args()
1445
options.is_enabled = True
1446
options.client = ["foo"]
1447
self.check_option_syntax(options)
1449
def test_is_enabled_fails_with_two_clients(self):
1450
options = self.parser.parse_args()
1451
options.is_enabled = True
1452
options.client = ["foo", "barbar"]
1453
with self.assertParseError():
1454
self.check_option_syntax(options)
1458
def should_only_run_tests():
1459
parser = argparse.ArgumentParser(add_help=False)
1460
parser.add_argument("--check", action='store_true')
1461
args, unknown_args = parser.parse_known_args()
1462
run_tests = args.check
1464
# Remove --check argument from sys.argv
1465
sys.argv[1:] = unknown_args
1468
# Add all tests from doctest strings
1469
def load_tests(loader, tests, none):
1471
tests.addTests(doctest.DocTestSuite())
403
if not has_actions(options) and clients:
404
if options.verbose or options.dump_json:
405
keywords = ("Name", "Enabled", "Timeout", "LastCheckedOK",
406
"Created", "Interval", "Host", "Fingerprint",
407
"CheckerRunning", "LastEnabled",
408
"ApprovalPending", "ApprovedByDefault",
409
"LastApprovalRequest", "ApprovalDelay",
410
"ApprovalDuration", "Checker",
411
"ExtendedTimeout", "Expires",
414
keywords = defaultkeywords
416
if options.dump_json:
417
json.dump({client["Name"]: {key:
419
if isinstance(client[key],
423
for client in clients.values()},
424
fp=sys.stdout, indent=4,
425
separators=(',', ': '))
428
print_clients(clients.values(), keywords)
430
# Process each client in the list by all selected options
431
for client in clients:
433
def set_client_prop(prop, value):
434
"""Set a Client D-Bus property"""
435
client.Set(client_interface, prop, value,
436
dbus_interface=dbus.PROPERTIES_IFACE)
438
def set_client_prop_ms(prop, value):
439
"""Set a Client D-Bus property, converted
440
from a string to milliseconds."""
441
set_client_prop(prop,
442
string_to_delta(value).total_seconds()
446
mandos_serv.RemoveClient(client.__dbus_object_path__)
448
set_client_prop("Enabled", dbus.Boolean(True))
450
set_client_prop("Enabled", dbus.Boolean(False))
451
if options.bump_timeout:
452
set_client_prop("LastCheckedOK", "")
453
if options.start_checker:
454
set_client_prop("CheckerRunning", dbus.Boolean(True))
455
if options.stop_checker:
456
set_client_prop("CheckerRunning", dbus.Boolean(False))
457
if options.is_enabled:
458
if client.Get(client_interface, "Enabled",
459
dbus_interface=dbus.PROPERTIES_IFACE):
463
if options.checker is not None:
464
set_client_prop("Checker", options.checker)
465
if options.host is not None:
466
set_client_prop("Host", options.host)
467
if options.interval is not None:
468
set_client_prop_ms("Interval", options.interval)
469
if options.approval_delay is not None:
470
set_client_prop_ms("ApprovalDelay",
471
options.approval_delay)
472
if options.approval_duration is not None:
473
set_client_prop_ms("ApprovalDuration",
474
options.approval_duration)
475
if options.timeout is not None:
476
set_client_prop_ms("Timeout", options.timeout)
477
if options.extended_timeout is not None:
478
set_client_prop_ms("ExtendedTimeout",
479
options.extended_timeout)
480
if options.secret is not None:
481
set_client_prop("Secret",
482
dbus.ByteArray(options.secret.read()))
483
if options.approved_by_default is not None:
484
set_client_prop("ApprovedByDefault",
486
.approved_by_default))
488
client.Approve(dbus.Boolean(True),
489
dbus_interface=client_interface)
491
client.Approve(dbus.Boolean(False),
492
dbus_interface=client_interface)
1474
495
if __name__ == "__main__":
1475
if should_only_run_tests():
1476
# Call using ./tdd-python-script --check [--verbose]