434
524
class AvahiServiceToSyslog(AvahiService):
435
525
def rename(self, *args, **kwargs):
436
526
"""Add the new name to the syslog messages"""
437
ret = AvahiService.rename(self, *args, **kwargs)
527
ret = super(AvahiServiceToSyslog, self).rename(*args,
438
529
syslogger.setFormatter(logging.Formatter(
439
530
'Mandos ({}) [%(process)d]: %(levelname)s: %(message)s'
440
531
.format(self.name)))
443
535
# Pretend that we have a GnuTLS module
444
class GnuTLS(object):
445
"""This isn't so much a class as it is a module-like namespace.
446
It is instantiated once, and simulates having a GnuTLS module."""
448
_library = ctypes.cdll.LoadLibrary(
449
ctypes.util.find_library("gnutls"))
450
_need_version = "3.3.0"
452
# Need to use class name "GnuTLS" here, since this method is
453
# called before the assignment to the "gnutls" global variable
455
if GnuTLS.check_version(self._need_version) is None:
456
raise GnuTLS.Error("Needs GnuTLS {} or later"
457
.format(self._need_version))
537
"""This isn't so much a class as it is a module-like namespace."""
539
library = ctypes.util.find_library("gnutls")
541
library = ctypes.util.find_library("gnutls-deb0")
542
_library = ctypes.cdll.LoadLibrary(library)
459
545
# Unless otherwise indicated, the constants and types below are
460
546
# all from the gnutls/gnutls.h C header file.
464
550
E_INTERRUPTED = -52
469
556
CRD_CERTIFICATE = 1
470
557
E_NO_CERTIFICATE_FOUND = -49
562
KEYID_USE_SHA256 = 1 # gnutls/x509.h
471
563
OPENPGP_FMT_RAW = 0 # gnutls/openpgp.h
474
class session_int(ctypes.Structure):
566
class _session_int(ctypes.Structure):
476
session_t = ctypes.POINTER(session_int)
568
session_t = ctypes.POINTER(_session_int)
477
570
class certificate_credentials_st(ctypes.Structure):
479
572
certificate_credentials_t = ctypes.POINTER(
480
573
certificate_credentials_st)
481
574
certificate_type_t = ctypes.c_int
482
576
class datum_t(ctypes.Structure):
483
577
_fields_ = [('data', ctypes.POINTER(ctypes.c_ubyte)),
484
578
('size', ctypes.c_uint)]
485
class openpgp_crt_int(ctypes.Structure):
580
class _openpgp_crt_int(ctypes.Structure):
487
openpgp_crt_t = ctypes.POINTER(openpgp_crt_int)
488
openpgp_crt_fmt_t = ctypes.c_int # gnutls/openpgp.h
582
openpgp_crt_t = ctypes.POINTER(_openpgp_crt_int)
583
openpgp_crt_fmt_t = ctypes.c_int # gnutls/openpgp.h
489
584
log_func = ctypes.CFUNCTYPE(None, ctypes.c_int, ctypes.c_char_p)
490
credentials_type_t = ctypes.c_int #
585
credentials_type_t = ctypes.c_int
491
586
transport_ptr_t = ctypes.c_void_p
492
587
close_request_t = ctypes.c_int
495
590
class Error(Exception):
496
# We need to use the class name "GnuTLS" here, since this
497
# exception might be raised from within GnuTLS.__init__,
498
# which is called before the assignment to the "gnutls"
499
# global variable has happened.
500
def __init__(self, message = None, code = None, args=()):
591
def __init__(self, message=None, code=None, args=()):
501
592
# Default usage is by a message string, but if a return
502
593
# code is passed, convert it to a string with
503
594
# gnutls.strerror()
505
596
if message is None and code is not None:
506
message = GnuTLS.strerror(code)
507
return super(GnuTLS.Error, self).__init__(
597
message = gnutls.strerror(code).decode(
598
"utf-8", errors="replace")
599
return super(gnutls.Error, self).__init__(
510
602
class CertificateSecurityError(Error):
606
def __init__(self, cls):
609
def from_param(self, obj):
610
if not isinstance(obj, self.cls):
611
raise TypeError("Not of type {}: {!r}"
612
.format(self.cls.__name__, obj))
613
return ctypes.byref(obj.from_param(obj))
615
class CastToVoidPointer:
616
def __init__(self, cls):
619
def from_param(self, obj):
620
if not isinstance(obj, self.cls):
621
raise TypeError("Not of type {}: {!r}"
622
.format(self.cls.__name__, obj))
623
return ctypes.cast(obj.from_param(obj), ctypes.c_void_p)
625
class With_from_param:
627
def from_param(cls, obj):
628
return obj._as_parameter_
514
class Credentials(object):
631
class Credentials(With_from_param):
515
632
def __init__(self):
516
self._c_object = gnutls.certificate_credentials_t()
517
gnutls.certificate_allocate_credentials(
518
ctypes.byref(self._c_object))
633
self._as_parameter_ = gnutls.certificate_credentials_t()
634
gnutls.certificate_allocate_credentials(self)
519
635
self.type = gnutls.CRD_CERTIFICATE
521
637
def __del__(self):
522
gnutls.certificate_free_credentials(self._c_object)
524
class ClientSession(object):
525
def __init__(self, socket, credentials = None):
526
self._c_object = gnutls.session_t()
527
gnutls.init(ctypes.byref(self._c_object), gnutls.CLIENT)
528
gnutls.set_default_priority(self._c_object)
529
gnutls.transport_set_ptr(self._c_object, socket.fileno())
530
gnutls.handshake_set_private_extensions(self._c_object,
638
gnutls.certificate_free_credentials(self)
640
class ClientSession(With_from_param):
641
def __init__(self, socket, credentials=None):
642
self._as_parameter_ = gnutls.session_t()
643
gnutls_flags = gnutls.CLIENT
644
if gnutls.check_version(b"3.5.6"):
645
gnutls_flags |= gnutls.NO_TICKETS
647
gnutls_flags |= gnutls.ENABLE_RAWPK
648
gnutls.init(self, gnutls_flags)
650
gnutls.set_default_priority(self)
651
gnutls.transport_set_ptr(self, socket.fileno())
652
gnutls.handshake_set_private_extensions(self, True)
532
653
self.socket = socket
533
654
if credentials is None:
534
655
credentials = gnutls.Credentials()
535
gnutls.credentials_set(self._c_object, credentials.type,
536
ctypes.cast(credentials._c_object,
656
gnutls.credentials_set(self, credentials.type,
538
658
self.credentials = credentials
540
660
def __del__(self):
541
gnutls.deinit(self._c_object)
543
663
def handshake(self):
544
return gnutls.handshake(self._c_object)
664
return gnutls.handshake(self)
546
666
def send(self, data):
547
667
data = bytes(data)
548
668
data_len = len(data)
549
669
while data_len > 0:
550
data_len -= gnutls.record_send(self._c_object,
670
data_len -= gnutls.record_send(self, data[-data_len:],
555
return gnutls.bye(self._c_object, gnutls.SHUT_RDWR)
674
return gnutls.bye(self, gnutls.SHUT_RDWR)
557
676
# Error handling functions
558
677
def _error_code(result):
559
678
"""A function to raise exceptions on errors, suitable
560
679
for the 'restype' attribute on ctypes functions"""
680
if result >= gnutls.E_SUCCESS:
563
682
if result == gnutls.E_NO_CERTIFICATE_FOUND:
564
raise gnutls.CertificateSecurityError(code = result)
565
raise gnutls.Error(code = result)
567
def _retry_on_error(result, func, arguments):
683
raise gnutls.CertificateSecurityError(code=result)
684
raise gnutls.Error(code=result)
686
def _retry_on_error(result, func, arguments,
687
_error_code=_error_code):
568
688
"""A function to retry on some errors, suitable
569
689
for the 'errcheck' attribute on ctypes functions"""
690
while result < gnutls.E_SUCCESS:
571
691
if result not in (gnutls.E_INTERRUPTED, gnutls.E_AGAIN):
572
692
return _error_code(result)
573
693
result = func(*arguments)
576
696
# Unless otherwise indicated, the function declarations below are
577
697
# all from the gnutls/gnutls.h C header file.
580
700
priority_set_direct = _library.gnutls_priority_set_direct
581
priority_set_direct.argtypes = [session_t, ctypes.c_char_p,
701
priority_set_direct.argtypes = [ClientSession, ctypes.c_char_p,
582
702
ctypes.POINTER(ctypes.c_char_p)]
583
703
priority_set_direct.restype = _error_code
585
705
init = _library.gnutls_init
586
init.argtypes = [ctypes.POINTER(session_t), ctypes.c_int]
706
init.argtypes = [PointerTo(ClientSession), ctypes.c_int]
587
707
init.restype = _error_code
589
709
set_default_priority = _library.gnutls_set_default_priority
590
set_default_priority.argtypes = [session_t]
710
set_default_priority.argtypes = [ClientSession]
591
711
set_default_priority.restype = _error_code
593
713
record_send = _library.gnutls_record_send
594
record_send.argtypes = [session_t, ctypes.c_void_p,
714
record_send.argtypes = [ClientSession, ctypes.c_void_p,
596
716
record_send.restype = ctypes.c_ssize_t
597
717
record_send.errcheck = _retry_on_error
599
719
certificate_allocate_credentials = (
600
720
_library.gnutls_certificate_allocate_credentials)
601
721
certificate_allocate_credentials.argtypes = [
602
ctypes.POINTER(certificate_credentials_t)]
722
PointerTo(Credentials)]
603
723
certificate_allocate_credentials.restype = _error_code
605
725
certificate_free_credentials = (
606
726
_library.gnutls_certificate_free_credentials)
607
certificate_free_credentials.argtypes = [certificate_credentials_t]
727
certificate_free_credentials.argtypes = [Credentials]
608
728
certificate_free_credentials.restype = None
610
730
handshake_set_private_extensions = (
611
731
_library.gnutls_handshake_set_private_extensions)
612
handshake_set_private_extensions.argtypes = [session_t,
732
handshake_set_private_extensions.argtypes = [ClientSession,
614
734
handshake_set_private_extensions.restype = None
616
736
credentials_set = _library.gnutls_credentials_set
617
credentials_set.argtypes = [session_t, credentials_type_t,
737
credentials_set.argtypes = [ClientSession, credentials_type_t,
738
CastToVoidPointer(Credentials)]
619
739
credentials_set.restype = _error_code
621
741
strerror = _library.gnutls_strerror
622
742
strerror.argtypes = [ctypes.c_int]
623
743
strerror.restype = ctypes.c_char_p
625
745
certificate_type_get = _library.gnutls_certificate_type_get
626
certificate_type_get.argtypes = [session_t]
746
certificate_type_get.argtypes = [ClientSession]
627
747
certificate_type_get.restype = _error_code
629
749
certificate_get_peers = _library.gnutls_certificate_get_peers
630
certificate_get_peers.argtypes = [session_t,
750
certificate_get_peers.argtypes = [ClientSession,
631
751
ctypes.POINTER(ctypes.c_uint)]
632
752
certificate_get_peers.restype = ctypes.POINTER(datum_t)
634
754
global_set_log_level = _library.gnutls_global_set_log_level
635
755
global_set_log_level.argtypes = [ctypes.c_int]
636
756
global_set_log_level.restype = None
638
758
global_set_log_function = _library.gnutls_global_set_log_function
639
759
global_set_log_function.argtypes = [log_func]
640
760
global_set_log_function.restype = None
642
762
deinit = _library.gnutls_deinit
643
deinit.argtypes = [session_t]
763
deinit.argtypes = [ClientSession]
644
764
deinit.restype = None
646
766
handshake = _library.gnutls_handshake
647
handshake.argtypes = [session_t]
648
handshake.restype = _error_code
767
handshake.argtypes = [ClientSession]
768
handshake.restype = ctypes.c_int
649
769
handshake.errcheck = _retry_on_error
651
771
transport_set_ptr = _library.gnutls_transport_set_ptr
652
transport_set_ptr.argtypes = [session_t, transport_ptr_t]
772
transport_set_ptr.argtypes = [ClientSession, transport_ptr_t]
653
773
transport_set_ptr.restype = None
655
775
bye = _library.gnutls_bye
656
bye.argtypes = [session_t, close_request_t]
657
bye.restype = _error_code
776
bye.argtypes = [ClientSession, close_request_t]
777
bye.restype = ctypes.c_int
658
778
bye.errcheck = _retry_on_error
660
780
check_version = _library.gnutls_check_version
661
781
check_version.argtypes = [ctypes.c_char_p]
662
782
check_version.restype = ctypes.c_char_p
664
# All the function declarations below are from gnutls/openpgp.h
666
openpgp_crt_init = _library.gnutls_openpgp_crt_init
667
openpgp_crt_init.argtypes = [ctypes.POINTER(openpgp_crt_t)]
668
openpgp_crt_init.restype = _error_code
670
openpgp_crt_import = _library.gnutls_openpgp_crt_import
671
openpgp_crt_import.argtypes = [openpgp_crt_t,
672
ctypes.POINTER(datum_t),
674
openpgp_crt_import.restype = _error_code
676
openpgp_crt_verify_self = _library.gnutls_openpgp_crt_verify_self
677
openpgp_crt_verify_self.argtypes = [openpgp_crt_t, ctypes.c_uint,
678
ctypes.POINTER(ctypes.c_uint)]
679
openpgp_crt_verify_self.restype = _error_code
681
openpgp_crt_deinit = _library.gnutls_openpgp_crt_deinit
682
openpgp_crt_deinit.argtypes = [openpgp_crt_t]
683
openpgp_crt_deinit.restype = None
685
openpgp_crt_get_fingerprint = (
686
_library.gnutls_openpgp_crt_get_fingerprint)
687
openpgp_crt_get_fingerprint.argtypes = [openpgp_crt_t,
691
openpgp_crt_get_fingerprint.restype = _error_code
784
_need_version = b"3.3.0"
785
if check_version(_need_version) is None:
786
raise self.Error("Needs GnuTLS {} or later"
787
.format(_need_version))
789
_tls_rawpk_version = b"3.6.6"
790
has_rawpk = bool(check_version(_tls_rawpk_version))
794
class pubkey_st(ctypes.Structure):
796
pubkey_t = ctypes.POINTER(pubkey_st)
798
x509_crt_fmt_t = ctypes.c_int
800
# All the function declarations below are from
802
pubkey_init = _library.gnutls_pubkey_init
803
pubkey_init.argtypes = [ctypes.POINTER(pubkey_t)]
804
pubkey_init.restype = _error_code
806
pubkey_import = _library.gnutls_pubkey_import
807
pubkey_import.argtypes = [pubkey_t, ctypes.POINTER(datum_t),
809
pubkey_import.restype = _error_code
811
pubkey_get_key_id = _library.gnutls_pubkey_get_key_id
812
pubkey_get_key_id.argtypes = [pubkey_t, ctypes.c_int,
813
ctypes.POINTER(ctypes.c_ubyte),
814
ctypes.POINTER(ctypes.c_size_t)]
815
pubkey_get_key_id.restype = _error_code
817
pubkey_deinit = _library.gnutls_pubkey_deinit
818
pubkey_deinit.argtypes = [pubkey_t]
819
pubkey_deinit.restype = None
821
# All the function declarations below are from
824
openpgp_crt_init = _library.gnutls_openpgp_crt_init
825
openpgp_crt_init.argtypes = [ctypes.POINTER(openpgp_crt_t)]
826
openpgp_crt_init.restype = _error_code
828
openpgp_crt_import = _library.gnutls_openpgp_crt_import
829
openpgp_crt_import.argtypes = [openpgp_crt_t,
830
ctypes.POINTER(datum_t),
832
openpgp_crt_import.restype = _error_code
834
openpgp_crt_verify_self = \
835
_library.gnutls_openpgp_crt_verify_self
836
openpgp_crt_verify_self.argtypes = [
839
ctypes.POINTER(ctypes.c_uint),
841
openpgp_crt_verify_self.restype = _error_code
843
openpgp_crt_deinit = _library.gnutls_openpgp_crt_deinit
844
openpgp_crt_deinit.argtypes = [openpgp_crt_t]
845
openpgp_crt_deinit.restype = None
847
openpgp_crt_get_fingerprint = (
848
_library.gnutls_openpgp_crt_get_fingerprint)
849
openpgp_crt_get_fingerprint.argtypes = [openpgp_crt_t,
853
openpgp_crt_get_fingerprint.restype = _error_code
855
if check_version(b"3.6.4"):
856
certificate_type_get2 = _library.gnutls_certificate_type_get2
857
certificate_type_get2.argtypes = [ClientSession, ctypes.c_int]
858
certificate_type_get2.restype = _error_code
693
860
# Remove non-public functions
694
861
del _error_code, _retry_on_error
695
# Create the global "gnutls" object, simulating a module
698
864
def call_pipe(connection, # : multiprocessing.Connection
699
865
func, *args, **kwargs):
700
866
"""This function is meant to be called by multiprocessing.Process
702
868
This function runs func(*args, **kwargs), and writes the resulting
703
869
return value on the provided multiprocessing.Connection.
705
871
connection.send(func(*args, **kwargs))
706
872
connection.close()
708
class Client(object):
709
876
"""A representation of a client host served by this server.
712
879
approved: bool(); 'None' if not yet approved/disapproved
713
880
approval_delay: datetime.timedelta(); Time to wait for approval
714
881
approval_duration: datetime.timedelta(); Duration of one approval
715
checker: subprocess.Popen(); a running checker process used
716
to see if the client lives.
717
'None' if no process is running.
718
checker_callback_tag: a gobject event source tag, or None
882
checker: multiprocessing.Process(); a running checker process used
883
to see if the client lives. 'None' if no process is
885
checker_callback_tag: a GLib event source tag, or None
719
886
checker_command: string; External command which is run to check
720
887
if client lives. %() expansions are done at
721
888
runtime with vars(self) as dict, so that for
722
889
instance %(name)s can be used in the command.
723
checker_initiator_tag: a gobject event source tag, or None
890
checker_initiator_tag: a GLib event source tag, or None
724
891
created: datetime.datetime(); (UTC) object creation
725
892
client_structure: Object describing what attributes a client has
726
893
and is used for storing the client at exit
727
894
current_checker_command: string; current running checker_command
728
disable_initiator_tag: a gobject event source tag, or None
895
disable_initiator_tag: a GLib event source tag, or None
730
897
fingerprint: string (40 or 32 hexadecimal digits); used to
731
uniquely identify the client
898
uniquely identify an OpenPGP client
899
key_id: string (64 hexadecimal digits); used to uniquely identify
900
a client using raw public keys
732
901
host: string; available for use by the checker command
733
902
interval: datetime.timedelta(); How often to start a new checker
734
903
last_approval_request: datetime.datetime(); (UTC) or None