431
448
return now < (self.created + self.timeout)
433
450
return now < (self.last_checked_ok + self.timeout)
436
class ClientDBus(Client, dbus.service.Object):
437
"""A Client class using D-Bus
440
dbus_object_path: dbus.ObjectPath ; only set if self.use_dbus
442
# dbus.service.Object doesn't use super(), so we can't either.
444
def __init__(self, *args, **kwargs):
445
Client.__init__(self, *args, **kwargs)
446
# Only now, when this client is initialized, can it show up on
448
self.dbus_object_path = (dbus.ObjectPath
450
+ self.name.replace(".", "_")))
451
dbus.service.Object.__init__(self, bus,
452
self.dbus_object_path)
454
oldstate = getattr(self, "enabled", False)
455
r = Client.enable(self)
456
if oldstate != self.enabled:
458
self.PropertyChanged(dbus.String(u"enabled"),
459
dbus.Boolean(True, variant_level=1))
460
self.PropertyChanged(dbus.String(u"last_enabled"),
461
(_datetime_to_dbus(self.last_enabled,
465
def disable(self, signal = True):
466
oldstate = getattr(self, "enabled", False)
467
r = Client.disable(self)
468
if signal and oldstate != self.enabled:
470
self.PropertyChanged(dbus.String(u"enabled"),
471
dbus.Boolean(False, variant_level=1))
474
def __del__(self, *args, **kwargs):
476
self.remove_from_connection()
479
if hasattr(dbus.service.Object, "__del__"):
480
dbus.service.Object.__del__(self, *args, **kwargs)
481
Client.__del__(self, *args, **kwargs)
483
def checker_callback(self, pid, condition, command,
485
self.checker_callback_tag = None
488
self.PropertyChanged(dbus.String(u"checker_running"),
489
dbus.Boolean(False, variant_level=1))
490
if os.WIFEXITED(condition):
491
exitstatus = os.WEXITSTATUS(condition)
493
self.CheckerCompleted(dbus.Int16(exitstatus),
494
dbus.Int64(condition),
495
dbus.String(command))
498
self.CheckerCompleted(dbus.Int16(-1),
499
dbus.Int64(condition),
500
dbus.String(command))
502
return Client.checker_callback(self, pid, condition, command,
505
def checked_ok(self, *args, **kwargs):
506
r = Client.checked_ok(self, *args, **kwargs)
508
self.PropertyChanged(
509
dbus.String(u"last_checked_ok"),
510
(_datetime_to_dbus(self.last_checked_ok,
514
def start_checker(self, *args, **kwargs):
515
old_checker = self.checker
516
if self.checker is not None:
517
old_checker_pid = self.checker.pid
519
old_checker_pid = None
520
r = Client.start_checker(self, *args, **kwargs)
521
# Only if new checker process was started
522
if (self.checker is not None
523
and old_checker_pid != self.checker.pid):
525
self.CheckerStarted(self.current_checker_command)
526
self.PropertyChanged(
527
dbus.String("checker_running"),
528
dbus.Boolean(True, variant_level=1))
531
def stop_checker(self, *args, **kwargs):
532
old_checker = getattr(self, "checker", None)
533
r = Client.stop_checker(self, *args, **kwargs)
534
if (old_checker is not None
535
and getattr(self, "checker", None) is None):
536
self.PropertyChanged(dbus.String(u"checker_running"),
537
dbus.Boolean(False, variant_level=1))
540
452
## D-Bus methods & signals
541
453
_interface = u"se.bsnet.fukt.Mandos.Client"
691
class ClientHandler(SocketServer.BaseRequestHandler, object):
692
"""A class to handle client connections.
694
Instantiated once for each connection to handle it.
591
def peer_certificate(session):
592
"Return the peer's OpenPGP certificate as a bytestring"
593
# If not an OpenPGP certificate...
594
if (gnutls.library.functions
595
.gnutls_certificate_type_get(session._c_object)
596
!= gnutls.library.constants.GNUTLS_CRT_OPENPGP):
597
# ...do the normal thing
598
return session.peer_certificate
599
list_size = ctypes.c_uint(1)
600
cert_list = (gnutls.library.functions
601
.gnutls_certificate_get_peers
602
(session._c_object, ctypes.byref(list_size)))
603
if not bool(cert_list) and list_size.value != 0:
604
raise gnutls.errors.GNUTLSError("error getting peer"
606
if list_size.value == 0:
609
return ctypes.string_at(cert.data, cert.size)
612
def fingerprint(openpgp):
613
"Convert an OpenPGP bytestring to a hexdigit fingerprint string"
614
# New GnuTLS "datum" with the OpenPGP public key
615
datum = (gnutls.library.types
616
.gnutls_datum_t(ctypes.cast(ctypes.c_char_p(openpgp),
619
ctypes.c_uint(len(openpgp))))
620
# New empty GnuTLS certificate
621
crt = gnutls.library.types.gnutls_openpgp_crt_t()
622
(gnutls.library.functions
623
.gnutls_openpgp_crt_init(ctypes.byref(crt)))
624
# Import the OpenPGP public key into the certificate
625
(gnutls.library.functions
626
.gnutls_openpgp_crt_import(crt, ctypes.byref(datum),
627
gnutls.library.constants
628
.GNUTLS_OPENPGP_FMT_RAW))
629
# Verify the self signature in the key
630
crtverify = ctypes.c_uint()
631
(gnutls.library.functions
632
.gnutls_openpgp_crt_verify_self(crt, 0, ctypes.byref(crtverify)))
633
if crtverify.value != 0:
634
gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
635
raise gnutls.errors.CertificateSecurityError("Verify failed")
636
# New buffer for the fingerprint
637
buf = ctypes.create_string_buffer(20)
638
buf_len = ctypes.c_size_t()
639
# Get the fingerprint from the certificate into the buffer
640
(gnutls.library.functions
641
.gnutls_openpgp_crt_get_fingerprint(crt, ctypes.byref(buf),
642
ctypes.byref(buf_len)))
643
# Deinit the certificate
644
gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
645
# Convert the buffer to a Python bytestring
646
fpr = ctypes.string_at(buf, buf_len.value)
647
# Convert the bytestring to hexadecimal notation
648
hex_fpr = u''.join(u"%02X" % ord(char) for char in fpr)
652
class TCP_handler(SocketServer.BaseRequestHandler, object):
653
"""A TCP request handler class.
654
Instantiated by IPv6_TCPServer for each request to handle it.
695
655
Note: This will run in its own forked process."""
697
657
def handle(self):
698
658
logger.info(u"TCP connection from: %s",
699
659
unicode(self.client_address))
700
logger.debug(u"IPC Pipe FD: %d", self.server.pipe[1])
701
# Open IPC pipe to parent process
702
with closing(os.fdopen(self.server.pipe[1], "w", 1)) as ipc:
703
session = (gnutls.connection
704
.ClientSession(self.request,
708
line = self.request.makefile().readline()
709
logger.debug(u"Protocol version: %r", line)
711
if int(line.strip().split()[0]) > 1:
713
except (ValueError, IndexError, RuntimeError), error:
714
logger.error(u"Unknown protocol version: %s", error)
717
# Note: gnutls.connection.X509Credentials is really a
718
# generic GnuTLS certificate credentials object so long as
719
# no X.509 keys are added to it. Therefore, we can use it
720
# here despite using OpenPGP certificates.
722
#priority = ':'.join(("NONE", "+VERS-TLS1.1",
723
# "+AES-256-CBC", "+SHA1",
724
# "+COMP-NULL", "+CTYPE-OPENPGP",
726
# Use a fallback default, since this MUST be set.
727
priority = self.server.gnutls_priority
730
(gnutls.library.functions
731
.gnutls_priority_set_direct(session._c_object,
736
except gnutls.errors.GNUTLSError, error:
737
logger.warning(u"Handshake failed: %s", error)
738
# Do not run session.bye() here: the session is not
739
# established. Just abandon the request.
741
logger.debug(u"Handshake succeeded")
743
fpr = self.fingerprint(self.peer_certificate(session))
744
except (TypeError, gnutls.errors.GNUTLSError), error:
745
logger.warning(u"Bad certificate: %s", error)
748
logger.debug(u"Fingerprint: %s", fpr)
750
for c in self.server.clients:
751
if c.fingerprint == fpr:
755
ipc.write("NOTFOUND %s\n" % fpr)
758
# Have to check if client.still_valid(), since it is
759
# possible that the client timed out while establishing
760
# the GnuTLS session.
761
if not client.still_valid():
762
ipc.write("INVALID %s\n" % client.name)
765
ipc.write("SENDING %s\n" % client.name)
767
while sent_size < len(client.secret):
768
sent = session.send(client.secret[sent_size:])
769
logger.debug(u"Sent: %d, remaining: %d",
770
sent, len(client.secret)
771
- (sent_size + sent))
776
def peer_certificate(session):
777
"Return the peer's OpenPGP certificate as a bytestring"
778
# If not an OpenPGP certificate...
779
if (gnutls.library.functions
780
.gnutls_certificate_type_get(session._c_object)
781
!= gnutls.library.constants.GNUTLS_CRT_OPENPGP):
782
# ...do the normal thing
783
return session.peer_certificate
784
list_size = ctypes.c_uint(1)
785
cert_list = (gnutls.library.functions
786
.gnutls_certificate_get_peers
787
(session._c_object, ctypes.byref(list_size)))
788
if not bool(cert_list) and list_size.value != 0:
789
raise gnutls.errors.GNUTLSError("error getting peer"
791
if list_size.value == 0:
794
return ctypes.string_at(cert.data, cert.size)
797
def fingerprint(openpgp):
798
"Convert an OpenPGP bytestring to a hexdigit fingerprint"
799
# New GnuTLS "datum" with the OpenPGP public key
800
datum = (gnutls.library.types
801
.gnutls_datum_t(ctypes.cast(ctypes.c_char_p(openpgp),
804
ctypes.c_uint(len(openpgp))))
805
# New empty GnuTLS certificate
806
crt = gnutls.library.types.gnutls_openpgp_crt_t()
807
(gnutls.library.functions
808
.gnutls_openpgp_crt_init(ctypes.byref(crt)))
809
# Import the OpenPGP public key into the certificate
810
(gnutls.library.functions
811
.gnutls_openpgp_crt_import(crt, ctypes.byref(datum),
812
gnutls.library.constants
813
.GNUTLS_OPENPGP_FMT_RAW))
814
# Verify the self signature in the key
815
crtverify = ctypes.c_uint()
816
(gnutls.library.functions
817
.gnutls_openpgp_crt_verify_self(crt, 0,
818
ctypes.byref(crtverify)))
819
if crtverify.value != 0:
820
gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
821
raise (gnutls.errors.CertificateSecurityError
823
# New buffer for the fingerprint
824
buf = ctypes.create_string_buffer(20)
825
buf_len = ctypes.c_size_t()
826
# Get the fingerprint from the certificate into the buffer
827
(gnutls.library.functions
828
.gnutls_openpgp_crt_get_fingerprint(crt, ctypes.byref(buf),
829
ctypes.byref(buf_len)))
830
# Deinit the certificate
831
gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
832
# Convert the buffer to a Python bytestring
833
fpr = ctypes.string_at(buf, buf_len.value)
834
# Convert the bytestring to hexadecimal notation
835
hex_fpr = u''.join(u"%02X" % ord(char) for char in fpr)
839
class ForkingMixInWithPipe(SocketServer.ForkingMixIn, object):
840
"""Like SocketServer.ForkingMixIn, but also pass a pipe.
842
Assumes a gobject.MainLoop event loop.
844
def process_request(self, request, client_address):
845
"""Overrides and wraps the original process_request().
847
This function creates a new pipe in self.pipe
849
self.pipe = os.pipe()
850
super(ForkingMixInWithPipe,
851
self).process_request(request, client_address)
852
os.close(self.pipe[1]) # close write end
853
# Call "handle_ipc" for both data and EOF events
854
gobject.io_add_watch(self.pipe[0],
855
gobject.IO_IN | gobject.IO_HUP,
857
def handle_ipc(source, condition):
858
"""Dummy function; override as necessary"""
863
class IPv6_TCPServer(ForkingMixInWithPipe,
660
session = (gnutls.connection
661
.ClientSession(self.request,
665
line = self.request.makefile().readline()
666
logger.debug(u"Protocol version: %r", line)
668
if int(line.strip().split()[0]) > 1:
670
except (ValueError, IndexError, RuntimeError), error:
671
logger.error(u"Unknown protocol version: %s", error)
674
# Note: gnutls.connection.X509Credentials is really a generic
675
# GnuTLS certificate credentials object so long as no X.509
676
# keys are added to it. Therefore, we can use it here despite
677
# using OpenPGP certificates.
679
#priority = ':'.join(("NONE", "+VERS-TLS1.1", "+AES-256-CBC",
680
# "+SHA1", "+COMP-NULL", "+CTYPE-OPENPGP",
682
# Use a fallback default, since this MUST be set.
683
priority = self.server.settings.get("priority", "NORMAL")
684
(gnutls.library.functions
685
.gnutls_priority_set_direct(session._c_object,
690
except gnutls.errors.GNUTLSError, error:
691
logger.warning(u"Handshake failed: %s", error)
692
# Do not run session.bye() here: the session is not
693
# established. Just abandon the request.
695
logger.debug(u"Handshake succeeded")
697
fpr = fingerprint(peer_certificate(session))
698
except (TypeError, gnutls.errors.GNUTLSError), error:
699
logger.warning(u"Bad certificate: %s", error)
702
logger.debug(u"Fingerprint: %s", fpr)
704
for c in self.server.clients:
705
if c.fingerprint == fpr:
709
logger.warning(u"Client not found for fingerprint: %s",
713
# Have to check if client.still_valid(), since it is possible
714
# that the client timed out while establishing the GnuTLS
716
if not client.still_valid():
717
logger.warning(u"Client %(name)s is invalid",
721
## This won't work here, since we're in a fork.
722
# client.checked_ok()
724
while sent_size < len(client.secret):
725
sent = session.send(client.secret[sent_size:])
726
logger.debug(u"Sent: %d, remaining: %d",
727
sent, len(client.secret)
728
- (sent_size + sent))
733
class IPv6_TCPServer(SocketServer.ForkingMixIn,
864
734
SocketServer.TCPServer, object):
865
"""IPv6-capable TCP server. Accepts 'None' as address and/or port
735
"""IPv6 TCP server. Accepts 'None' as address and/or port.
737
settings: Server settings
738
clients: Set() of Client objects
868
739
enabled: Boolean; whether this server is activated yet
869
interface: None or a network interface name (string)
870
use_ipv6: Boolean; to use IPv6 or not
872
clients: Set() of Client objects
873
gnutls_priority GnuTLS priority string
874
use_dbus: Boolean; to emit D-Bus signals or not
876
def __init__(self, server_address, RequestHandlerClass,
877
interface=None, use_ipv6=True, clients=None,
878
gnutls_priority=None, use_dbus=True):
741
address_family = socket.AF_INET6
742
def __init__(self, *args, **kwargs):
743
if "settings" in kwargs:
744
self.settings = kwargs["settings"]
745
del kwargs["settings"]
746
if "clients" in kwargs:
747
self.clients = kwargs["clients"]
748
del kwargs["clients"]
879
749
self.enabled = False
880
self.interface = interface
882
self.address_family = socket.AF_INET6
883
self.clients = clients
884
self.use_dbus = use_dbus
885
self.gnutls_priority = gnutls_priority
886
SocketServer.TCPServer.__init__(self, server_address,
750
super(IPv6_TCPServer, self).__init__(*args, **kwargs)
888
751
def server_bind(self):
889
752
"""This overrides the normal server_bind() function
890
753
to bind to an interface if one was specified, and also NOT to
891
754
bind to an address or port if they were not specified."""
892
if self.interface is not None:
755
if self.settings["interface"]:
756
# 25 is from /usr/include/asm-i486/socket.h
757
SO_BINDTODEVICE = getattr(socket, "SO_BINDTODEVICE", 25)
894
759
self.socket.setsockopt(socket.SOL_SOCKET,
896
self.interface + '\0')
761
self.settings["interface"])
897
762
except socket.error, error:
898
763
if error[0] == errno.EPERM:
899
764
logger.error(u"No permission to"
900
765
u" bind to interface %s",
766
self.settings["interface"])
904
769
# Only bind(2) the socket if we really need to.
905
770
if self.server_address[0] or self.server_address[1]:
906
771
if not self.server_address[0]:
907
if self.address_family == socket.AF_INET6:
908
any_address = "::" # in6addr_any
910
any_address = socket.INADDR_ANY
911
self.server_address = (any_address,
773
self.server_address = (in6addr_any,
912
774
self.server_address[1])
913
775
elif not self.server_address[1]:
914
776
self.server_address = (self.server_address[0],
778
# if self.settings["interface"]:
917
779
# self.server_address = (self.server_address[0],
922
return SocketServer.TCPServer.server_bind(self)
785
return super(IPv6_TCPServer, self).server_bind()
923
786
def server_activate(self):
925
return SocketServer.TCPServer.server_activate(self)
788
return super(IPv6_TCPServer, self).server_activate()
926
789
def enable(self):
927
790
self.enabled = True
928
def handle_ipc(self, source, condition, file_objects={}):
930
gobject.IO_IN: "IN", # There is data to read.
931
gobject.IO_OUT: "OUT", # Data can be written (without
933
gobject.IO_PRI: "PRI", # There is urgent data to read.
934
gobject.IO_ERR: "ERR", # Error condition.
935
gobject.IO_HUP: "HUP" # Hung up (the connection has been
936
# broken, usually for pipes and
939
conditions_string = ' | '.join(name
941
condition_names.iteritems()
943
logger.debug("Handling IPC: FD = %d, condition = %s", source,
946
# Turn the pipe file descriptor into a Python file object
947
if source not in file_objects:
948
file_objects[source] = os.fdopen(source, "r", 1)
950
# Read a line from the file object
951
cmdline = file_objects[source].readline()
952
if not cmdline: # Empty line means end of file
954
file_objects[source].close()
955
del file_objects[source]
957
# Stop calling this function
960
logger.debug("IPC command: %r", cmdline)
962
# Parse and act on command
963
cmd, args = cmdline.rstrip("\r\n").split(None, 1)
965
if cmd == "NOTFOUND":
966
logger.warning(u"Client not found for fingerprint: %s",
970
mandos_dbus_service.ClientNotFound(args)
971
elif cmd == "INVALID":
972
for client in self.clients:
973
if client.name == args:
974
logger.warning(u"Client %s is invalid", args)
980
logger.error(u"Unknown client %s is invalid", args)
981
elif cmd == "SENDING":
982
for client in self.clients:
983
if client.name == args:
984
logger.info(u"Sending secret to %s", client.name)
988
client.ReceivedSecret()
991
logger.error(u"Sending secret to unknown client %s",
994
logger.error("Unknown IPC command: %r", cmdline)
996
# Keep calling this function
1000
793
def string_to_delta(interval):