/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-02 02:17:17 UTC
  • Revision ID: teddy@recompile.se-20190302021717-kzk7xwjtef3syau6
mandos-ctl: Refactor

* mandos-ctl (TableOfClients.rows): Extract methods.
  (TableOfClients.row_formatting_string): New.
  (TableOfClients.string_from_client): New.
  (TableOfClients.header_line): New.
  (TableOfClients.client_line): New.

Show diffs side-by-side

added added

removed removed

Lines of Context:
61
61
 
62
62
locale.setlocale(locale.LC_ALL, "")
63
63
 
 
64
defaultkeywords = ("Name", "Enabled", "Timeout", "LastCheckedOK")
64
65
domain = "se.recompile"
65
66
busname = domain + ".Mandos"
66
67
server_path = "/"
215
216
 
216
217
 
217
218
def string_to_delta(interval):
218
 
    """Parse a string and return a datetime.timedelta"""
 
219
    """Parse a string and return a datetime.timedelta
 
220
    """
219
221
 
220
222
    try:
221
223
        return rfc3339_duration_to_delta(interval)
226
228
 
227
229
 
228
230
def parse_pre_1_6_1_interval(interval):
229
 
    """Parse an interval string as documented by Mandos before 1.6.1,
230
 
    and return a datetime.timedelta
231
 
 
 
231
    """Parse an interval string as documented by Mandos before 1.6.1, and
 
232
    return a datetime.timedelta
232
233
    >>> parse_pre_1_6_1_interval('7d')
233
234
    datetime.timedelta(7)
234
235
    >>> parse_pre_1_6_1_interval('60s')
268
269
    return value
269
270
 
270
271
 
271
 
## Classes for commands.
272
 
 
273
 
# Abstract classes first
274
 
class Command(object):
275
 
    """Abstract class for commands"""
276
 
    def run(self, mandos, clients):
277
 
        """Normal commands should implement run_on_one_client(), but
278
 
        commands which want to operate on all clients at the same time
279
 
        can override this run() method instead."""
280
 
        self.mandos = mandos
281
 
        for client in clients:
282
 
            self.run_on_one_client(client)
283
 
 
284
 
class PrintCmd(Command):
285
 
    """Abstract class for commands printing client details"""
286
 
    all_keywords = ("Name", "Enabled", "Timeout", "LastCheckedOK",
287
 
                    "Created", "Interval", "Host", "KeyID",
288
 
                    "Fingerprint", "CheckerRunning", "LastEnabled",
289
 
                    "ApprovalPending", "ApprovedByDefault",
290
 
                    "LastApprovalRequest", "ApprovalDelay",
291
 
                    "ApprovalDuration", "Checker", "ExtendedTimeout",
292
 
                    "Expires", "LastCheckerStatus")
293
 
    def run(self, mandos, clients):
294
 
        print(self.output(clients))
295
 
 
296
 
class PropertyCmd(Command):
297
 
    """Abstract class for Actions for setting one client property"""
298
 
    def run_on_one_client(self, client):
299
 
        """Set the Client's D-Bus property"""
300
 
        client.Set(client_interface, self.property, self.value_to_set,
301
 
                   dbus_interface=dbus.PROPERTIES_IFACE)
302
 
 
303
 
class ValueArgumentMixIn(object):
304
 
    """Mixin class for commands taking a value as argument"""
305
 
    def __init__(self, value):
306
 
        self.value_to_set = value
307
 
 
308
 
class MillisecondsValueArgumentMixIn(ValueArgumentMixIn):
309
 
    """Mixin class for commands taking a value argument as
310
 
    milliseconds."""
311
 
    @property
312
 
    def value_to_set(self):
313
 
        return self._vts
314
 
    @value_to_set.setter
315
 
    def value_to_set(self, value):
316
 
        """When setting, convert value to a datetime.timedelta"""
317
 
        self._vts = string_to_delta(value).total_seconds() * 1000
318
 
 
319
 
# Actual (non-abstract) command classes
320
 
 
321
 
class PrintTableCmd(PrintCmd):
322
 
    def __init__(self, verbose=False):
323
 
        self.verbose = verbose
324
 
 
325
 
    def output(self, clients):
326
 
        if self.verbose:
327
 
            keywords = self.all_keywords
328
 
        else:
329
 
            keywords = ("Name", "Enabled", "Timeout", "LastCheckedOK")
330
 
        return str(self.TableOfClients(clients.values(), keywords))
331
 
 
332
 
    class TableOfClients(object):
333
 
        tableheaders = {
334
 
            "Name": "Name",
335
 
            "Enabled": "Enabled",
336
 
            "Timeout": "Timeout",
337
 
            "LastCheckedOK": "Last Successful Check",
338
 
            "LastApprovalRequest": "Last Approval Request",
339
 
            "Created": "Created",
340
 
            "Interval": "Interval",
341
 
            "Host": "Host",
342
 
            "Fingerprint": "Fingerprint",
343
 
            "KeyID": "Key ID",
344
 
            "CheckerRunning": "Check Is Running",
345
 
            "LastEnabled": "Last Enabled",
346
 
            "ApprovalPending": "Approval Is Pending",
347
 
            "ApprovedByDefault": "Approved By Default",
348
 
            "ApprovalDelay": "Approval Delay",
349
 
            "ApprovalDuration": "Approval Duration",
350
 
            "Checker": "Checker",
351
 
            "ExtendedTimeout": "Extended Timeout",
352
 
            "Expires": "Expires",
353
 
            "LastCheckerStatus": "Last Checker Status",
354
 
        }
355
 
 
356
 
        def __init__(self, clients, keywords, tableheaders=None):
357
 
            self.clients = clients
358
 
            self.keywords = keywords
359
 
            if tableheaders is not None:
360
 
                self.tableheaders = tableheaders
361
 
 
362
 
        def __str__(self):
363
 
            return "\n".join(self.rows())
364
 
 
365
 
        if sys.version_info.major == 2:
366
 
            __unicode__ = __str__
367
 
            def __str__(self):
368
 
                return str(self).encode(locale.getpreferredencoding())
369
 
 
370
 
        def rows(self):
371
 
            format_string = self.row_formatting_string()
372
 
            rows = [self.header_line(format_string)]
373
 
            rows.extend(self.client_line(client, format_string)
374
 
                        for client in self.clients)
375
 
            return rows
376
 
 
377
 
        def row_formatting_string(self):
378
 
            "Format string used to format table rows"
379
 
            return " ".join("{{{key}:{width}}}".format(
380
 
                width=max(len(self.tableheaders[key]),
381
 
                          *(len(self.string_from_client(client, key))
382
 
                            for client in self.clients)),
383
 
                key=key)
384
 
                            for key in self.keywords)
385
 
 
386
 
        def string_from_client(self, client, key):
387
 
            return self.valuetostring(client[key], key)
388
 
 
389
 
        @staticmethod
390
 
        def valuetostring(value, keyword):
391
 
            if isinstance(value, dbus.Boolean):
392
 
                return "Yes" if value else "No"
393
 
            if keyword in ("Timeout", "Interval", "ApprovalDelay",
394
 
                           "ApprovalDuration", "ExtendedTimeout"):
395
 
                return milliseconds_to_string(value)
396
 
            return str(value)
397
 
 
398
 
        def header_line(self, format_string):
399
 
            return format_string.format(**self.tableheaders)
400
 
 
401
 
        def client_line(self, client, format_string):
402
 
            return format_string.format(
403
 
                **{key: self.string_from_client(client, key)
404
 
                   for key in self.keywords})
405
 
 
406
 
 
407
 
 
408
 
class DumpJSONCmd(PrintCmd):
409
 
    def output(self, clients):
410
 
        data = {client["Name"]:
411
 
                {key: self.dbus_boolean_to_bool(client[key])
412
 
                 for key in self.all_keywords}
413
 
                for client in clients.values()}
414
 
        return json.dumps(data, indent=4, separators=(',', ': '))
 
272
def print_clients(clients, keywords):
 
273
    print('\n'.join(TableOfClients(clients, keywords).rows()))
 
274
 
 
275
class TableOfClients(object):
 
276
    tablewords = {
 
277
        "Name": "Name",
 
278
        "Enabled": "Enabled",
 
279
        "Timeout": "Timeout",
 
280
        "LastCheckedOK": "Last Successful Check",
 
281
        "LastApprovalRequest": "Last Approval Request",
 
282
        "Created": "Created",
 
283
        "Interval": "Interval",
 
284
        "Host": "Host",
 
285
        "Fingerprint": "Fingerprint",
 
286
        "KeyID": "Key ID",
 
287
        "CheckerRunning": "Check Is Running",
 
288
        "LastEnabled": "Last Enabled",
 
289
        "ApprovalPending": "Approval Is Pending",
 
290
        "ApprovedByDefault": "Approved By Default",
 
291
        "ApprovalDelay": "Approval Delay",
 
292
        "ApprovalDuration": "Approval Duration",
 
293
        "Checker": "Checker",
 
294
        "ExtendedTimeout": "Extended Timeout",
 
295
        "Expires": "Expires",
 
296
        "LastCheckerStatus": "Last Checker Status",
 
297
    }
 
298
 
 
299
    def __init__(self, clients, keywords, tablewords=None):
 
300
        self.clients = clients
 
301
        self.keywords = keywords
 
302
        if tablewords is not None:
 
303
            self.tablewords = tablewords
 
304
 
 
305
    def rows(self):
 
306
        format_string = self.row_formatting_string()
 
307
        rows = [self.header_line(format_string)]
 
308
        rows.extend(self.client_line(client, format_string)
 
309
                    for client in self.clients)
 
310
        return rows
 
311
 
 
312
    def row_formatting_string(self):
 
313
        "Format string used to format table rows"
 
314
        return " ".join("{{{key}:{width}}}".format(
 
315
            width=max(len(self.tablewords[key]),
 
316
                      max(len(self.string_from_client(client, key))
 
317
                          for client in self.clients)),
 
318
            key=key)
 
319
                                 for key in self.keywords)
 
320
 
 
321
    def string_from_client(self, client, key):
 
322
        return self.valuetostring(client[key], key)
 
323
 
415
324
    @staticmethod
416
 
    def dbus_boolean_to_bool(value):
 
325
    def valuetostring(value, keyword):
417
326
        if isinstance(value, dbus.Boolean):
418
 
            value = bool(value)
419
 
        return value
