510
365
follow_name_owner_changes=True),
511
366
avahi.DBUS_INTERFACE_SERVER)
512
367
self.server.connect_to_signal("StateChanged",
513
self.server_state_changed)
368
self.server_state_changed)
514
369
self.server_state_changed(self.server.GetState())
517
371
class AvahiServiceToSyslog(AvahiService):
518
def rename(self, *args, **kwargs):
519
373
"""Add the new name to the syslog messages"""
520
ret = super(AvahiServiceToSyslog, self).rename(*args, **kwargs)
521
syslogger.setFormatter(logging.Formatter(
522
'Mandos ({}) [%(process)d]: %(levelname)s: %(message)s'
374
ret = AvahiService.rename(self)
375
syslogger.setFormatter(logging.Formatter
376
('Mandos (%s) [%%(process)d]:'
377
' %%(levelname)s: %%(message)s'
527
# Pretend that we have a GnuTLS module
529
"""This isn't so much a class as it is a module-like namespace."""
531
library = ctypes.util.find_library("gnutls")
533
library = ctypes.util.find_library("gnutls-deb0")
534
_library = ctypes.cdll.LoadLibrary(library)
537
# Unless otherwise indicated, the constants and types below are
538
# all from the gnutls/gnutls.h C header file.
549
E_NO_CERTIFICATE_FOUND = -49
554
KEYID_USE_SHA256 = 1 # gnutls/x509.h
555
OPENPGP_FMT_RAW = 0 # gnutls/openpgp.h
558
class session_int(ctypes.Structure):
560
session_t = ctypes.POINTER(session_int)
562
class certificate_credentials_st(ctypes.Structure):
564
certificate_credentials_t = ctypes.POINTER(
565
certificate_credentials_st)
566
certificate_type_t = ctypes.c_int
568
class datum_t(ctypes.Structure):
569
_fields_ = [('data', ctypes.POINTER(ctypes.c_ubyte)),
570
('size', ctypes.c_uint)]
572
class openpgp_crt_int(ctypes.Structure):
574
openpgp_crt_t = ctypes.POINTER(openpgp_crt_int)
575
openpgp_crt_fmt_t = ctypes.c_int # gnutls/openpgp.h
576
log_func = ctypes.CFUNCTYPE(None, ctypes.c_int, ctypes.c_char_p)
577
credentials_type_t = ctypes.c_int
578
transport_ptr_t = ctypes.c_void_p
579
close_request_t = ctypes.c_int
582
class Error(Exception):
583
def __init__(self, message=None, code=None, args=()):
584
# Default usage is by a message string, but if a return
585
# code is passed, convert it to a string with
588
if message is None and code is not None:
589
message = gnutls.strerror(code)
590
return super(gnutls.Error, self).__init__(
593
class CertificateSecurityError(Error):
599
self._c_object = gnutls.certificate_credentials_t()
600
gnutls.certificate_allocate_credentials(
601
ctypes.byref(self._c_object))
602
self.type = gnutls.CRD_CERTIFICATE
605
gnutls.certificate_free_credentials(self._c_object)
608
def __init__(self, socket, credentials=None):
609
self._c_object = gnutls.session_t()
610
gnutls_flags = gnutls.CLIENT
611
if gnutls.check_version(b"3.5.6"):
612
gnutls_flags |= gnutls.NO_TICKETS
614
gnutls_flags |= gnutls.ENABLE_RAWPK
615
gnutls.init(ctypes.byref(self._c_object), gnutls_flags)
617
gnutls.set_default_priority(self._c_object)
618
gnutls.transport_set_ptr(self._c_object, socket.fileno())
619
gnutls.handshake_set_private_extensions(self._c_object,
622
if credentials is None:
623
credentials = gnutls.Credentials()
624
gnutls.credentials_set(self._c_object, credentials.type,
625
ctypes.cast(credentials._c_object,
627
self.credentials = credentials
630
gnutls.deinit(self._c_object)
633
return gnutls.handshake(self._c_object)
635
def send(self, data):
639
data_len -= gnutls.record_send(self._c_object,
644
return gnutls.bye(self._c_object, gnutls.SHUT_RDWR)
646
# Error handling functions
647
def _error_code(result):
648
"""A function to raise exceptions on errors, suitable
649
for the 'restype' attribute on ctypes functions"""
652
if result == gnutls.E_NO_CERTIFICATE_FOUND:
653
raise gnutls.CertificateSecurityError(code=result)
654
raise gnutls.Error(code=result)
656
def _retry_on_error(result, func, arguments):
657
"""A function to retry on some errors, suitable
658
for the 'errcheck' attribute on ctypes functions"""
660
if result not in (gnutls.E_INTERRUPTED, gnutls.E_AGAIN):
661
return _error_code(result)
662
result = func(*arguments)
665
# Unless otherwise indicated, the function declarations below are
666
# all from the gnutls/gnutls.h C header file.
669
priority_set_direct = _library.gnutls_priority_set_direct
670
priority_set_direct.argtypes = [session_t, ctypes.c_char_p,
671
ctypes.POINTER(ctypes.c_char_p)]
672
priority_set_direct.restype = _error_code
674
init = _library.gnutls_init
675
init.argtypes = [ctypes.POINTER(session_t), ctypes.c_int]
676
init.restype = _error_code
678
set_default_priority = _library.gnutls_set_default_priority
679
set_default_priority.argtypes = [session_t]
680
set_default_priority.restype = _error_code
682
record_send = _library.gnutls_record_send
683
record_send.argtypes = [session_t, ctypes.c_void_p,
685
record_send.restype = ctypes.c_ssize_t
686
record_send.errcheck = _retry_on_error
688
certificate_allocate_credentials = (
689
_library.gnutls_certificate_allocate_credentials)
690
certificate_allocate_credentials.argtypes = [
691
ctypes.POINTER(certificate_credentials_t)]
692
certificate_allocate_credentials.restype = _error_code
694
certificate_free_credentials = (
695
_library.gnutls_certificate_free_credentials)
696
certificate_free_credentials.argtypes = [
697
certificate_credentials_t]
698
certificate_free_credentials.restype = None
700
handshake_set_private_extensions = (
701
_library.gnutls_handshake_set_private_extensions)
702
handshake_set_private_extensions.argtypes = [session_t,
704
handshake_set_private_extensions.restype = None
706
credentials_set = _library.gnutls_credentials_set
707
credentials_set.argtypes = [session_t, credentials_type_t,
709
credentials_set.restype = _error_code
711
strerror = _library.gnutls_strerror
712
strerror.argtypes = [ctypes.c_int]
713
strerror.restype = ctypes.c_char_p
715
certificate_type_get = _library.gnutls_certificate_type_get
716
certificate_type_get.argtypes = [session_t]
717
certificate_type_get.restype = _error_code
719
certificate_get_peers = _library.gnutls_certificate_get_peers
720
certificate_get_peers.argtypes = [session_t,
721
ctypes.POINTER(ctypes.c_uint)]
722
certificate_get_peers.restype = ctypes.POINTER(datum_t)
724
global_set_log_level = _library.gnutls_global_set_log_level
725
global_set_log_level.argtypes = [ctypes.c_int]
726
global_set_log_level.restype = None
728
global_set_log_function = _library.gnutls_global_set_log_function
729
global_set_log_function.argtypes = [log_func]
730
global_set_log_function.restype = None
732
deinit = _library.gnutls_deinit
733
deinit.argtypes = [session_t]
734
deinit.restype = None
736
handshake = _library.gnutls_handshake
737
handshake.argtypes = [session_t]
738
handshake.restype = _error_code
739
handshake.errcheck = _retry_on_error
741
transport_set_ptr = _library.gnutls_transport_set_ptr
742
transport_set_ptr.argtypes = [session_t, transport_ptr_t]
743
transport_set_ptr.restype = None
745
bye = _library.gnutls_bye
746
bye.argtypes = [session_t, close_request_t]
747
bye.restype = _error_code
748
bye.errcheck = _retry_on_error
750
check_version = _library.gnutls_check_version
751
check_version.argtypes = [ctypes.c_char_p]
752
check_version.restype = ctypes.c_char_p
754
_need_version = b"3.3.0"
755
if check_version(_need_version) is None:
756
raise self.Error("Needs GnuTLS {} or later"
757
.format(_need_version))
759
_tls_rawpk_version = b"3.6.6"
760
has_rawpk = bool(check_version(_tls_rawpk_version))
764
class pubkey_st(ctypes.Structure):
766
pubkey_t = ctypes.POINTER(pubkey_st)
768
x509_crt_fmt_t = ctypes.c_int
770
# All the function declarations below are from gnutls/abstract.h
771
pubkey_init = _library.gnutls_pubkey_init
772
pubkey_init.argtypes = [ctypes.POINTER(pubkey_t)]
773
pubkey_init.restype = _error_code
775
pubkey_import = _library.gnutls_pubkey_import
776
pubkey_import.argtypes = [pubkey_t, ctypes.POINTER(datum_t),
778
pubkey_import.restype = _error_code
780
pubkey_get_key_id = _library.gnutls_pubkey_get_key_id
781
pubkey_get_key_id.argtypes = [pubkey_t, ctypes.c_int,
782
ctypes.POINTER(ctypes.c_ubyte),
783
ctypes.POINTER(ctypes.c_size_t)]
784
pubkey_get_key_id.restype = _error_code
786
pubkey_deinit = _library.gnutls_pubkey_deinit
787
pubkey_deinit.argtypes = [pubkey_t]
788
pubkey_deinit.restype = None
790
# All the function declarations below are from gnutls/openpgp.h
792
openpgp_crt_init = _library.gnutls_openpgp_crt_init
793
openpgp_crt_init.argtypes = [ctypes.POINTER(openpgp_crt_t)]
794
openpgp_crt_init.restype = _error_code
796
openpgp_crt_import = _library.gnutls_openpgp_crt_import
797
openpgp_crt_import.argtypes = [openpgp_crt_t,
798
ctypes.POINTER(datum_t),
800
openpgp_crt_import.restype = _error_code
802
openpgp_crt_verify_self = _library.gnutls_openpgp_crt_verify_self
803
openpgp_crt_verify_self.argtypes = [openpgp_crt_t, ctypes.c_uint,
804
ctypes.POINTER(ctypes.c_uint)]
805
openpgp_crt_verify_self.restype = _error_code
807
openpgp_crt_deinit = _library.gnutls_openpgp_crt_deinit
808
openpgp_crt_deinit.argtypes = [openpgp_crt_t]
809
openpgp_crt_deinit.restype = None
811
openpgp_crt_get_fingerprint = (
812
_library.gnutls_openpgp_crt_get_fingerprint)
813
openpgp_crt_get_fingerprint.argtypes = [openpgp_crt_t,
817
openpgp_crt_get_fingerprint.restype = _error_code
819
if check_version(b"3.6.4"):
820
certificate_type_get2 = _library.gnutls_certificate_type_get2
821
certificate_type_get2.argtypes = [session_t, ctypes.c_int]
822
certificate_type_get2.restype = _error_code
824
# Remove non-public functions
825
del _error_code, _retry_on_error
828
def call_pipe(connection, # : multiprocessing.Connection
829
func, *args, **kwargs):
830
"""This function is meant to be called by multiprocessing.Process
832
This function runs func(*args, **kwargs), and writes the resulting
833
return value on the provided multiprocessing.Connection.
835
connection.send(func(*args, **kwargs))
381
def _timedelta_to_milliseconds(td):
382
"Convert a datetime.timedelta() to milliseconds"
383
return ((td.days * 24 * 60 * 60 * 1000)
384
+ (td.seconds * 1000)
385
+ (td.microseconds // 1000))
387
class Client(object):
840
388
"""A representation of a client host served by this server.
843
approved: bool(); 'None' if not yet approved/disapproved
391
_approved: bool(); 'None' if not yet approved/disapproved
844
392
approval_delay: datetime.timedelta(); Time to wait for approval
845
393
approval_duration: datetime.timedelta(); Duration of one approval
846
checker: multiprocessing.Process(); a running checker process used
847
to see if the client lives. 'None' if no process is
849
checker_callback_tag: a GLib event source tag, or None
394
checker: subprocess.Popen(); a running checker process used
395
to see if the client lives.
396
'None' if no process is running.
397
checker_callback_tag: a gobject event source tag, or None
850
398
checker_command: string; External command which is run to check
851
399
if client lives. %() expansions are done at
852
400
runtime with vars(self) as dict, so that for
853
401
instance %(name)s can be used in the command.
854
checker_initiator_tag: a GLib event source tag, or None
402
checker_initiator_tag: a gobject event source tag, or None
855
403
created: datetime.datetime(); (UTC) object creation
856
404
client_structure: Object describing what attributes a client has
857
405
and is used for storing the client at exit
858
406
current_checker_command: string; current running checker_command
859
disable_initiator_tag: a GLib event source tag, or None
407
disable_initiator_tag: a gobject event source tag, or None
861
409
fingerprint: string (40 or 32 hexadecimal digits); used to
862
uniquely identify an OpenPGP client
863
key_id: string (64 hexadecimal digits); used to uniquely identify
864
a client using raw public keys
410
uniquely identify the client
865
411
host: string; available for use by the checker command
866
412
interval: datetime.timedelta(); How often to start a new checker
867
413
last_approval_request: datetime.datetime(); (UTC) or None
868
414
last_checked_ok: datetime.datetime(); (UTC) or None
869
416
last_checker_status: integer between 0 and 255 reflecting exit
870
417
status of last checker. -1 reflects crashed
871
checker, -2 means no checker completed yet.
872
last_checker_signal: The signal which killed the last checker, if
873
last_checker_status is -1
874
419
last_enabled: datetime.datetime(); (UTC) or None
875
420
name: string; from the config file, used in log messages and
876
421
D-Bus identifiers
877
422
secret: bytestring; sent verbatim (over TLS) to client
878
423
timeout: datetime.timedelta(); How long from last_checked_ok
879
424
until this client is disabled
880
extended_timeout: extra long timeout when secret has been sent
425
extended_timeout: extra long timeout when password has been sent
881
426
runtime_expansions: Allowed attributes for runtime expansion.
882
427
expires: datetime.datetime(); time (UTC) when a client will be
883
428
disabled, or None
884
server_settings: The server_settings dict from main()
887
431
runtime_expansions = ("approval_delay", "approval_duration",
888
"created", "enabled", "expires", "key_id",
889
"fingerprint", "host", "interval",
890
"last_approval_request", "last_checked_ok",
432
"created", "enabled", "fingerprint",
433
"host", "interval", "last_checked_ok",
891
434
"last_enabled", "name", "timeout")
894
"extended_timeout": "PT15M",
896
"checker": "fping -q -- %%(host)s",
898
"approval_delay": "PT0S",
899
"approval_duration": "PT1S",
900
"approved_by_default": "True",
905
def config_parser(config):
906
"""Construct a new dict of client settings of this form:
907
{ client_name: {setting_name: value, ...}, ...}
908
with exceptions for any special settings as defined above.
909
NOTE: Must be a pure function. Must return the same result
910
value given the same arguments.
913
for client_name in config.sections():
914
section = dict(config.items(client_name))
915
client = settings[client_name] = {}
917
client["host"] = section["host"]
918
# Reformat values from string types to Python types
919
client["approved_by_default"] = config.getboolean(
920
client_name, "approved_by_default")
921
client["enabled"] = config.getboolean(client_name,
924
# Uppercase and remove spaces from key_id and fingerprint
925
# for later comparison purposes with return value from the
926
# key_id() and fingerprint() functions
927
client["key_id"] = (section.get("key_id", "").upper()
929
client["fingerprint"] = (section["fingerprint"].upper()
931
if "secret" in section:
932
client["secret"] = codecs.decode(section["secret"]
935
elif "secfile" in section:
936
with open(os.path.expanduser(os.path.expandvars
937
(section["secfile"])),
939
client["secret"] = secfile.read()
941
raise TypeError("No secret or secfile for section {}"
943
client["timeout"] = string_to_delta(section["timeout"])
944
client["extended_timeout"] = string_to_delta(
945
section["extended_timeout"])
946
client["interval"] = string_to_delta(section["interval"])
947
client["approval_delay"] = string_to_delta(
948
section["approval_delay"])
949
client["approval_duration"] = string_to_delta(
950
section["approval_duration"])
951
client["checker_command"] = section["checker"]
952
client["last_approval_request"] = None
953
client["last_checked_ok"] = None
954
client["last_checker_status"] = -2
958
def __init__(self, settings, name=None, server_settings=None):
436
def timeout_milliseconds(self):
437
"Return the 'timeout' attribute in milliseconds"
438
return _timedelta_to_milliseconds(self.timeout)
440
def extended_timeout_milliseconds(self):
441
"Return the 'extended_timeout' attribute in milliseconds"
442
return _timedelta_to_milliseconds(self.extended_timeout)
444
def interval_milliseconds(self):
445
"Return the 'interval' attribute in milliseconds"
446
return _timedelta_to_milliseconds(self.interval)
448
def approval_delay_milliseconds(self):
449
return _timedelta_to_milliseconds(self.approval_delay)
451
def __init__(self, name = None, config=None):
452
"""Note: the 'checker' key in 'config' sets the
453
'checker_command' attribute and *not* the 'checker'
960
if server_settings is None:
962
self.server_settings = server_settings
963
# adding all client settings
964
for setting, value in settings.items():
965
setattr(self, setting, value)
968
if not hasattr(self, "last_enabled"):
969
self.last_enabled = datetime.datetime.utcnow()
970
if not hasattr(self, "expires"):
971
self.expires = (datetime.datetime.utcnow()
974
self.last_enabled = None
977
458
logger.debug("Creating client %r", self.name)
978
logger.debug(" Key ID: %s", self.key_id)
459
# Uppercase and remove spaces from fingerprint for later
460
# comparison purposes with return value from the fingerprint()
462
self.fingerprint = (config["fingerprint"].upper()
979
464
logger.debug(" Fingerprint: %s", self.fingerprint)
980
self.created = settings.get("created",
981
datetime.datetime.utcnow())
983
# attributes specific for this server instance
465
if "secret" in config:
466
self.secret = config["secret"].decode("base64")
467
elif "secfile" in config:
468
with open(os.path.expanduser(os.path.expandvars
469
(config["secfile"])),
471
self.secret = secfile.read()
473
raise TypeError("No secret or secfile for client %s"
475
self.host = config.get("host", "")
476
self.created = datetime.datetime.utcnow()
477
self.enabled = config.get("enabled", True)
478
self.last_approval_request = None
480
self.last_enabled = datetime.datetime.utcnow()
482
self.last_enabled = None
483
self.last_checked_ok = None
484
self.last_checker_status = None
485
self.timeout = string_to_delta(config["timeout"])
486
self.extended_timeout = string_to_delta(config
487
["extended_timeout"])
488
self.interval = string_to_delta(config["interval"])
984
489
self.checker = None
985
490
self.checker_initiator_tag = None
986
491
self.disable_initiator_tag = None
493
self.expires = datetime.datetime.utcnow() + self.timeout
987
496
self.checker_callback_tag = None
497
self.checker_command = config["checker"]
988
498
self.current_checker_command = None
499
self._approved = None
500
self.approved_by_default = config.get("approved_by_default",
990
502
self.approvals_pending = 0
991
self.changedstate = multiprocessing_manager.Condition(
992
multiprocessing_manager.Lock())
993
self.client_structure = [attr
994
for attr in self.__dict__.keys()
503
self.approval_delay = string_to_delta(
504
config["approval_delay"])
505
self.approval_duration = string_to_delta(
506
config["approval_duration"])
507
self.changedstate = (multiprocessing_manager
508
.Condition(multiprocessing_manager
510
self.client_structure = [attr for attr in
511
self.__dict__.iterkeys()
995
512
if not attr.startswith("_")]
996
513
self.client_structure.append("client_structure")
998
for name, t in inspect.getmembers(
999
type(self), lambda obj: isinstance(obj, property)):
515
for name, t in inspect.getmembers(type(self),
1000
519
if not name.startswith("_"):
1001
520
self.client_structure.append(name)
1003
522
# Send notice to process children that client state has changed
1004
523
def send_changedstate(self):
1005
524
with self.changedstate:
1006
525
self.changedstate.notify_all()
1008
527
def enable(self):
1009
528
"""Start this client's checker and timeout hooks"""
1010
529
if getattr(self, "enabled", False):
1011
530
# Already enabled
532
self.send_changedstate()
1013
533
self.expires = datetime.datetime.utcnow() + self.timeout
1014
534
self.enabled = True
1015
535
self.last_enabled = datetime.datetime.utcnow()
1016
536
self.init_checker()
1017
self.send_changedstate()
1019
538
def disable(self, quiet=True):
1020
539
"""Disable this client."""
1021
540
if not getattr(self, "enabled", False):
543
self.send_changedstate()
1024
545
logger.info("Disabling client %s", self.name)
1025
if getattr(self, "disable_initiator_tag", None) is not None:
1026
GLib.source_remove(self.disable_initiator_tag)
546
if getattr(self, "disable_initiator_tag", False):
547
gobject.source_remove(self.disable_initiator_tag)
1027
548
self.disable_initiator_tag = None
1028
549
self.expires = None
1029
if getattr(self, "checker_initiator_tag", None) is not None:
1030
GLib.source_remove(self.checker_initiator_tag)
550
if getattr(self, "checker_initiator_tag", False):
551
gobject.source_remove(self.checker_initiator_tag)
1031
552
self.checker_initiator_tag = None
1032
553
self.stop_checker()
1033
554
self.enabled = False
1035
self.send_changedstate()
1036
# Do not run this again if called by a GLib.timeout_add
555
# Do not run this again if called by a gobject.timeout_add
1039
558
def __del__(self):
1042
561
def init_checker(self):
1043
562
# Schedule a new checker to be started an 'interval' from now,
1044
563
# and every interval from then on.
1045
if self.checker_initiator_tag is not None:
1046
GLib.source_remove(self.checker_initiator_tag)
1047
self.checker_initiator_tag = GLib.timeout_add(
1048
random.randrange(int(self.interval.total_seconds() * 1000
564
self.checker_initiator_tag = (gobject.timeout_add
565
(self.interval_milliseconds(),
1051
567
# Schedule a disable() when 'timeout' has passed
1052
if self.disable_initiator_tag is not None:
1053
GLib.source_remove(self.disable_initiator_tag)
1054
self.disable_initiator_tag = GLib.timeout_add(
1055
int(self.timeout.total_seconds() * 1000), self.disable)
568
self.disable_initiator_tag = (gobject.timeout_add
569
(self.timeout_milliseconds(),
1056
571
# Also start a new checker *right now*.
1057
572
self.start_checker()
1059
def checker_callback(self, source, condition, connection,
574
def checker_callback(self, pid, condition, command):
1061
575
"""The checker has completed, so take appropriate actions."""
1062
# Read return code from connection (see call_pipe)
1063
returncode = connection.recv()
1065
if self.checker is not None:
1067
576
self.checker_callback_tag = None
1068
577
self.checker = None
1071
self.last_checker_status = returncode
1072
self.last_checker_signal = None
578
if os.WIFEXITED(condition):
579
self.last_checker_status = os.WEXITSTATUS(condition)
1073
580
if self.last_checker_status == 0:
1074
581
logger.info("Checker for %(name)s succeeded",
1076
583
self.checked_ok()
1078
logger.info("Checker for %(name)s failed", vars(self))
585
logger.info("Checker for %(name)s failed",
1080
588
self.last_checker_status = -1
1081
self.last_checker_signal = -returncode
1082
589
logger.warning("Checker for %(name)s crashed?",
1086
def checked_ok(self):
1087
"""Assert that the client has been seen, alive and well."""
1088
self.last_checked_ok = datetime.datetime.utcnow()
1089
self.last_checker_status = 0
1090
self.last_checker_signal = None
1093
def bump_timeout(self, timeout=None):
1094
"""Bump up the timeout for this client."""
592
def checked_ok(self, timeout=None):
593
"""Bump up the timeout for this client.
595
This should only be called when the client has been seen,
1095
598
if timeout is None:
1096
599
timeout = self.timeout
600
self.last_checked_ok = datetime.datetime.utcnow()
1097
601
if self.disable_initiator_tag is not None:
1098
GLib.source_remove(self.disable_initiator_tag)
1099
self.disable_initiator_tag = None
602
gobject.source_remove(self.disable_initiator_tag)
1100
603
if getattr(self, "enabled", False):
1101
self.disable_initiator_tag = GLib.timeout_add(
1102
int(timeout.total_seconds() * 1000), self.disable)
604
self.disable_initiator_tag = (gobject.timeout_add
605
(_timedelta_to_milliseconds
606
(timeout), self.disable))
1103
607
self.expires = datetime.datetime.utcnow() + timeout
1105
609
def need_approval(self):
1106
610
self.last_approval_request = datetime.datetime.utcnow()
1108
612
def start_checker(self):
1109
613
"""Start a new checker subprocess if one is not running.
1111
615
If a checker already exists, leave it running and do
1113
617
# The reason for not killing a running checker is that if we
1114
# did that, and if a checker (for some reason) started running
1115
# slowly and taking more than 'interval' time, then the client
1116
# would inevitably timeout, since no checker would get a
1117
# chance to run to completion. If we instead leave running
618
# did that, then if a checker (for some reason) started
619
# running slowly and taking more than 'interval' time, the
620
# client would inevitably timeout, since no checker would get
621
# a chance to run to completion. If we instead leave running
1118
622
# checkers alone, the checker would have to take more time
1119
623
# than 'timeout' for the client to be disabled, which is as it
1122
if self.checker is not None and not self.checker.is_alive():
1123
logger.warning("Checker was not alive; joining")
626
# If a checker exists, make sure it is not a zombie
628
pid, status = os.waitpid(self.checker.pid, os.WNOHANG)
629
except (AttributeError, OSError) as error:
630
if (isinstance(error, OSError)
631
and error.errno != errno.ECHILD):
635
logger.warning("Checker was a zombie")
636
gobject.source_remove(self.checker_callback_tag)
637
self.checker_callback(pid, status,
638
self.current_checker_command)
1126
639
# Start a new checker if needed
1127
640
if self.checker is None:
1128
# Escape attributes for the shell
1130
attr: re.escape(str(getattr(self, attr)))
1131
for attr in self.runtime_expansions}
1133
command = self.checker_command % escaped_attrs
1134
except TypeError as error:
1135
logger.error('Could not format string "%s"',
1136
self.checker_command,
1138
return True # Try again later
642
# In case checker_command has exactly one % operator
643
command = self.checker_command % self.host
645
# Escape attributes for the shell
646
escaped_attrs = dict(
648
re.escape(unicode(str(getattr(self, attr, "")),
652
self.runtime_expansions)
655
command = self.checker_command % escaped_attrs
656
except TypeError as error:
657
logger.error('Could not format string "%s":'
658
' %s', self.checker_command, error)
659
return True # Try again later
1139
660
self.current_checker_command = command
1140
logger.info("Starting checker %r for %s", command,
1142
# We don't need to redirect stdout and stderr, since
1143
# in normal mode, that is already done by daemon(),
1144
# and in debug mode we don't want to. (Stdin is
1145
# always replaced by /dev/null.)
1146
# The exception is when not debugging but nevertheless
1147
# running in the foreground; use the previously
1149
popen_args = {"close_fds": True,
1152
if (not self.server_settings["debug"]
1153
and self.server_settings["foreground"]):
1154
popen_args.update({"stdout": wnull,
1156
pipe = multiprocessing.Pipe(duplex=False)
1157
self.checker = multiprocessing.Process(
1159
args=(pipe[1], subprocess.call, command),
1161
self.checker.start()
1162
self.checker_callback_tag = GLib.io_add_watch(
1163
GLib.IOChannel.unix_new(pipe[0].fileno()),
1164
GLib.PRIORITY_DEFAULT, GLib.IO_IN,
1165
self.checker_callback, pipe[0], command)
1166
# Re-run this periodically if run by GLib.timeout_add
662
logger.info("Starting checker %r for %s",
664
# We don't need to redirect stdout and stderr, since
665
# in normal mode, that is already done by daemon(),
666
# and in debug mode we don't want to. (Stdin is
667
# always replaced by /dev/null.)
668
self.checker = subprocess.Popen(command,
671
self.checker_callback_tag = (gobject.child_watch_add
673
self.checker_callback,
675
# The checker may have completed before the gobject
676
# watch was added. Check for this.
677
pid, status = os.waitpid(self.checker.pid, os.WNOHANG)
679
gobject.source_remove(self.checker_callback_tag)
680
self.checker_callback(pid, status, command)
681
except OSError as error:
682
logger.error("Failed to start subprocess: %s",
684
# Re-run this periodically if run by gobject.timeout_add
1169
687
def stop_checker(self):
1170
688
"""Force the checker process, if any, to stop."""
1171
689
if self.checker_callback_tag:
1172
GLib.source_remove(self.checker_callback_tag)
690
gobject.source_remove(self.checker_callback_tag)
1173
691
self.checker_callback_tag = None
1174
692
if getattr(self, "checker", None) is None:
1176
694
logger.debug("Stopping checker for %(name)s", vars(self))
1177
self.checker.terminate()
696
os.kill(self.checker.pid, signal.SIGTERM)
698
#if self.checker.poll() is None:
699
# os.kill(self.checker.pid, signal.SIGKILL)
700
except OSError as error:
701
if error.errno != errno.ESRCH: # No such process
1178
703
self.checker = None
1181
def dbus_service_property(dbus_interface,
706
def dbus_service_property(dbus_interface, signature="v",
707
access="readwrite", byte_arrays=False):
1185
708
"""Decorators for marking methods of a DBusObjectWithProperties to
1186
709
become properties on the D-Bus.
1188
711
The decorated method will be called with no arguments by "Get"
1189
712
and with one argument by "Set".
1191
714
The parameters, where they are supported, are the same as
1192
715
dbus.service.method, except there is only "signature", since the
1193
716
type from Get() and the type sent to Set() is the same.
1525
886
except (AttributeError, xml.dom.DOMException,
1526
887
xml.parsers.expat.ExpatError) as error:
1527
888
logger.error("Failed to override Introspection method",
1533
dbus.OBJECT_MANAGER_IFACE
1534
except AttributeError:
1535
dbus.OBJECT_MANAGER_IFACE = "org.freedesktop.DBus.ObjectManager"
1538
class DBusObjectWithObjectManager(DBusObjectWithAnnotations):
1539
"""A D-Bus object with an ObjectManager.
1541
Classes inheriting from this exposes the standard
1542
GetManagedObjects call and the InterfacesAdded and
1543
InterfacesRemoved signals on the standard
1544
"org.freedesktop.DBus.ObjectManager" interface.
1546
Note: No signals are sent automatically; they must be sent
1549
@dbus.service.method(dbus.OBJECT_MANAGER_IFACE,
1550
out_signature="a{oa{sa{sv}}}")
1551
def GetManagedObjects(self):
1552
"""This function must be overridden"""
1553
raise NotImplementedError()
1555
@dbus.service.signal(dbus.OBJECT_MANAGER_IFACE,
1556
signature="oa{sa{sv}}")
1557
def InterfacesAdded(self, object_path, interfaces_and_properties):
1560
@dbus.service.signal(dbus.OBJECT_MANAGER_IFACE, signature="oas")
1561
def InterfacesRemoved(self, object_path, interfaces):
1564
@dbus.service.method(dbus.INTROSPECTABLE_IFACE,
1566
path_keyword='object_path',
1567
connection_keyword='connection')
1568
def Introspect(self, object_path, connection):
1569
"""Overloading of standard D-Bus method.
1571
Override return argument name of GetManagedObjects to be
1572
"objpath_interfaces_and_properties"
1574
xmlstring = DBusObjectWithAnnotations.Introspect(self,
1578
document = xml.dom.minidom.parseString(xmlstring)
1580
for if_tag in document.getElementsByTagName("interface"):
1581
# Fix argument name for the GetManagedObjects method
1582
if (if_tag.getAttribute("name")
1583
== dbus.OBJECT_MANAGER_IFACE):
1584
for cn in if_tag.getElementsByTagName("method"):
1585
if (cn.getAttribute("name")
1586
== "GetManagedObjects"):
1587
for arg in cn.getElementsByTagName("arg"):
1588
if (arg.getAttribute("direction")
1592
"objpath_interfaces"
1594
xmlstring = document.toxml("utf-8")
1596
except (AttributeError, xml.dom.DOMException,
1597
xml.parsers.expat.ExpatError) as error:
1598
logger.error("Failed to override Introspection method",
1603
def datetime_to_dbus(dt, variant_level=0):
893
def datetime_to_dbus (dt, variant_level=0):
1604
894
"""Convert a UTC datetime.datetime() to a D-Bus type."""
1606
return dbus.String("", variant_level=variant_level)
1607
return dbus.String(dt.isoformat(), variant_level=variant_level)
1610
def alternate_dbus_interfaces(alt_interface_names, deprecate=True):
1611
"""A class decorator; applied to a subclass of
1612
dbus.service.Object, it will add alternate D-Bus attributes with
1613
interface names according to the "alt_interface_names" mapping.
1616
@alternate_dbus_interfaces({"org.example.Interface":
1617
"net.example.AlternateInterface"})
1618
class SampleDBusObject(dbus.service.Object):
1619
@dbus.service.method("org.example.Interface")
1620
def SampleDBusMethod():
1623
The above "SampleDBusMethod" on "SampleDBusObject" will be
1624
reachable via two interfaces: "org.example.Interface" and
1625
"net.example.AlternateInterface", the latter of which will have
1626
its D-Bus annotation "org.freedesktop.DBus.Deprecated" set to
1627
"true", unless "deprecate" is passed with a False value.
1629
This works for methods and signals, and also for D-Bus properties
1630
(from DBusObjectWithProperties) and interfaces (from the
1631
dbus_interface_annotations decorator).
896
return dbus.String("", variant_level = variant_level)
897
return dbus.String(dt.isoformat(),
898
variant_level=variant_level)
901
class AlternateDBusNamesMetaclass(DBusObjectWithProperties
903
"""Applied to an empty subclass of a D-Bus object, this metaclass
904
will add additional D-Bus attributes matching a certain pattern.
1635
for orig_interface_name, alt_interface_name in (
1636
alt_interface_names.items()):
1638
interface_names = set()
1639
# Go though all attributes of the class
1640
for attrname, attribute in inspect.getmembers(cls):
906
def __new__(mcs, name, bases, attr):
907
# Go through all the base classes which could have D-Bus
908
# methods, signals, or properties in them
909
for base in (b for b in bases
910
if issubclass(b, dbus.service.Object)):
911
# Go though all attributes of the base class
912
for attrname, attribute in inspect.getmembers(base):
1641
913
# Ignore non-D-Bus attributes, and D-Bus attributes
1642
914
# with the wrong interface name
1643
915
if (not hasattr(attribute, "_dbus_interface")
1644
or not attribute._dbus_interface.startswith(
1645
orig_interface_name)):
916
or not attribute._dbus_interface
917
.startswith("se.recompile.Mandos")):
1647
919
# Create an alternate D-Bus interface name based on
1648
920
# the current name
1649
alt_interface = attribute._dbus_interface.replace(
1650
orig_interface_name, alt_interface_name)
1651
interface_names.add(alt_interface)
921
alt_interface = (attribute._dbus_interface
922
.replace("se.recompile.Mandos",
923
"se.bsnet.fukt.Mandos"))
1652
924
# Is this a D-Bus signal?
1653
925
if getattr(attribute, "_dbus_is_signal", False):
1654
# Extract the original non-method undecorated
1655
# function by black magic
1656
if sys.version_info.major == 2:
1657
nonmethod_func = (dict(
926
# Extract the original non-method function by
928
nonmethod_func = (dict(
1658
929
zip(attribute.func_code.co_freevars,
1659
attribute.__closure__))
1660
["func"].cell_contents)
1662
nonmethod_func = (dict(
1663
zip(attribute.__code__.co_freevars,
1664
attribute.__closure__))
1665
["func"].cell_contents)
930
attribute.__closure__))["func"]
1666
932
# Create a new, but exactly alike, function
1667
933
# object, and decorate it to be a new D-Bus signal
1668
934
# with the alternate D-Bus interface name
1669
new_function = copy_function(nonmethod_func)
1670
new_function = (dbus.service.signal(
1672
attribute._dbus_signature)(new_function))
1673
# Copy annotations, if any
1675
new_function._dbus_annotations = dict(
1676
attribute._dbus_annotations)
1677
except AttributeError:
935
new_function = (dbus.service.signal
937
attribute._dbus_signature)
939
nonmethod_func.func_code,
940
nonmethod_func.func_globals,
941
nonmethod_func.func_name,
942
nonmethod_func.func_defaults,
943
nonmethod_func.func_closure)))
1680
944
# Define a creator of a function to call both the
1681
# original and alternate functions, so both the
1682
# original and alternate signals gets sent when
1683
# the function is called
945
# old and new functions, so both the old and new
946
# signals gets sent when the function is called
1684
947
def fixscope(func1, func2):
1685
948
"""This function is a scope container to pass
1686
949
func1 and func2 to the "call_both" function
1687
950
outside of its arguments"""
1689
@functools.wraps(func2)
1690
951
def call_both(*args, **kwargs):
1691
952
"""This function will emit two D-Bus
1692
953
signals by calling func1 and func2"""
1693
954
func1(*args, **kwargs)
1694
955
func2(*args, **kwargs)
1695
# Make wrapper function look like a D-Bus
1697
for name, attr in inspect.getmembers(func2):
1698
if name.startswith("_dbus_"):
1699
setattr(call_both, name, attr)
1701
956
return call_both
1702
957
# Create the "call_both" function and add it to
1704
attr[attrname] = fixscope(attribute, new_function)
959
attr[attrname] = fixscope(attribute,
1705
961
# Is this a D-Bus method?
1706
962
elif getattr(attribute, "_dbus_is_method", False):
1707
963
# Create a new, but exactly alike, function
1708
964
# object. Decorate it to be a new D-Bus method
1709
965
# with the alternate D-Bus interface name. Add it
1712
dbus.service.method(
1714
attribute._dbus_in_signature,
1715
attribute._dbus_out_signature)
1716
(copy_function(attribute)))
1717
# Copy annotations, if any
1719
attr[attrname]._dbus_annotations = dict(
1720
attribute._dbus_annotations)
1721
except AttributeError:
967
attr[attrname] = (dbus.service.method
969
attribute._dbus_in_signature,
970
attribute._dbus_out_signature)
972
(attribute.func_code,
973
attribute.func_globals,
975
attribute.func_defaults,
976
attribute.func_closure)))
1723
977
# Is this a D-Bus property?
1724
978
elif getattr(attribute, "_dbus_is_property", False):
1725
979
# Create a new, but exactly alike, function
1726
980
# object, and decorate it to be a new D-Bus
1727
981
# property with the alternate D-Bus interface
1728
982
# name. Add it to the class.
1729
attr[attrname] = (dbus_service_property(
1730
alt_interface, attribute._dbus_signature,
1731
attribute._dbus_access,
1732
attribute._dbus_get_args_options
1734
(copy_function(attribute)))
1735
# Copy annotations, if any
1737
attr[attrname]._dbus_annotations = dict(
1738
attribute._dbus_annotations)
1739
except AttributeError:
1741
# Is this a D-Bus interface?
1742
elif getattr(attribute, "_dbus_is_interface", False):
1743
# Create a new, but exactly alike, function
1744
# object. Decorate it to be a new D-Bus interface
1745
# with the alternate D-Bus interface name. Add it
1748
dbus_interface_annotations(alt_interface)
1749
(copy_function(attribute)))
1751
# Deprecate all alternate interfaces
1752
iname = "_AlternateDBusNames_interface_annotation{}"
1753
for interface_name in interface_names:
1755
@dbus_interface_annotations(interface_name)
1757
return {"org.freedesktop.DBus.Deprecated":
1759
# Find an unused name
1760
for aname in (iname.format(i)
1761
for i in itertools.count()):
1762
if aname not in attr:
1766
# Replace the class with a new subclass of it with
1767
# methods, signals, etc. as created above.
1768
if sys.version_info.major == 2:
1769
cls = type(b"{}Alternate".format(cls.__name__),
1772
cls = type("{}Alternate".format(cls.__name__),
1779
@alternate_dbus_interfaces({"se.recompile.Mandos":
1780
"se.bsnet.fukt.Mandos"})
983
attr[attrname] = (dbus_service_property
985
attribute._dbus_signature,
986
attribute._dbus_access,
988
._dbus_get_args_options
991
(attribute.func_code,
992
attribute.func_globals,
994
attribute.func_defaults,
995
attribute.func_closure)))
996
return type.__new__(mcs, name, bases, attr)
1781
999
class ClientDBus(Client, DBusObjectWithProperties):
1782
1000
"""A Client class using D-Bus
1785
1003
dbus_object_path: dbus.ObjectPath
1786
1004
bus: dbus.SystemBus()
1789
1007
runtime_expansions = (Client.runtime_expansions
1790
+ ("dbus_object_path", ))
1792
_interface = "se.recompile.Mandos.Client"
1008
+ ("dbus_object_path",))
1794
1010
# dbus.service.Object doesn't use super(), so we can't either.
1796
def __init__(self, bus=None, *args, **kwargs):
1012
def __init__(self, bus = None, *args, **kwargs):
1798
1014
Client.__init__(self, *args, **kwargs)
1016
self._approvals_pending = 0
1799
1017
# Only now, when this client is initialized, can it show up on
1801
client_object_name = str(self.name).translate(
1019
client_object_name = unicode(self.name).translate(
1802
1020
{ord("."): ord("_"),
1803
1021
ord("-"): ord("_")})
1804
self.dbus_object_path = dbus.ObjectPath(
1805
"/clients/" + client_object_name)
1022
self.dbus_object_path = (dbus.ObjectPath
1023
("/clients/" + client_object_name))
1806
1024
DBusObjectWithProperties.__init__(self, self.bus,
1807
1025
self.dbus_object_path)
1809
def notifychangeproperty(transform_func, dbus_name,
1810
type_func=lambda x: x,
1812
invalidate_only=False,
1813
_interface=_interface):
1027
def notifychangeproperty(transform_func,
1028
dbus_name, type_func=lambda x: x,
1814
1030
""" Modify a variable so that it's a property which announces
1815
1031
its changes to DBus.
1817
1033
transform_fun: Function that takes a value and a variant_level
1818
1034
and transforms it to a D-Bus type.
1819
1035
dbus_name: D-Bus name of the variable
2210
1392
self.start_checker()
2212
1394
self.stop_checker()
2214
1396
# ObjectPath - property
2216
{"org.freedesktop.DBus.Property.EmitsChangedSignal": "const",
2217
"org.freedesktop.DBus.Deprecated": "true"})
2218
1397
@dbus_service_property(_interface, signature="o", access="read")
2219
1398
def ObjectPath_dbus_property(self):
2220
return self.dbus_object_path # is already a dbus.ObjectPath
1399
return self.dbus_object_path # is already a dbus.ObjectPath
2222
1401
# Secret = property
2224
{"org.freedesktop.DBus.Property.EmitsChangedSignal":
2226
@dbus_service_property(_interface,
1402
@dbus_service_property(_interface, signature="ay",
1403
access="write", byte_arrays=True)
2230
1404
def Secret_dbus_property(self, value):
2231
self.secret = bytes(value)
1405
self.secret = str(value)
2237
def __init__(self, child_pipe, key_id, fpr, address):
1410
class ProxyClient(object):
1411
def __init__(self, child_pipe, fpr, address):
2238
1412
self._pipe = child_pipe
2239
self._pipe.send(('init', key_id, fpr, address))
1413
self._pipe.send(('init', fpr, address))
2240
1414
if not self._pipe.recv():
2241
raise KeyError(key_id or fpr)
2243
1417
def __getattribute__(self, name):
1418
if(name == '_pipe'):
2245
1419
return super(ProxyClient, self).__getattribute__(name)
2246
1420
self._pipe.send(('getattr', name))
2247
1421
data = self._pipe.recv()
2248
1422
if data[0] == 'data':
2250
1424
if data[0] == 'function':
2252
1425
def func(*args, **kwargs):
2253
1426
self._pipe.send(('funcall', name, args, kwargs))
2254
1427
return self._pipe.recv()[1]
2258
1430
def __setattr__(self, name, value):
1431
if(name == '_pipe'):
2260
1432
return super(ProxyClient, self).__setattr__(name, value)
2261
1433
self._pipe.send(('setattr', name, value))
1436
class ClientDBusTransitional(ClientDBus):
1437
__metaclass__ = AlternateDBusNamesMetaclass
2264
1440
class ClientHandler(socketserver.BaseRequestHandler, object):
2265
1441
"""A class to handle client connections.
2267
1443
Instantiated once for each connection to handle it.
2268
1444
Note: This will run in its own forked process."""
2270
1446
def handle(self):
2271
1447
with contextlib.closing(self.server.child_pipe) as child_pipe:
2272
1448
logger.info("TCP connection from: %s",
2273
str(self.client_address))
1449
unicode(self.client_address))
2274
1450
logger.debug("Pipe FD: %d",
2275
1451
self.server.child_pipe.fileno())
2277
session = gnutls.ClientSession(self.request)
2279
# priority = ':'.join(("NONE", "+VERS-TLS1.1",
2280
# "+AES-256-CBC", "+SHA1",
2281
# "+COMP-NULL", "+CTYPE-OPENPGP",
1453
session = (gnutls.connection
1454
.ClientSession(self.request,
1456
.X509Credentials()))
1458
# Note: gnutls.connection.X509Credentials is really a
1459
# generic GnuTLS certificate credentials object so long as
1460
# no X.509 keys are added to it. Therefore, we can use it
1461
# here despite using OpenPGP certificates.
1463
#priority = ':'.join(("NONE", "+VERS-TLS1.1",
1464
# "+AES-256-CBC", "+SHA1",
1465
# "+COMP-NULL", "+CTYPE-OPENPGP",
2283
1467
# Use a fallback default, since this MUST be set.
2284
1468
priority = self.server.gnutls_priority
2285
1469
if priority is None:
2286
1470
priority = "NORMAL"
2287
gnutls.priority_set_direct(session._c_object,
2288
priority.encode("utf-8"),
1471
(gnutls.library.functions
1472
.gnutls_priority_set_direct(session._c_object,
2291
1475
# Start communication using the Mandos protocol
2292
1476
# Get protocol number
2293
1477
line = self.request.makefile().readline()
2294
1478
logger.debug("Protocol version: %r", line)
2296
1480
if int(line.strip().split()[0]) > 1:
2297
raise RuntimeError(line)
2298
1482
except (ValueError, IndexError, RuntimeError) as error:
2299
1483
logger.error("Unknown protocol version: %s", error)
2302
1486
# Start GnuTLS connection
2304
1488
session.handshake()
2305
except gnutls.Error as error:
1489
except gnutls.errors.GNUTLSError as error:
2306
1490
logger.warning("Handshake failed: %s", error)
2307
1491
# Do not run session.bye() here: the session is not
2308
1492
# established. Just abandon the request.
2310
1494
logger.debug("Handshake succeeded")
2312
1496
approval_required = False
2314
if gnutls.has_rawpk:
2317
key_id = self.key_id(
2318
self.peer_certificate(session))
2319
except (TypeError, gnutls.Error) as error:
2320
logger.warning("Bad certificate: %s", error)
2322
logger.debug("Key ID: %s", key_id)
2327
fpr = self.fingerprint(
2328
self.peer_certificate(session))
2329
except (TypeError, gnutls.Error) as error:
2330
logger.warning("Bad certificate: %s", error)
2332
logger.debug("Fingerprint: %s", fpr)
2335
client = ProxyClient(child_pipe, key_id, fpr,
1499
fpr = self.fingerprint(self.peer_certificate
1502
gnutls.errors.GNUTLSError) as error:
1503
logger.warning("Bad certificate: %s", error)
1505
logger.debug("Fingerprint: %s", fpr)
1506
if self.server.use_dbus:
1508
client.NewRequest(str(self.client_address))
1511
client = ProxyClient(child_pipe, fpr,
2336
1512
self.client_address)
2337
1513
except KeyError:
2340
1516
if client.approval_delay:
2341
1517
delay = client.approval_delay
2342
1518
client.approvals_pending += 1
2343
1519
approval_required = True
2346
1522
if not client.enabled:
2347
1523
logger.info("Client %s is disabled",
2349
1525
if self.server.use_dbus:
2350
1526
# Emit D-Bus signal
2351
1527
client.Rejected("Disabled")
2354
if client.approved or not client.approval_delay:
2355
# We are approved or approval is disabled
1530
if client._approved or not client.approval_delay:
1531
#We are approved or approval is disabled
2357
elif client.approved is None:
1533
elif client._approved is None:
2358
1534
logger.info("Client %s needs approval",
2360
1536
if self.server.use_dbus:
2361
1537
# Emit D-Bus signal
2362
1538
client.NeedApproval(
2363
client.approval_delay.total_seconds()
2364
* 1000, client.approved_by_default)
1539
client.approval_delay_milliseconds(),
1540
client.approved_by_default)
2366
1542
logger.warning("Client %s was not approved",
3079
2047
use_ipv6 = server_settings["use_ipv6"]
3080
2048
stored_state_path = os.path.join(server_settings["statedir"],
3081
2049
stored_state_file)
3082
foreground = server_settings["foreground"]
3083
zeroconf = server_settings["zeroconf"]
3086
initlogger(debug, logging.DEBUG)
2052
initlogger(logging.DEBUG)
3088
2054
if not debuglevel:
3091
2057
level = getattr(logging, debuglevel.upper())
3092
initlogger(debug, level)
3094
2060
if server_settings["servicename"] != "Mandos":
3095
syslogger.setFormatter(
3096
logging.Formatter('Mandos ({}) [%(process)d]:'
3097
' %(levelname)s: %(message)s'.format(
3098
server_settings["servicename"])))
2061
syslogger.setFormatter(logging.Formatter
2062
('Mandos (%s) [%%(process)d]:'
2063
' %%(levelname)s: %%(message)s'
2064
% server_settings["servicename"]))
3100
2066
# Parse config file with clients
3101
client_config = configparser.ConfigParser(Client.client_defaults)
2067
client_defaults = { "timeout": "5m",
2068
"extended_timeout": "15m",
2070
"checker": "fping -q -- %%(host)s",
2072
"approval_delay": "0s",
2073
"approval_duration": "1s",
2075
client_config = configparser.SafeConfigParser(client_defaults)
3102
2076
client_config.read(os.path.join(server_settings["configdir"],
3103
2077
"clients.conf"))
3105
2079
global mandos_dbus_service
3106
2080
mandos_dbus_service = None
3109
if server_settings["socket"] != "":
3110
socketfd = server_settings["socket"]
3111
tcp_server = MandosServer(
3112
(server_settings["address"], server_settings["port"]),
3114
interface=(server_settings["interface"] or None),
3116
gnutls_priority=server_settings["priority"],
3120
pidfilename = "/run/mandos.pid"
3121
if not os.path.isdir("/run/."):
3122
pidfilename = "/var/run/mandos.pid"
3125
pidfile = codecs.open(pidfilename, "w", encoding="utf-8")
3126
except IOError as e:
3127
logger.error("Could not open file %r", pidfilename,
3130
for name, group in (("_mandos", "_mandos"),
3131
("mandos", "mandos"),
3132
("nobody", "nogroup")):
3134
uid = pwd.getpwnam(name).pw_uid
3135
gid = pwd.getpwnam(group).pw_gid
2082
tcp_server = MandosServer((server_settings["address"],
2083
server_settings["port"]),
2085
interface=(server_settings["interface"]
2089
server_settings["priority"],
2092
pidfilename = "/var/run/mandos.pid"
2094
pidfile = open(pidfilename, "w")
2096
logger.error("Could not open file %r", pidfilename)
2099
uid = pwd.getpwnam("_mandos").pw_uid
2100
gid = pwd.getpwnam("_mandos").pw_gid
2103
uid = pwd.getpwnam("mandos").pw_uid
2104
gid = pwd.getpwnam("mandos").pw_gid
3137
2105
except KeyError:
2107
uid = pwd.getpwnam("nobody").pw_uid
2108
gid = pwd.getpwnam("nobody").pw_gid
3146
logger.debug("Did setuid/setgid to {}:{}".format(uid,
3148
2115
except OSError as error:
3149
logger.warning("Failed to setuid/setgid to {}:{}: {}"
3150
.format(uid, gid, os.strerror(error.errno)))
3151
if error.errno != errno.EPERM:
2116
if error[0] != errno.EPERM:
3155
2120
# Enable all possible GnuTLS debugging
3157
2122
# "Use a log level over 10 to enable all debugging options."
3158
2123
# - GnuTLS manual
3159
gnutls.global_set_log_level(11)
2124
gnutls.library.functions.gnutls_global_set_log_level(11)
2126
@gnutls.library.types.gnutls_log_func
3162
2127
def debug_gnutls(level, string):
3163
2128
logger.debug("GnuTLS: %s", string[:-1])
3165
gnutls.global_set_log_function(debug_gnutls)
2130
(gnutls.library.functions
2131
.gnutls_global_set_log_function(debug_gnutls))
3167
2133
# Redirect stdin so all checkers get /dev/null
3168
null = os.open(os.devnull, os.O_NOCTTY | os.O_RDWR)
2134
null = os.open(os.path.devnull, os.O_NOCTTY | os.O_RDWR)
3169
2135
os.dup2(null, sys.stdin.fileno())
2139
# No console logging
2140
logger.removeHandler(console)
3173
2142
# Need to fork before connecting to D-Bus
3175
2144
# Close all input and output, do double fork, etc.
3178
if gi.version_info < (3, 10, 2):
3179
# multiprocessing will use threads, so before we use GLib we
3180
# need to inform GLib that threads will be used.
3183
2147
global main_loop
3184
2148
# From the Avahi example code
3185
DBusGMainLoop(set_as_default=True)
3186
main_loop = GLib.MainLoop()
2149
DBusGMainLoop(set_as_default=True )
2150
main_loop = gobject.MainLoop()
3187
2151
bus = dbus.SystemBus()
3188
2152
# End of Avahi example code
3191
2155
bus_name = dbus.service.BusName("se.recompile.Mandos",
3194
old_bus_name = dbus.service.BusName(
3195
"se.bsnet.fukt.Mandos", bus,
3197
except dbus.exceptions.DBusException as e:
3198
logger.error("Disabling D-Bus:", exc_info=e)
2156
bus, do_not_queue=True)
2157
old_bus_name = (dbus.service.BusName
2158
("se.bsnet.fukt.Mandos", bus,
2160
except dbus.exceptions.NameExistsException as e:
2161
logger.error(unicode(e) + ", disabling D-Bus")
3199
2162
use_dbus = False
3200
2163
server_settings["use_dbus"] = False
3201
2164
tcp_server.use_dbus = False
3203
protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
3204
service = AvahiServiceToSyslog(
3205
name=server_settings["servicename"],
3206
servicetype="_mandos._tcp",
3209
if server_settings["interface"]:
3210
service.interface = if_nametoindex(
3211
server_settings["interface"].encode("utf-8"))
2165
protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
2166
service = AvahiServiceToSyslog(name =
2167
server_settings["servicename"],
2168
servicetype = "_mandos._tcp",
2169
protocol = protocol, bus = bus)
2170
if server_settings["interface"]:
2171
service.interface = (if_nametoindex
2172
(str(server_settings["interface"])))
3213
2174
global multiprocessing_manager
3214
2175
multiprocessing_manager = multiprocessing.Manager()
3216
2177
client_class = Client
3218
client_class = functools.partial(ClientDBus, bus=bus)
3220
client_settings = Client.config_parser(client_config)
2179
client_class = functools.partial(ClientDBusTransitional,
2182
special_settings = {
2183
# Some settings need to be accessd by special methods;
2184
# booleans need .getboolean(), etc. Here is a list of them:
2185
"approved_by_default":
2187
client_config.getboolean(section, "approved_by_default"),
2190
client_config.getboolean(section, "enabled"),
2192
# Construct a new dict of client settings of this form:
2193
# { client_name: {setting_name: value, ...}, ...}
2194
# with exceptions for any special settings as defined above
2195
client_settings = dict((clientname,
2198
if setting not in special_settings
2199
else special_settings[setting]
2201
for setting, value in
2202
client_config.items(clientname)))
2203
for clientname in client_config.sections())
3221
2205
old_client_settings = {}
3224
# This is used to redirect stdout and stderr for checker processes
3226
wnull = open(os.devnull, "w") # A writable /dev/null
3227
# Only used if server is running in foreground but not in debug
3229
if debug or not foreground:
3232
2208
# Get client data and settings from last running state.
3233
2209
if server_settings["restore"]:
3235
2211
with open(stored_state_path, "rb") as stored_state:
3236
if sys.version_info.major == 2:
3237
clients_data, old_client_settings = pickle.load(
3240
bytes_clients_data, bytes_old_client_settings = (
3241
pickle.load(stored_state, encoding="bytes"))
3242
# Fix bytes to strings
3245
clients_data = {(key.decode("utf-8")
3246
if isinstance(key, bytes)
3249
bytes_clients_data.items()}
3250
del bytes_clients_data
3251
for key in clients_data:
3252
value = {(k.decode("utf-8")
3253
if isinstance(k, bytes) else k): v
3255
clients_data[key].items()}
3256
clients_data[key] = value
3258
value["client_structure"] = [
3260
if isinstance(s, bytes)
3262
value["client_structure"]]
3263
# .name, .host, and .checker_command
3264
for k in ("name", "host", "checker_command"):
3265
if isinstance(value[k], bytes):
3266
value[k] = value[k].decode("utf-8")
3267
if "key_id" not in value:
3268
value["key_id"] = ""
3269
elif "fingerprint" not in value:
3270
value["fingerprint"] = ""
3271
# old_client_settings
3273
old_client_settings = {
3274
(key.decode("utf-8")
3275
if isinstance(key, bytes)
3278
bytes_old_client_settings.items()}
3279
del bytes_old_client_settings
3280
# .host and .checker_command
3281
for value in old_client_settings.values():
3282
for attribute in ("host", "checker_command"):
3283
if isinstance(value[attribute], bytes):
3284
value[attribute] = (value[attribute]
2212
clients_data, old_client_settings = (pickle.load
3286
2214
os.remove(stored_state_path)
3287
2215
except IOError as e:
3288
if e.errno == errno.ENOENT:
3289
logger.warning("Could not load persistent state:"
3290
" {}".format(os.strerror(e.errno)))
3292
logger.critical("Could not load persistent state:",
2216
logger.warning("Could not load persistent state: {0}"
2218
if e.errno != errno.ENOENT:
3295
except EOFError as e:
3296
logger.warning("Could not load persistent state: "
3300
2221
with PGPEngine() as pgp:
3301
for client_name, client in clients_data.items():
3302
# Skip removed clients
3303
if client_name not in client_settings:
2222
for client in clients_data:
2223
client_name = client["name"]
3306
2225
# Decide which value to use after restoring saved state.
3307
2226
# We have three different values: Old config file,
3308
2227
# new config file, and saved state.
3313
2232
# For each value in new config, check if it
3314
2233
# differs from the old config value (Except for
3315
2234
# the "secret" attribute)
3316
if (name != "secret"
3318
old_client_settings[client_name][name])):
3319
client[name] = value
2235
if (name != "secret" and
2236
value != old_client_settings[client_name]
2238
setattr(client, name, value)
3320
2239
except KeyError:
3323
2242
# Clients who has passed its expire date can still be
3324
# enabled if its last checker was successful. A Client
3325
# whose checker succeeded before we stored its state is
3326
# assumed to have successfully run all checkers during
3328
if client["enabled"]:
3329
if datetime.datetime.utcnow() >= client["expires"]:
3330
if not client["last_checked_ok"]:
3332
"disabling client {} - Client never "
3333
"performed a successful checker".format(
3335
client["enabled"] = False
3336
elif client["last_checker_status"] != 0:
3338
"disabling client {} - Client last"
3339
" checker failed with error code"
3342
client["last_checker_status"]))
2243
# enabled if its last checker was sucessful. Clients
2244
# whose checker failed before we stored its state is
2245
# assumed to have failed all checkers during downtime.
2246
if client["enabled"] and client["last_checked_ok"]:
2247
if ((datetime.datetime.utcnow()
2248
- client["last_checked_ok"])
2249
> client["interval"]):
2250
if client["last_checker_status"] != 0:
3343
2251
client["enabled"] = False
3345
client["expires"] = (
3346
datetime.datetime.utcnow()
3347
+ client["timeout"])
3348
logger.debug("Last checker succeeded,"
3349
" keeping {} enabled".format(
2253
client["expires"] = (datetime.datetime
2255
+ client["timeout"])
2257
client["changedstate"] = (multiprocessing_manager
2259
(multiprocessing_manager
2262
new_client = (ClientDBusTransitional.__new__
2263
(ClientDBusTransitional))
2264
tcp_server.clients[client_name] = new_client
2265
new_client.bus = bus
2266
for name, value in client.iteritems():
2267
setattr(new_client, name, value)
2268
client_object_name = unicode(client_name).translate(
2269
{ord("."): ord("_"),
2270
ord("-"): ord("_")})
2271
new_client.dbus_object_path = (dbus.ObjectPath
2273
+ client_object_name))
2274
DBusObjectWithProperties.__init__(new_client,
2279
tcp_server.clients[client_name] = (Client.__new__
2281
for name, value in client.iteritems():
2282
setattr(tcp_server.clients[client_name],
3352
client["secret"] = pgp.decrypt(
3353
client["encrypted_secret"],
3354
client_settings[client_name]["secret"])
2286
tcp_server.clients[client_name].secret = (
2287
pgp.decrypt(tcp_server.clients[client_name]
2289
client_settings[client_name]
3355
2291
except PGPError:
3356
2292
# If decryption fails, we use secret from new settings
3357
logger.debug("Failed to decrypt {} old secret".format(
3359
client["secret"] = (client_settings[client_name]
3362
# Add/remove clients based on new changes made to config
3363
for client_name in (set(old_client_settings)
3364
- set(client_settings)):
3365
del clients_data[client_name]
3366
for client_name in (set(client_settings)
3367
- set(old_client_settings)):
3368
clients_data[client_name] = client_settings[client_name]
3370
# Create all client objects
3371
for client_name, client in clients_data.items():
3372
tcp_server.clients[client_name] = client_class(
3375
server_settings=server_settings)
2293
tcp_server.clients[client_name].secret = (
2294
client_settings[client_name]["secret"])
2296
# Create/remove clients based on new changes made to config
2297
for clientname in set(old_client_settings) - set(client_settings):
2298
del tcp_server.clients[clientname]
2299
for clientname in set(client_settings) - set(old_client_settings):
2300
tcp_server.clients[clientname] = (client_class(name
3377
2306
if not tcp_server.clients:
3378
2307
logger.warning("No clients defined")
3381
if pidfile is not None:
3385
print(pid, file=pidfile)
3387
logger.error("Could not write to file %r with PID %d",
2313
pidfile.write(str(pid) + "\n".encode("utf-8"))
2316
logger.error("Could not write to file %r with PID %d",
2319
# "pidfile" was never created
3390
2321
del pidfilename
3392
for termsig in (signal.SIGHUP, signal.SIGTERM):
3393
GLib.unix_signal_add(GLib.PRIORITY_HIGH, termsig,
3394
lambda: main_loop.quit() and False)
2323
signal.signal(signal.SIGINT, signal.SIG_IGN)
2325
signal.signal(signal.SIGHUP, lambda signum, frame: sys.exit())
2326
signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit())
3398
@alternate_dbus_interfaces(
3399
{"se.recompile.Mandos": "se.bsnet.fukt.Mandos"})
3400
class MandosDBusService(DBusObjectWithObjectManager):
2329
class MandosDBusService(dbus.service.Object):
3401
2330
"""A D-Bus proxy object"""
3403
2331
def __init__(self):
3404
2332
dbus.service.Object.__init__(self, bus, "/")
3406
2333
_interface = "se.recompile.Mandos"
3408
2335
@dbus.service.signal(_interface, signature="o")
3409
2336
def ClientAdded(self, objpath):
3413
2340
@dbus.service.signal(_interface, signature="ss")
3414
def ClientNotFound(self, key_id, address):
2341
def ClientNotFound(self, fingerprint, address):
3418
@dbus_annotations({"org.freedesktop.DBus.Deprecated":
3420
2345
@dbus.service.signal(_interface, signature="os")
3421
2346
def ClientRemoved(self, objpath, name):
3425
@dbus_annotations({"org.freedesktop.DBus.Deprecated":
3427
2350
@dbus.service.method(_interface, out_signature="ao")
3428
2351
def GetAllClients(self):
3430
return dbus.Array(c.dbus_object_path for c in
3431
tcp_server.clients.values())
3433
@dbus_annotations({"org.freedesktop.DBus.Deprecated":
2353
return dbus.Array(c.dbus_object_path
2355
tcp_server.clients.itervalues())
3435
2357
@dbus.service.method(_interface,
3436
2358
out_signature="a{oa{sv}}")
3437
2359
def GetAllClientsWithProperties(self):
3439
2361
return dbus.Dictionary(
3440
{c.dbus_object_path: c.GetAll(
3441
"se.recompile.Mandos.Client")
3442
for c in tcp_server.clients.values()},
2362
((c.dbus_object_path, c.GetAll(""))
2363
for c in tcp_server.clients.itervalues()),
3443
2364
signature="oa{sv}")
3445
2366
@dbus.service.method(_interface, in_signature="o")
3446
2367
def RemoveClient(self, object_path):
3448
for c in tcp_server.clients.values():
2369
for c in tcp_server.clients.itervalues():
3449
2370
if c.dbus_object_path == object_path:
3450
2371
del tcp_server.clients[c.name]
3451
2372
c.remove_from_connection()
3452
# Don't signal the disabling
2373
# Don't signal anything except ClientRemoved
3453
2374
c.disable(quiet=True)
3454
# Emit D-Bus signal for removal
3455
self.client_removed_signal(c)
2376
self.ClientRemoved(object_path, c.name)
3457
2378
raise KeyError(object_path)
3461
@dbus.service.method(dbus.OBJECT_MANAGER_IFACE,
3462
out_signature="a{oa{sa{sv}}}")
3463
def GetManagedObjects(self):
3465
return dbus.Dictionary(
3466
{client.dbus_object_path:
3468
{interface: client.GetAll(interface)
3470
client._get_all_interface_names()})
3471
for client in tcp_server.clients.values()})
3473
def client_added_signal(self, client):
3474
"""Send the new standard signal and the old signal"""
3476
# New standard signal
3477
self.InterfacesAdded(
3478
client.dbus_object_path,
3480
{interface: client.GetAll(interface)
3482
client._get_all_interface_names()}))
3484
self.ClientAdded(client.dbus_object_path)
3486
def client_removed_signal(self, client):
3487
"""Send the new standard signal and the old signal"""
3489
# New standard signal
3490
self.InterfacesRemoved(
3491
client.dbus_object_path,
3492
client._get_all_interface_names())
3494
self.ClientRemoved(client.dbus_object_path,
3497
mandos_dbus_service = MandosDBusService()
3499
# Save modules to variables to exempt the modules from being
3500
# unloaded before the function registered with atexit() is run.
3501
mp = multiprocessing
2382
class MandosDBusServiceTransitional(MandosDBusService):
2383
__metaclass__ = AlternateDBusNamesMetaclass
2384
mandos_dbus_service = MandosDBusServiceTransitional()
3505
2387
"Cleanup function; run on exit"
3509
mp.active_children()
2390
multiprocessing.active_children()
3511
2391
if not (tcp_server.clients or client_settings):
3514
2394
# Store client before exiting. Secrets are encrypted with key
3515
2395
# based on what config file has. If config file is
3516
2396
# removed/edited, old secret will thus be unrecovable.
3518
2398
with PGPEngine() as pgp:
3519
for client in tcp_server.clients.values():
2399
for client in tcp_server.clients.itervalues():
3520
2400
key = client_settings[client.name]["secret"]
3521
2401
client.encrypted_secret = pgp.encrypt(client.secret,
3523
2403
client_dict = {}
3525
# A list of attributes that can not be pickled
3527
exclude = {"bus", "changedstate", "secret",
3528
"checker", "server_settings"}
3529
for name, typ in inspect.getmembers(dbus.service
2405
# A list of attributes that will not be stored when
2407
exclude = set(("bus", "changedstate", "secret"))
2408
for name, typ in (inspect.getmembers
2409
(dbus.service.Object)):
3531
2410
exclude.add(name)
3533
2412
client_dict["encrypted_secret"] = (client
3534
2413
.encrypted_secret)
3535
2414
for attr in client.client_structure:
3536
2415
if attr not in exclude:
3537
2416
client_dict[attr] = getattr(client, attr)
3539
clients[client.name] = client_dict
2418
clients.append(client_dict)
3540
2419
del client_settings[client.name]["secret"]
3543
with tempfile.NamedTemporaryFile(
3547
dir=os.path.dirname(stored_state_path),
3548
delete=False) as stored_state:
3549
pickle.dump((clients, client_settings), stored_state,
3551
tempname = stored_state.name
3552
os.rename(tempname, stored_state_path)
2422
with os.fdopen(os.open(stored_state_path,
2423
os.O_CREAT|os.O_WRONLY|os.O_TRUNC,
2424
0600), "wb") as stored_state:
2425
pickle.dump((clients, client_settings), stored_state)
3553
2426
except (IOError, OSError) as e:
3559
if e.errno in (errno.ENOENT, errno.EACCES, errno.EEXIST):
3560
logger.warning("Could not save persistent state: {}"
3561
.format(os.strerror(e.errno)))
3563
logger.warning("Could not save persistent state:",
2427
logger.warning("Could not save persistent state: {0}"
2429
if e.errno not in (errno.ENOENT, errno.EACCES):
3567
2432
# Delete all clients, and settings from config
3568
2433
while tcp_server.clients:
3569
2434
name, client = tcp_server.clients.popitem()
3571
2436
client.remove_from_connection()
3572
# Don't signal the disabling
2437
# Don't signal anything except ClientRemoved
3573
2438
client.disable(quiet=True)
3574
# Emit D-Bus signal for removal
3576
mandos_dbus_service.client_removed_signal(client)
2441
mandos_dbus_service.ClientRemoved(client
3577
2444
client_settings.clear()
3579
2446
atexit.register(cleanup)
3581
for client in tcp_server.clients.values():
2448
for client in tcp_server.clients.itervalues():
3583
# Emit D-Bus signal for adding
3584
mandos_dbus_service.client_added_signal(client)
2451
mandos_dbus_service.ClientAdded(client.dbus_object_path)
3585
2452
# Need to initiate checking of clients
3586
2453
if client.enabled:
3587
2454
client.init_checker()
3589
2456
tcp_server.enable()
3590
2457
tcp_server.server_activate()
3592
2459
# Find out what port we got
3594
service.port = tcp_server.socket.getsockname()[1]
2460
service.port = tcp_server.socket.getsockname()[1]
3596
2462
logger.info("Now listening on address %r, port %d,"
3597
" flowinfo %d, scope_id %d",
3598
*tcp_server.socket.getsockname())
2463
" flowinfo %d, scope_id %d"
2464
% tcp_server.socket.getsockname())
3600
logger.info("Now listening on address %r, port %d",
3601
*tcp_server.socket.getsockname())
3603
# service.interface = tcp_server.socket.getsockname()[3]
2466
logger.info("Now listening on address %r, port %d"
2467
% tcp_server.socket.getsockname())
2469
#service.interface = tcp_server.socket.getsockname()[3]
3607
# From the Avahi example code
3610
except dbus.exceptions.DBusException as error:
3611
logger.critical("D-Bus Exception", exc_info=error)
3614
# End of Avahi example code
3617
GLib.IOChannel.unix_new(tcp_server.fileno()),
3618
GLib.PRIORITY_DEFAULT, GLib.IO_IN,
3619
lambda *args, **kwargs: (tcp_server.handle_request
3620
(*args[2:], **kwargs) or True))
2472
# From the Avahi example code
2475
except dbus.exceptions.DBusException as error:
2476
logger.critical("DBusException: %s", error)
2479
# End of Avahi example code
2481
gobject.io_add_watch(tcp_server.fileno(), gobject.IO_IN,
2482
lambda *args, **kwargs:
2483
(tcp_server.handle_request
2484
(*args[2:], **kwargs) or True))
3622
2486
logger.debug("Starting main loop")
3623
2487
main_loop.run()
3624
2488
except AvahiError as error:
3625
logger.critical("Avahi Error", exc_info=error)
2489
logger.critical("AvahiError: %s", error)
3628
2492
except KeyboardInterrupt: