11
11
# "AvahiService" class, and some lines in "main".
13
13
# Everything else is
14
# Copyright © 2008-2017 Teddy Hogeborn
15
# Copyright © 2008-2017 Björn Påhlsson
17
# This program is free software: you can redistribute it and/or modify
18
# it under the terms of the GNU General Public License as published by
14
# Copyright © 2008-2020 Teddy Hogeborn
15
# Copyright © 2008-2020 Björn Påhlsson
17
# This file is part of Mandos.
19
# Mandos is free software: you can redistribute it and/or modify it
20
# under the terms of the GNU General Public License as published by
19
21
# the Free Software Foundation, either version 3 of the License, or
20
22
# (at your option) any later version.
22
# This program is distributed in the hope that it will be useful,
23
# but WITHOUT ANY WARRANTY; without even the implied warranty of
24
# Mandos is distributed in the hope that it will be useful, but
25
# WITHOUT ANY WARRANTY; without even the implied warranty of
24
26
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25
27
# GNU General Public License for more details.
27
29
# You should have received a copy of the GNU General Public License
28
# along with this program. If not, see
29
# <http://www.gnu.org/licenses/>.
30
# along with Mandos. If not, see <http://www.gnu.org/licenses/>.
31
32
# Contact the authors at <mandos@recompile.se>.
563
590
class Error(Exception):
564
# We need to use the class name "GnuTLS" here, since this
565
# exception might be raised from within GnuTLS.__init__,
566
# which is called before the assignment to the "gnutls"
567
# global variable has happened.
568
591
def __init__(self, message=None, code=None, args=()):
569
592
# Default usage is by a message string, but if a return
570
593
# code is passed, convert it to a string with
571
594
# gnutls.strerror()
573
596
if message is None and code is not None:
574
message = GnuTLS.strerror(code)
575
return super(GnuTLS.Error, self).__init__(
597
message = gnutls.strerror(code).decode(
598
"utf-8", errors="replace")
599
return super(gnutls.Error, self).__init__(
578
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_
582
class Credentials(object):
631
class Credentials(With_from_param):
583
632
def __init__(self):
584
self._c_object = gnutls.certificate_credentials_t()
585
gnutls.certificate_allocate_credentials(
586
ctypes.byref(self._c_object))
633
self._as_parameter_ = gnutls.certificate_credentials_t()
634
gnutls.certificate_allocate_credentials(self)
587
635
self.type = gnutls.CRD_CERTIFICATE
589
637
def __del__(self):
590
gnutls.certificate_free_credentials(self._c_object)
638
gnutls.certificate_free_credentials(self)
592
class ClientSession(object):
640
class ClientSession(With_from_param):
593
641
def __init__(self, socket, credentials=None):
594
self._c_object = gnutls.session_t()
595
gnutls.init(ctypes.byref(self._c_object), gnutls.CLIENT)
596
gnutls.set_default_priority(self._c_object)
597
gnutls.transport_set_ptr(self._c_object, socket.fileno())
598
gnutls.handshake_set_private_extensions(self._c_object,
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)
600
653
self.socket = socket
601
654
if credentials is None:
602
655
credentials = gnutls.Credentials()
603
gnutls.credentials_set(self._c_object, credentials.type,
604
ctypes.cast(credentials._c_object,
656
gnutls.credentials_set(self, credentials.type,
606
658
self.credentials = credentials
608
660
def __del__(self):
609
gnutls.deinit(self._c_object)
611
663
def handshake(self):
612
return gnutls.handshake(self._c_object)
664
return gnutls.handshake(self)
614
666
def send(self, data):
615
667
data = bytes(data)
616
668
data_len = len(data)
617
669
while data_len > 0:
618
data_len -= gnutls.record_send(self._c_object,
670
data_len -= gnutls.record_send(self, data[-data_len:],
623
return gnutls.bye(self._c_object, gnutls.SHUT_RDWR)
674
return gnutls.bye(self, gnutls.SHUT_RDWR)
625
676
# Error handling functions
626
677
def _error_code(result):
627
678
"""A function to raise exceptions on errors, suitable
628
679
for the 'restype' attribute on ctypes functions"""
680
if result >= gnutls.E_SUCCESS:
631
682
if result == gnutls.E_NO_CERTIFICATE_FOUND:
632
683
raise gnutls.CertificateSecurityError(code=result)
633
684
raise gnutls.Error(code=result)
635
def _retry_on_error(result, func, arguments):
686
def _retry_on_error(result, func, arguments,
687
_error_code=_error_code):
636
688
"""A function to retry on some errors, suitable
637
689
for the 'errcheck' attribute on ctypes functions"""
690
while result < gnutls.E_SUCCESS:
639
691
if result not in (gnutls.E_INTERRUPTED, gnutls.E_AGAIN):
640
692
return _error_code(result)
641
693
result = func(*arguments)
648
700
priority_set_direct = _library.gnutls_priority_set_direct
649
priority_set_direct.argtypes = [session_t, ctypes.c_char_p,
701
priority_set_direct.argtypes = [ClientSession, ctypes.c_char_p,
650
702
ctypes.POINTER(ctypes.c_char_p)]
651
703
priority_set_direct.restype = _error_code
653
705
init = _library.gnutls_init
654
init.argtypes = [ctypes.POINTER(session_t), ctypes.c_int]
706
init.argtypes = [PointerTo(ClientSession), ctypes.c_int]
655
707
init.restype = _error_code
657
709
set_default_priority = _library.gnutls_set_default_priority
658
set_default_priority.argtypes = [session_t]
710
set_default_priority.argtypes = [ClientSession]
659
711
set_default_priority.restype = _error_code
661
713
record_send = _library.gnutls_record_send
662
record_send.argtypes = [session_t, ctypes.c_void_p,
714
record_send.argtypes = [ClientSession, ctypes.c_void_p,
664
716
record_send.restype = ctypes.c_ssize_t
665
717
record_send.errcheck = _retry_on_error
667
719
certificate_allocate_credentials = (
668
720
_library.gnutls_certificate_allocate_credentials)
669
721
certificate_allocate_credentials.argtypes = [
670
ctypes.POINTER(certificate_credentials_t)]
722
PointerTo(Credentials)]
671
723
certificate_allocate_credentials.restype = _error_code
673
725
certificate_free_credentials = (
674
726
_library.gnutls_certificate_free_credentials)
675
certificate_free_credentials.argtypes = [
676
certificate_credentials_t]
727
certificate_free_credentials.argtypes = [Credentials]
677
728
certificate_free_credentials.restype = None
679
730
handshake_set_private_extensions = (
680
731
_library.gnutls_handshake_set_private_extensions)
681
handshake_set_private_extensions.argtypes = [session_t,
732
handshake_set_private_extensions.argtypes = [ClientSession,
683
734
handshake_set_private_extensions.restype = None
685
736
credentials_set = _library.gnutls_credentials_set
686
credentials_set.argtypes = [session_t, credentials_type_t,
737
credentials_set.argtypes = [ClientSession, credentials_type_t,
738
CastToVoidPointer(Credentials)]
688
739
credentials_set.restype = _error_code
690
741
strerror = _library.gnutls_strerror
709
760
global_set_log_function.restype = None
711
762
deinit = _library.gnutls_deinit
712
deinit.argtypes = [session_t]
763
deinit.argtypes = [ClientSession]
713
764
deinit.restype = None
715
766
handshake = _library.gnutls_handshake
716
handshake.argtypes = [session_t]
717
handshake.restype = _error_code
767
handshake.argtypes = [ClientSession]
768
handshake.restype = ctypes.c_int
718
769
handshake.errcheck = _retry_on_error
720
771
transport_set_ptr = _library.gnutls_transport_set_ptr
721
transport_set_ptr.argtypes = [session_t, transport_ptr_t]
772
transport_set_ptr.argtypes = [ClientSession, transport_ptr_t]
722
773
transport_set_ptr.restype = None
724
775
bye = _library.gnutls_bye
725
bye.argtypes = [session_t, close_request_t]
726
bye.restype = _error_code
776
bye.argtypes = [ClientSession, close_request_t]
777
bye.restype = ctypes.c_int
727
778
bye.errcheck = _retry_on_error
729
780
check_version = _library.gnutls_check_version
730
781
check_version.argtypes = [ctypes.c_char_p]
731
782
check_version.restype = ctypes.c_char_p
733
# All the function declarations below are from gnutls/openpgp.h
735
openpgp_crt_init = _library.gnutls_openpgp_crt_init
736
openpgp_crt_init.argtypes = [ctypes.POINTER(openpgp_crt_t)]
737
openpgp_crt_init.restype = _error_code
739
openpgp_crt_import = _library.gnutls_openpgp_crt_import
740
openpgp_crt_import.argtypes = [openpgp_crt_t,
741
ctypes.POINTER(datum_t),
743
openpgp_crt_import.restype = _error_code
745
openpgp_crt_verify_self = _library.gnutls_openpgp_crt_verify_self
746
openpgp_crt_verify_self.argtypes = [openpgp_crt_t, ctypes.c_uint,
747
ctypes.POINTER(ctypes.c_uint)]
748
openpgp_crt_verify_self.restype = _error_code
750
openpgp_crt_deinit = _library.gnutls_openpgp_crt_deinit
751
openpgp_crt_deinit.argtypes = [openpgp_crt_t]
752
openpgp_crt_deinit.restype = None
754
openpgp_crt_get_fingerprint = (
755
_library.gnutls_openpgp_crt_get_fingerprint)
756
openpgp_crt_get_fingerprint.argtypes = [openpgp_crt_t,
760
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
762
860
# Remove non-public functions
763
861
del _error_code, _retry_on_error
764
# Create the global "gnutls" object, simulating a module
768
864
def call_pipe(connection, # : multiprocessing.Connection
2237
2347
approval_required = False
2240
fpr = self.fingerprint(
2241
self.peer_certificate(session))
2242
except (TypeError, gnutls.Error) as error:
2243
logger.warning("Bad certificate: %s", error)
2245
logger.debug("Fingerprint: %s", fpr)
2248
client = ProxyClient(child_pipe, fpr,
2349
if gnutls.has_rawpk:
2352
key_id = self.key_id(
2353
self.peer_certificate(session))
2354
except (TypeError, gnutls.Error) as error:
2355
logger.warning("Bad certificate: %s", error)
2357
logger.debug("Key ID: %s",
2358
key_id.decode("utf-8",
2364
fpr = self.fingerprint(
2365
self.peer_certificate(session))
2366
except (TypeError, gnutls.Error) as error:
2367
logger.warning("Bad certificate: %s", error)
2369
logger.debug("Fingerprint: %s", fpr)
2372
client = ProxyClient(child_pipe, key_id, fpr,
2249
2373
self.client_address)
2250
2374
except KeyError:
2330
2454
def peer_certificate(session):
2331
"Return the peer's OpenPGP certificate as a bytestring"
2332
# If not an OpenPGP certificate...
2333
if (gnutls.certificate_type_get(session._c_object)
2334
!= gnutls.CRT_OPENPGP):
2455
"Return the peer's certificate as a bytestring"
2457
cert_type = gnutls.certificate_type_get2(
2458
session, gnutls.CTYPE_PEERS)
2459
except AttributeError:
2460
cert_type = gnutls.certificate_type_get(session)
2461
if gnutls.has_rawpk:
2462
valid_cert_types = frozenset((gnutls.CRT_RAWPK,))
2464
valid_cert_types = frozenset((gnutls.CRT_OPENPGP,))
2465
# If not a valid certificate type...
2466
if cert_type not in valid_cert_types:
2467
logger.info("Cert type %r not in %r", cert_type,
2335
2469
# ...return invalid data
2337
2471
list_size = ctypes.c_uint(1)
2338
2472
cert_list = (gnutls.certificate_get_peers
2339
(session._c_object, ctypes.byref(list_size)))
2473
(session, ctypes.byref(list_size)))
2340
2474
if not bool(cert_list) and list_size.value != 0:
2341
2475
raise gnutls.Error("error getting peer certificate")
2342
2476
if list_size.value == 0:
2345
2479
return ctypes.string_at(cert.data, cert.size)
2482
def key_id(certificate):
2483
"Convert a certificate bytestring to a hexdigit key ID"
2484
# New GnuTLS "datum" with the public key
2485
datum = gnutls.datum_t(
2486
ctypes.cast(ctypes.c_char_p(certificate),
2487
ctypes.POINTER(ctypes.c_ubyte)),
2488
ctypes.c_uint(len(certificate)))
2489
# XXX all these need to be created in the gnutls "module"
2490
# New empty GnuTLS certificate
2491
pubkey = gnutls.pubkey_t()
2492
gnutls.pubkey_init(ctypes.byref(pubkey))
2493
# Import the raw public key into the certificate
2494
gnutls.pubkey_import(pubkey,
2495
ctypes.byref(datum),
2496
gnutls.X509_FMT_DER)
2497
# New buffer for the key ID
2498
buf = ctypes.create_string_buffer(32)
2499
buf_len = ctypes.c_size_t(len(buf))
2500
# Get the key ID from the raw public key into the buffer
2501
gnutls.pubkey_get_key_id(
2503
gnutls.KEYID_USE_SHA256,
2504
ctypes.cast(ctypes.byref(buf),
2505
ctypes.POINTER(ctypes.c_ubyte)),
2506
ctypes.byref(buf_len))
2507
# Deinit the certificate
2508
gnutls.pubkey_deinit(pubkey)
2510
# Convert the buffer to a Python bytestring
2511
key_id = ctypes.string_at(buf, buf_len.value)
2512
# Convert the bytestring to hexadecimal notation
2513
hex_key_id = binascii.hexlify(key_id).upper()
2348
2517
def fingerprint(openpgp):
2349
2518
"Convert an OpenPGP bytestring to a hexdigit fingerprint"
2350
2519
# New GnuTLS "datum" with the OpenPGP public key
2577
2749
command = request[0]
2579
2751
if command == 'init':
2581
address = request[2]
2752
key_id = request[1].decode("ascii")
2753
fpr = request[2].decode("ascii")
2754
address = request[3]
2583
2756
for c in self.clients.values():
2584
if c.fingerprint == fpr:
2757
if key_id == ("E3B0C44298FC1C149AFBF4C8996FB924"
2758
"27AE41E4649B934CA495991B7852B855"):
2760
if key_id and c.key_id == key_id:
2763
if fpr and c.fingerprint == fpr:
2588
logger.info("Client not found for fingerprint: %s, ad"
2589
"dress: %s", fpr, address)
2767
logger.info("Client not found for key ID: %s, address"
2768
": %s", key_id or fpr, address)
2590
2769
if self.use_dbus:
2591
2770
# Emit D-Bus signal
2592
mandos_dbus_service.ClientNotFound(fpr,
2771
mandos_dbus_service.ClientNotFound(key_id or fpr,
2594
2773
parent_pipe.send(False)
2597
2776
GLib.io_add_watch(
2598
parent_pipe.fileno(),
2599
GLib.IO_IN | GLib.IO_HUP,
2777
GLib.IOChannel.unix_new(parent_pipe.fileno()),
2778
GLib.PRIORITY_DEFAULT, GLib.IO_IN | GLib.IO_HUP,
2600
2779
functools.partial(self.handle_ipc,
2601
2780
parent_pipe=parent_pipe,
2634
2813
def rfc3339_duration_to_delta(duration):
2635
2814
"""Parse an RFC 3339 "duration" and return a datetime.timedelta
2637
>>> rfc3339_duration_to_delta("P7D")
2638
datetime.timedelta(7)
2639
>>> rfc3339_duration_to_delta("PT60S")
2640
datetime.timedelta(0, 60)
2641
>>> rfc3339_duration_to_delta("PT60M")
2642
datetime.timedelta(0, 3600)
2643
>>> rfc3339_duration_to_delta("PT24H")
2644
datetime.timedelta(1)
2645
>>> rfc3339_duration_to_delta("P1W")
2646
datetime.timedelta(7)
2647
>>> rfc3339_duration_to_delta("PT5M30S")
2648
datetime.timedelta(0, 330)
2649
>>> rfc3339_duration_to_delta("P1DT3M20S")
2650
datetime.timedelta(1, 200)
2816
>>> timedelta = datetime.timedelta
2817
>>> rfc3339_duration_to_delta("P7D") == timedelta(7)
2819
>>> rfc3339_duration_to_delta("PT60S") == timedelta(0, 60)
2821
>>> rfc3339_duration_to_delta("PT60M") == timedelta(0, 3600)
2823
>>> rfc3339_duration_to_delta("PT24H") == timedelta(1)
2825
>>> rfc3339_duration_to_delta("P1W") == timedelta(7)
2827
>>> rfc3339_duration_to_delta("PT5M30S") == timedelta(0, 330)
2829
>>> rfc3339_duration_to_delta("P1DT3M20S") == timedelta(1, 200)
2653
2834
# Parsing an RFC 3339 duration with regular expressions is not
2733
2914
def string_to_delta(interval):
2734
2915
"""Parse a string and return a datetime.timedelta
2736
>>> string_to_delta('7d')
2737
datetime.timedelta(7)
2738
>>> string_to_delta('60s')
2739
datetime.timedelta(0, 60)
2740
>>> string_to_delta('60m')
2741
datetime.timedelta(0, 3600)
2742
>>> string_to_delta('24h')
2743
datetime.timedelta(1)
2744
>>> string_to_delta('1w')
2745
datetime.timedelta(7)
2746
>>> string_to_delta('5m 30s')
2747
datetime.timedelta(0, 330)
2917
>>> string_to_delta('7d') == datetime.timedelta(7)
2919
>>> string_to_delta('60s') == datetime.timedelta(0, 60)
2921
>>> string_to_delta('60m') == datetime.timedelta(0, 3600)
2923
>>> string_to_delta('24h') == datetime.timedelta(1)
2925
>>> string_to_delta('1w') == datetime.timedelta(7)
2927
>>> string_to_delta('5m 30s') == datetime.timedelta(0, 330)