420
 
 
421
 
class IsEnabledCmd(Command):
422
 
    def run_on_one_client(self, client):
423
 
        if self.is_enabled(client):
424
 
            sys.exit(0)
425
 
        sys.exit(1)
426
 
    def is_enabled(self, client):
427
 
        return client.Get(client_interface, "Enabled",
428
 
                          dbus_interface=dbus.PROPERTIES_IFACE)
429
 
 
430
 
class RemoveCmd(Command):
431
 
    def run_on_one_client(self, client):
432
 
        self.mandos.RemoveClient(client.__dbus_object_path__)
433
 
 
434
 
class ApproveCmd(Command):
435
 
    def run_on_one_client(self, client):
436
 
        client.Approve(dbus.Boolean(True),
437
 
                       dbus_interface=client_interface)
438
 
 
439
 
class DenyCmd(Command):
440
 
    def run_on_one_client(self, client):
441
 
        client.Approve(dbus.Boolean(False),
442
 
                       dbus_interface=client_interface)
443
 
 
444
 
class EnableCmd(PropertyCmd):
445
 
    property = "Enabled"
446
 
    value_to_set = dbus.Boolean(True)
447
 
 
448
 
class DisableCmd(PropertyCmd):
449
 
    property = "Enabled"
450
 
    value_to_set = dbus.Boolean(False)
451
 
 
452
 
class BumpTimeoutCmd(PropertyCmd):
453
 
    property = "LastCheckedOK"
454
 
    value_to_set = ""
455
 
 
456
 
class StartCheckerCmd(PropertyCmd):
457
 
    property = "CheckerRunning"
458
 
    value_to_set = dbus.Boolean(True)
459
 
 
460
 
class StopCheckerCmd(PropertyCmd):
461
 
    property = "CheckerRunning"
462
 
    value_to_set = dbus.Boolean(False)
463
 
 
464
 
class ApproveByDefaultCmd(PropertyCmd):
465
 
    property = "ApprovedByDefault"
466
 
    value_to_set = dbus.Boolean(True)
467
 
 
468
 
class DenyByDefaultCmd(PropertyCmd):
469
 
    property = "ApprovedByDefault"
470
 
    value_to_set = dbus.Boolean(False)
471
 
 
472
 
class SetCheckerCmd(PropertyCmd, ValueArgumentMixIn):
473
 
    property = "Checker"
474
 
 
475
 
class SetHostCmd(PropertyCmd, ValueArgumentMixIn):
476
 
    property = "Host"
477
 
 
478
 
class SetSecretCmd(PropertyCmd, ValueArgumentMixIn):
479
 
    property = "Secret"
480
 
 
481
 
class SetTimeoutCmd(PropertyCmd, MillisecondsValueArgumentMixIn):
482
 
    property = "Timeout"
483
 
 
484
 
class SetExtendedTimeoutCmd(PropertyCmd,
485
 
                            MillisecondsValueArgumentMixIn):
486
 
    property = "ExtendedTimeout"
487
 
 
488
 
class SetIntervalCmd(PropertyCmd, MillisecondsValueArgumentMixIn):
489
 
    property = "Interval"
490
 
 
491
 
class SetApprovalDelayCmd(PropertyCmd,
492
 
                          MillisecondsValueArgumentMixIn):
493
 
    property = "ApprovalDelay"
494
 
 
495
 
class SetApprovalDurationCmd(PropertyCmd,
496
 
                             MillisecondsValueArgumentMixIn):
497
 
    property = "ApprovalDuration"
 
327
            return "Yes" if value else "No"
 
328
        if keyword in ("Timeout", "Interval", "ApprovalDelay",
 
329
                       "ApprovalDuration", "ExtendedTimeout"):
 
330
            return milliseconds_to_string(value)
 
331
        return str(value)
 
332
 
 
333
    def header_line(self, format_string):
 
334
        return format_string.format(**self.tablewords)
 
335
 
 
336
    def client_line(self, client, format_string):
 
337
        return format_string.format(
 
338
            **{key: self.string_from_client(client, key)
 
339
               for key in self.keywords})
 
340
 
498
341
 
499
342
def has_actions(options):
500
343
    return any((options.enable,
517
360
                options.deny))
518
361
 
519
362
 
520
 
def commands_and_clients_from_options(args=None):
521
 
    if args is None:
522
 
        args=sys.argv[1:]
 
363
def main():
523
364
    parser = argparse.ArgumentParser()
524
365
    parser.add_argument("--version", action="version",
525
366
                        version="%(prog)s {}".format(version),
530
371
                        help="Print all fields")
531
372
    parser.add_argument("-j", "--dump-json", action="store_true",
532
373
                        help="Dump client data in JSON format")
533
 
    enable_disable = parser.add_mutually_exclusive_group()
534
 
    enable_disable.add_argument("-e", "--enable", action="store_true",
535
 
                                help="Enable client")
536
 
    enable_disable.add_argument("-d", "--disable",
537
 
                                action="store_true",
538
 
                                help="disable client")
 
374
    parser.add_argument("-e", "--enable", action="store_true",
 
375
                        help="Enable client")
 
376
    parser.add_argument("-d", "--disable", action="store_true",
 
377
                        help="disable client")
539
378
    parser.add_argument("-b", "--bump-timeout", action="store_true",
540
379
                        help="Bump timeout for client")
541
 
    start_stop_checker = parser.add_mutually_exclusive_group()
542
 
    start_stop_checker.add_argument("--start-checker",
543
 
                                    action="store_true",
544
 
                                    help="Start checker for client")
545
 
    start_stop_checker.add_argument("--stop-checker",
546
 
                                    action="store_true",
547
 
                                    help="Stop checker for client")
 
380
    parser.add_argument("--start-checker", action="store_true",
 
381
                        help="Start checker for client")
 
382
    parser.add_argument("--stop-checker", action="store_true",
 
383
                        help="Stop checker for client")
548
384
    parser.add_argument("-V", "--is-enabled", action="store_true",
549
385
                        help="Check if client is enabled")
550
386
    parser.add_argument("-r", "--remove", action="store_true",
557
393
                        help="Set extended timeout for client")
558
394
    parser.add_argument("-i", "--interval",
559
395
                        help="Set checker interval for client")
560
 
    approve_deny_default = parser.add_mutually_exclusive_group()
561
 
    approve_deny_default.add_argument(
562
 
        "--approve-by-default", action="store_true",
563
 
        default=None, dest="approved_by_default",
564
 
        help="Set client to be approved by default")
565
 
    approve_deny_default.add_argument(
566
 
        "--deny-by-default", action="store_false",
567
 
        dest="approved_by_default",
568
 
        help="Set client to be denied by default")
 
396
    parser.add_argument("--approve-by-default", action="store_true",
 
397
                        default=None, dest="approved_by_default",
 
398
                        help="Set client to be approved by default")
 
399
    parser.add_argument("--deny-by-default", action="store_false",
 
400
                        dest="approved_by_default",
 
401
                        help="Set client to be denied by default")
569
402
    parser.add_argument("--approval-delay",
570
403
                        help="Set delay before client approve/deny")
571
404
    parser.add_argument("--approval-duration",
574
407
    parser.add_argument("-s", "--secret",
575
408
                        type=argparse.FileType(mode="rb"),
576
409
                        help="Set password blob (file) for client")
577
 
    approve_deny = parser.add_mutually_exclusive_group()
578
 
    approve_deny.add_argument(
579
 
        "-A", "--approve", action="store_true",
580
 
        help="Approve any current client request")
581
 
    approve_deny.add_argument("-D", "--deny", action="store_true",
582
 
                              help="Deny any current client request")
 
410
    parser.add_argument("-A", "--approve", action="store_true",
 
411
                        help="Approve any current client request")
 
412
    parser.add_argument("-D", "--deny", action="store_true",
 
413
                        help="Deny any current client request")
583
414
    parser.add_argument("--check", action="store_true",
584
415
                        help="Run self-test")
585
416
    parser.add_argument("client", nargs="*", help="Client name")
586
 
    options = parser.parse_args(args=args)
 
417
    options = parser.parse_args()
587
418
 
588
419
    if has_actions(options) and not (options.client or options.all):
589
420
        parser.error("Options require clients names or --all.")
594
425
        parser.error("--dump-json can only be used alone.")
595
426
    if options.all and not has_actions(options):
596
427
        parser.error("--all requires an action.")
597
 
    if options.is_enabled and len(options.client) > 1:
598
 
            parser.error("--is-enabled requires exactly one client")
599
 
 
600
 
    commands = []
601
 
 
602
 
    if options.dump_json:
603
 
        commands.append(DumpJSONCmd())
604
 
 
605
 
    if options.enable:
606
 
        commands.append(EnableCmd())
607
 
 
608
 
    if options.disable:
609
 
        commands.append(DisableCmd())
610
 
 
611
 
    if options.bump_timeout:
612
 
        commands.append(BumpTimeoutCmd(options.bump_timeout))
613
 
 
614
 
    if options.start_checker:
615
 
        commands.append(StartCheckerCmd())
616
 
 
617
 
    if options.stop_checker:
618
 
        commands.append(StopCheckerCmd())
619
 
 
620
 
    if options.is_enabled:
621
 
        commands.append(IsEnabledCmd())
622
 
 
623
 
    if options.remove:
624
 
        commands.append(RemoveCmd())
625
 
 
626
 
    if options.checker is not None:
627
 
        commands.append(SetCheckerCmd())
628
 
 
629
 
    if options.timeout is not None:
630
 
        commands.append(SetTimeoutCmd(options.timeout))
631
 
 
632
 
    if options.extended_timeout:
633
 
        commands.append(
634
 
            SetExtendedTimeoutCmd(options.extended_timeout))
635
 
 
636
 
    if options.interval is not None:
637
 
        command.append(SetIntervalCmd(options.interval))
638
 
 
639
 
    if options.approved_by_default is not None:
640
 
        if options.approved_by_default:
641
 
            command.append(ApproveByDefaultCmd())
642
 
        else:
643
 
            command.append(DenyByDefaultCmd())
644
 
 
645
 
    if options.approval_delay is not None:
646
 
        command.append(SetApprovalDelayCmd(options.approval_delay))
647
 
 
648
 
    if options.approval_duration is not None:
649
 
        command.append(
650
 
            SetApprovalDurationCmd(options.approval_duration))
651
 
 
652
 
    if options.host is not None:
653
 
        command.append(SetHostCmd(options.host))
654
 
 
655
 
    if options.secret is not None:
656
 
        command.append(SetSecretCmd(options.secret))
657
 
 
658
 
    if options.approve:
659
 
        commands.append(ApproveCmd())
660
 
 
661
 
    if options.deny:
662
 
        commands.append(DenyCmd())
663
 
 
664
 
    # If no command option has been given, show table of clients,
665
 
    # optionally verbosely
666
 
    if not commands:
667
 
        commands.append(PrintTableCmd(verbose=options.verbose))
668
 
 
669
 
    return commands, options.client
670
 
 
671
 
 
672
 
def main():
673
 
    commands, clientnames = commands_and_clients_from_options()
674
428
 
675
429
    try:
676
430
        bus = dbus.SystemBus()
684
438
    mandos_serv_object_manager = dbus.Interface(
685
439
        mandos_dbus_objc, dbus_interface=dbus.OBJECT_MANAGER_IFACE)
686
440
 
687
 
    # Filter out log message from dbus module
688
 
    dbus_logger = logging.getLogger("dbus.proxies")
689
 
    class NullFilter(logging.Filter):
690
 
        def filter(self, record):
691
 
            return False
692
 
    dbus_filter = NullFilter()
693
 
    dbus_logger.addFilter(dbus_filter)
 
441
    # block stderr since dbus library prints to stderr
 
442
    null = os.open(os.path.devnull, os.O_RDWR)
 
443
    stderrcopy = os.dup(sys.stderr.fileno())
 
444
    os.dup2(null, sys.stderr.fileno())
 
445
    os.close(null)
694
446
    try:
695
447
        try:
696
448
            mandos_clients = {path: ifs_and_props[client_interface]
699
451
                              .GetManagedObjects().items()
700
452
                              if client_interface in ifs_and_props}
701
453
        finally:
702
 
            # restore dbus logger
703
 
            dbus_logger.removeFilter(dbus_filter)
 
454
            # restore stderr
 
455
            os.dup2(stderrcopy, sys.stderr.fileno())
 
456
            os.close(stderrcopy)
704
457
    except dbus.exceptions.DBusException as e:
705
458
        log.critical("Failed to access Mandos server through D-Bus:"
706
459
                     "\n%s", e)
709
462
    # Compile dict of (clients: properties) to process
710
463
    clients = {}
711
464
 
712
 
    if not clientnames:
 
465
    if options.all or not options.client:
713
466
        clients = {bus.get_object(busname, path): properties
714
467
                   for path, properties in mandos_clients.items()}
715
468
    else:
716
 
        for name in clientnames:
 
469
        for name in options.client:
717
470
            for path, client in mandos_clients.items():
718
471
                if client["Name"] == name:
719
472
                    client_objc = bus.get_object(busname, path)
723
476
                log.critical("Client not found on server: %r", name)
724
477
                sys.exit(1)
725
478
 
726
 
    # Run all commands on clients
727
 
    for command in commands:
728
 
        command.run(mandos_serv, clients)
 
479
    if not has_actions(options) and clients:
 
480
        if options.verbose or options.dump_json:
 
481
            keywords = ("Name", "Enabled", "Timeout", "LastCheckedOK",
 
482
                        "Created", "Interval", "Host", "KeyID",
 
483
                        "Fingerprint", "CheckerRunning",
 
484
                        "LastEnabled", "ApprovalPending",
 
485
                        "ApprovedByDefault", "LastApprovalRequest",
 
486
                        "ApprovalDelay", "ApprovalDuration",
 
487
                        "Checker", "ExtendedTimeout", "Expires",
 
488
                        "LastCheckerStatus")
 
489
        else:
 
490
            keywords = defaultkeywords
 
491
 
 
492
        if options.dump_json:
 
493
            json.dump({client["Name"]: {key:
 
494
                                        bool(client[key])
 
495
                                        if isinstance(client[key],
 
496
                                                      dbus.Boolean)
 
497
                                        else client[key]
 
498
                                        for key in keywords}
 
499
                       for client in clients.values()},
 
500
                      fp=sys.stdout, indent=4,
 
501
                      separators=(',', ': '))
 
502
            print()
 
503
        else:
 
504
            print_clients(clients.values(), keywords)
 
505
    else:
 
506
        # Process each client in the list by all selected options
 
507
        for client in clients:
 
508
 
 
509
            def set_client_prop(prop, value):
 
510
                """Set a Client D-Bus property"""
 
511
                client.Set(client_interface, prop, value,
 
512
                           dbus_interface=dbus.PROPERTIES_IFACE)
 
513
 
 
514
            def set_client_prop_ms(prop, value):
 
515
                """Set a Client D-Bus property, converted
 
516
                from a string to milliseconds."""
 
517
                set_client_prop(prop,
 
518
                                string_to_delta(value).total_seconds()
 
519
                                * 1000)
 
520
 
 
521
            if options.remove:
 
522
                mandos_serv.RemoveClient(client.__dbus_object_path__)
 
523
            if options.enable:
 
524
                set_client_prop("Enabled", dbus.Boolean(True))
 
525
            if options.disable:
 
526
                set_client_prop("Enabled", dbus.Boolean(False))
 
527
            if options.bump_timeout:
 
528
                set_client_prop("LastCheckedOK", "")
 
529
            if options.start_checker:
 
530
                set_client_prop("CheckerRunning", dbus.Boolean(True))
 
531
            if options.stop_checker:
 
532
                set_client_prop("CheckerRunning", dbus.Boolean(False))
 
533
            if options.is_enabled:
 
534
                if client.Get(client_interface, "Enabled",
 
535
                              dbus_interface=dbus.PROPERTIES_IFACE):
 
536
                    sys.exit(0)
 
537
                else:
 
538
                    sys.exit(1)
 
539
            if options.checker is not None:
 
540
                set_client_prop("Checker", options.checker)
 
541
            if options.host is not None:
 
542
                set_client_prop("Host", options.host)
 
543
            if options.interval is not None:
 
544
                set_client_prop_ms("Interval", options.interval)
 
545
            if options.approval_delay is not None:
 
546
                set_client_prop_ms("ApprovalDelay",
 
547
                                   options.approval_delay)
 
548
            if options.approval_duration is not None:
 
549
                set_client_prop_ms("ApprovalDuration",
 
550
                                   options.approval_duration)
 
551
            if options.timeout is not None:
 
552
                set_client_prop_ms("Timeout", options.timeout)
 
553
            if options.extended_timeout is not None:
 
554
                set_client_prop_ms("ExtendedTimeout",
 
555
                                   options.extended_timeout)
 
556
            if options.secret is not None:
 
557
                set_client_prop("Secret",
 
558
                                dbus.ByteArray(options.secret.read()))
 
559
            if options.approved_by_default is not None:
 
560
                set_client_prop("ApprovedByDefault",
 
561
                                dbus.Boolean(options
 
562
                                             .approved_by_default))
 
563
            if options.approve:
 
564
                client.Approve(dbus.Boolean(True),
 
565
                               dbus_interface=client_interface)
 
566
            elif options.deny:
 
567
                client.Approve(dbus.Boolean(False),
 
568
                               dbus_interface=client_interface)
729
569
 
730
570
 
731
571
class Test_milliseconds_to_string(unittest.TestCase):
751
591
            with self.assertLogs(log, logging.WARNING):
752
592
                value = string_to_delta("2h")
753
593
        else:
754
 
            class WarningFilter(logging.Filter):
755
 
                """Don't show, but record the presence of, warnings"""
756
 
                def filter(self, record):
757
 
                    is_warning = record.levelno >= logging.WARNING
758
 
                    self.found = is_warning or getattr(self, "found",
759
 
                                                       False)
760
 
                    return not is_warning
761
 
            warning_filter = WarningFilter()
762
 
            log.addFilter(warning_filter)
763
 
            try:
764
 
                value = string_to_delta("2h")
765
 
            finally:
766
 
                log.removeFilter(warning_filter)
767
 
            self.assertTrue(getattr(warning_filter, "found", False))
 
594
            value = string_to_delta("2h")
768
595
        self.assertEqual(value, datetime.timedelta(0, 7200))
769
596
 
770
 
 
771
 
class TestCmd(unittest.TestCase):
772
 
    """Abstract class for tests of command classes"""
773
 
    def setUp(self):
774
 
        testcase = self
775
 
        class MockClient(object):
776
 
            def __init__(self, name, **attributes):
777
 
                self.__dbus_object_path__ = "objpath_{}".format(name)
778
 
                self.attributes = attributes
779
 
                self.attributes["Name"] = name
780
 
            def Set(interface, property, value,
781
 
                    properties_interface):
782
 
                testcase.assertEqual(interface, client_interface)
783
 
                testcase.assertEqual(properties_interface,
784
 
                                     dbus.PROPERTIES_IFACE)
785
 
                self.attributes[property] = value
786
 
            def Get(interface, property, properties_interface):
787
 
                testcase.assertEqual(interface, client_interface)
788
 
                testcase.assertEqual(properties_interface,
789
 
                                     dbus.PROPERTIES_IFACE)
790
 
                return self.attributes[property]
791
 
            def __getitem__(self, key):
792
 
                return self.attributes[key]
793
 
        self.clients = collections.OrderedDict([
794
 
            ("foo",
795
 
             MockClient(
796
 
                 "foo",
797
 
                 KeyID=("92ed150794387c03ce684574b1139a65"
798
 
                        "94a34f895daaaf09fd8ea90a27cddb12"),
799
 
                 Secret=b"secret",
800
 
                 Host="foo.example.org",
801
 
                 Enabled=dbus.Boolean(True),
802
 
                 Timeout=300000,
803
 
                 LastCheckedOK="2019-02-03T00:00:00",
804
 
                 Created="2019-01-02T00:00:00",
805
 
                 Interval=120000,
806
 
                 Fingerprint=("778827225BA7DE539C5A"
807
 
                              "7CFA59CFF7CDBD9A5920"),
808
 
                 CheckerRunning=dbus.Boolean(False),
809
 
                 LastEnabled="2019-01-03T00:00:00",
810
 
                 ApprovalPending=dbus.Boolean(False),
811
 
                 ApprovedByDefault=dbus.Boolean(True),
812
 
                 LastApprovalRequest="",
813
 
                 ApprovalDelay=0,
814
 
                 ApprovalDuration=1000,
815
 
                 Checker="fping -q -- %(host)s",
816
 
                 ExtendedTimeout=900000,
817
 
                 Expires="2019-02-04T00:00:00",
818
 
                 LastCheckerStatus=0)),
819
 
            ("barbar",
820
 
             MockClient(
821
 
                 "barbar",
822
 
                 KeyID=("0558568eedd67d622f5c83b35a115f79"
823
 
                        "6ab612cff5ad227247e46c2b020f441c"),
824
 
                 Secret=b"secretbar",
825
 
                 Host="192.0.2.3",
826
 
                 Enabled=dbus.Boolean(True),
827
 
                 Timeout=300000,
828
 
                 LastCheckedOK="2019-02-04T00:00:00",
829
 
                 Created="2019-01-03T00:00:00",
830
 
                 Interval=120000,
831
 
                 Fingerprint=("3E393AEAEFB84C7E89E2"
832
 
                              "F547B3A107558FCA3A27"),
833
 
                 CheckerRunning=dbus.Boolean(True),
834
 
                 LastEnabled="2019-01-04T00:00:00",
835
 
                 ApprovalPending=dbus.Boolean(False),
836
 
                 ApprovedByDefault=dbus.Boolean(False),
837
 
                 LastApprovalRequest="2019-01-03T00:00:00",
838
 
                 ApprovalDelay=30000,
839
 
                 ApprovalDuration=1000,
840
 
                 Checker=":",
841
 
                 ExtendedTimeout=900000,
842
 
                 Expires="2019-02-05T00:00:00",
843
 
                 LastCheckerStatus=-2)),
844
 
            ])
845
 
 
846
 
class TestPrintTableCmd(TestCmd):
847
 
    def test_normal(self):
848
 
        output = PrintTableCmd().output(self.clients)
849
 
        expected_output = """
850
 
Name   Enabled Timeout  Last Successful Check
851
 
foo    Yes     00:05:00 2019-02-03T00:00:00  
852
 
barbar Yes     00:05:00 2019-02-04T00:00:00  
853
 
"""[1:-1]
854
 
        self.assertEqual(output, expected_output)
855
 
    def test_verbose(self):
856
 
        output = PrintTableCmd(verbose=True).output(self.clients)
857
 
        expected_output = """
858
 
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
859
 
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                  
860
 
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                 
861
 
"""[1:-1]
862
 
        self.assertEqual(output, expected_output)
863
 
    def test_one_client(self):
864
 
        output = PrintTableCmd().output({"foo": self.clients["foo"]})
865
 
        expected_output = """
866
 
Name Enabled Timeout  Last Successful Check
867
 
foo  Yes     00:05:00 2019-02-03T00:00:00  
868
 
"""[1:-1]
869
 
        self.assertEqual(output, expected_output)
870
 
 
871
 
class TestDumpJSONCmd(TestCmd):
872
 
    def setUp(self):
873
 
        self.expected_json = {
874
 
            "foo": {
875
 
                "Name": "foo",
876
 
                "KeyID": ("92ed150794387c03ce684574b1139a65"
877
 
                          "94a34f895daaaf09fd8ea90a27cddb12"),
878
 
                "Host": "foo.example.org",
879
 
                "Enabled": True,
880
 
                "Timeout": 300000,
881
 
                "LastCheckedOK": "2019-02-03T00:00:00",
882
 
                "Created": "2019-01-02T00:00:00",
883
 
                "Interval": 120000,
884
 
                "Fingerprint": ("778827225BA7DE539C5A"
885
 
                                "7CFA59CFF7CDBD9A5920"),
886
 
                "CheckerRunning": False,
887
 
                "LastEnabled": "2019-01-03T00:00:00",
888
 
                "ApprovalPending": False,
889
 
                "ApprovedByDefault": True,
890
 
                "LastApprovalRequest": "",
891
 
                "ApprovalDelay": 0,
892
 
                "ApprovalDuration": 1000,
893
 
                "Checker": "fping -q -- %(host)s",
894
 
                "ExtendedTimeout": 900000,
895
 
                "Expires": "2019-02-04T00:00:00",
896
 
                "LastCheckerStatus": 0,
897
 
            },
898
 
            "barbar": {
899
 
                "Name": "barbar",
900
 
                "KeyID": ("0558568eedd67d622f5c83b35a115f79"
901
 
                          "6ab612cff5ad227247e46c2b020f441c"),
902
 
                "Host": "192.0.2.3",
903
 
                "Enabled": True,
904
 
                "Timeout": 300000,
905
 
                "LastCheckedOK": "2019-02-04T00:00:00",
906
 
                "Created": "2019-01-03T00:00:00",
907
 
                "Interval": 120000,
908
 
                "Fingerprint": ("3E393AEAEFB84C7E89E2"
909
 
                                "F547B3A107558FCA3A27"),
910
 
                "CheckerRunning": True,
911
 
                "LastEnabled": "2019-01-04T00:00:00",
912
 
                "ApprovalPending": False,
913
 
                "ApprovedByDefault": False,
914
 
                "LastApprovalRequest": "2019-01-03T00:00:00",
915
 
                "ApprovalDelay": 30000,
916
 
                "ApprovalDuration": 1000,
917
 
                "Checker": ":",
918
 
                "ExtendedTimeout": 900000,
919
 
                "Expires": "2019-02-05T00:00:00",
920
 
                "LastCheckerStatus": -2,
921
 
            },
 
597
class Test_TableOfClients(unittest.TestCase):
 
598
    def setUp(self):
 
599
        self.tablewords = {
 
600
            "Attr1": "X",
 
601
            "AttrTwo": "Yy",
 
602
            "AttrThree": "Zzz",
 
603
            "Bool": "A D-BUS Boolean",
 
604
            "NonDbusBoolean": "A Non-D-BUS Boolean",
 
605
            "Integer": "An Integer",
 
606
            "Timeout": "Timedelta 1",
 
607
            "Interval": "Timedelta 2",
 
608
            "ApprovalDelay": "Timedelta 3",
 
609
            "ApprovalDuration": "Timedelta 4",
 
610
            "ExtendedTimeout": "Timedelta 5",
 
611
            "String": "A String",
922
612
        }
923
 
        return super(TestDumpJSONCmd, self).setUp()
924
 
    def test_normal(self):
925
 
        json_data = json.loads(DumpJSONCmd().output(self.clients))
926
 
        self.assertDictEqual(json_data, self.expected_json)
927
 
    def test_one_client(self):
928
 
        clients = {"foo": self.clients["foo"]}
929
 
        json_data = json.loads(DumpJSONCmd().output(clients))
930
 
        expected_json = {"foo": self.expected_json["foo"]}
931
 
        self.assertDictEqual(json_data, expected_json)
 
613
        self.keywords = ["Attr1", "AttrTwo"]
 
614
        self.clients = [
 
615
            {
 
616
                "Attr1": "x1",
 
617
                "AttrTwo": "y1",
 
618
                "AttrThree": "z1",
 
619
                "Bool": dbus.Boolean(False),
 
620
                "NonDbusBoolean": False,
 
621
                "Integer": 0,
 
622
                "Timeout": 0,
 
623
                "Interval": 1000,
 
624
                "ApprovalDelay": 2000,
 
625
                "ApprovalDuration": 3000,
 
626
                "ExtendedTimeout": 4000,
 
627
                "String": "",
 
628
            },
 
629
            {
 
630
                "Attr1": "x2",
 
631
                "AttrTwo": "y2",
 
632
                "AttrThree": "z2",
 
633
                "Bool": dbus.Boolean(True),
 
634
                "NonDbusBoolean": True,
 
635
                "Integer": 1,
 
636
                "Timeout": 93785000,
 
637
                "Interval": 93786000,
 
638
                "ApprovalDelay": 93787000,
 
639
                "ApprovalDuration": 93788000,
 
640
                "ExtendedTimeout": 93789000,
 
641
                "String": "A huge string which will not fit," * 10,
 
642
            },
 
643
        ]
 
644
    def test_short_header(self):
 
645
        rows = TableOfClients(self.clients, self.keywords,
 
646
                              self.tablewords).rows()
 
647
        expected_rows = [
 
648
            "X  Yy",
 
649
            "x1 y1",
 
650
            "x2 y2"]
 
651
        self.assertEqual(rows, expected_rows)
 
652
    def test_booleans(self):
 
653
        keywords = ["Bool", "NonDbusBoolean"]
 
654
        rows = TableOfClients(self.clients, keywords,
 
655
                              self.tablewords).rows()
 
656
        expected_rows = [
 
657
            "A D-BUS Boolean A Non-D-BUS Boolean",
 
658
            "No              False              ",
 
659
            "Yes             True               ",
 
660
        ]
 
661
        self.assertEqual(rows, expected_rows)
 
662
    def test_milliseconds_detection(self):
 
663
        keywords = ["Integer", "Timeout", "Interval", "ApprovalDelay",
 
664
                    "ApprovalDuration", "ExtendedTimeout"]
 
665
        rows = TableOfClients(self.clients, keywords,
 
666
                              self.tablewords).rows()
 
667
        expected_rows = ("""
 
668
An Integer Timedelta 1 Timedelta 2 Timedelta 3 Timedelta 4 Timedelta 5
 
669
0          00:00:00    00:00:01    00:00:02    00:00:03    00:00:04   
 
670
1          1T02:03:05  1T02:03:06  1T02:03:07  1T02:03:08  1T02:03:09 
 
671
"""
 
672
        ).splitlines()[1:]
 
673
        self.assertEqual(rows, expected_rows)
 
674
    def test_empty_and_long_string_values(self):
 
675
        keywords = ["String"]
 
676
        rows = TableOfClients(self.clients, keywords,
 
677
                              self.tablewords).rows()
 
678
        expected_rows = ("""
 
679
A String                                                                                                                                                                                                                                                                                                                                  
 
680
                                                                                                                                                                                                                                                                                                                                          
 
681
A huge string which will not fit,A huge string which will not fit,A huge string which will not fit,A huge string which will not fit,A huge string which will not fit,A huge string which will not fit,A huge string which will not fit,A huge string which will not fit,A huge string which will not fit,A huge string which will not fit,
 
682
"""
 
683
        ).splitlines()[1:]
 
684
        self.assertEqual(rows, expected_rows)
 
685
 
932
686
 
933
687
 
934
688
def should_only_run_tests():