193
218
output = subprocess.check_output(["gpgconf"])
194
219
for line in output.splitlines():
195
220
name, text, path = line.split(b":")
199
224
except OSError as e:
200
225
if e.errno != errno.ENOENT:
202
self.gnupgargs = ['--batch',
203
'--homedir', self.tempdir,
227
self.gnupgargs = ["--batch",
228
"--homedir", self.tempdir,
206
231
# Only GPG version 1 has the --no-use-agent option.
207
if self.gpg == "gpg" or self.gpg.endswith("/gpg"):
232
if self.gpg == b"gpg" or self.gpg.endswith(b"/gpg"):
208
233
self.gnupgargs.append("--no-use-agent")
210
235
def __enter__(self):
568
594
# gnutls.strerror()
570
596
if message is None and code is not None:
571
message = gnutls.strerror(code)
597
message = gnutls.strerror(code).decode(
598
"utf-8", errors="replace")
572
599
return super(gnutls.Error, self).__init__(
575
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_
579
class Credentials(object):
631
class Credentials(With_from_param):
580
632
def __init__(self):
581
self._c_object = gnutls.certificate_credentials_t()
582
gnutls.certificate_allocate_credentials(
583
ctypes.byref(self._c_object))
633
self._as_parameter_ = gnutls.certificate_credentials_t()
634
gnutls.certificate_allocate_credentials(self)
584
635
self.type = gnutls.CRD_CERTIFICATE
586
637
def __del__(self):
587
gnutls.certificate_free_credentials(self._c_object)
638
gnutls.certificate_free_credentials(self)
589
class ClientSession(object):
640
class ClientSession(With_from_param):
590
641
def __init__(self, socket, credentials=None):
591
self._c_object = gnutls.session_t()
642
self._as_parameter_ = gnutls.session_t()
592
643
gnutls_flags = gnutls.CLIENT
593
644
if gnutls.check_version(b"3.5.6"):
594
645
gnutls_flags |= gnutls.NO_TICKETS
595
646
if gnutls.has_rawpk:
596
647
gnutls_flags |= gnutls.ENABLE_RAWPK
597
gnutls.init(ctypes.byref(self._c_object), gnutls_flags)
648
gnutls.init(self, gnutls_flags)
599
gnutls.set_default_priority(self._c_object)
600
gnutls.transport_set_ptr(self._c_object, socket.fileno())
601
gnutls.handshake_set_private_extensions(self._c_object,
650
gnutls.set_default_priority(self)
651
gnutls.transport_set_ptr(self, socket.fileno())
652
gnutls.handshake_set_private_extensions(self, True)
603
653
self.socket = socket
604
654
if credentials is None:
605
655
credentials = gnutls.Credentials()
606
gnutls.credentials_set(self._c_object, credentials.type,
607
ctypes.cast(credentials._c_object,
656
gnutls.credentials_set(self, credentials.type,
609
658
self.credentials = credentials
611
660
def __del__(self):
612
gnutls.deinit(self._c_object)
614
663
def handshake(self):
615
return gnutls.handshake(self._c_object)
664
return gnutls.handshake(self)
617
666
def send(self, data):
618
667
data = bytes(data)
619
668
data_len = len(data)
620
669
while data_len > 0:
621
data_len -= gnutls.record_send(self._c_object,
670
data_len -= gnutls.record_send(self, data[-data_len:],
626
return gnutls.bye(self._c_object, gnutls.SHUT_RDWR)
674
return gnutls.bye(self, gnutls.SHUT_RDWR)
628
676
# Error handling functions
629
677
def _error_code(result):
630
678
"""A function to raise exceptions on errors, suitable
631
for the 'restype' attribute on ctypes functions"""
679
for the "restype" attribute on ctypes functions"""
680
if result >= gnutls.E_SUCCESS:
634
682
if result == gnutls.E_NO_CERTIFICATE_FOUND:
635
683
raise gnutls.CertificateSecurityError(code=result)
636
684
raise gnutls.Error(code=result)
638
def _retry_on_error(result, func, arguments):
686
def _retry_on_error(result, func, arguments,
687
_error_code=_error_code):
639
688
"""A function to retry on some errors, suitable
640
for the 'errcheck' attribute on ctypes functions"""
689
for the "errcheck" attribute on ctypes functions"""
690
while result < gnutls.E_SUCCESS:
642
691
if result not in (gnutls.E_INTERRUPTED, gnutls.E_AGAIN):
643
692
return _error_code(result)
644
693
result = func(*arguments)
651
700
priority_set_direct = _library.gnutls_priority_set_direct
652
priority_set_direct.argtypes = [session_t, ctypes.c_char_p,
701
priority_set_direct.argtypes = [ClientSession, ctypes.c_char_p,
653
702
ctypes.POINTER(ctypes.c_char_p)]
654
703
priority_set_direct.restype = _error_code
656
705
init = _library.gnutls_init
657
init.argtypes = [ctypes.POINTER(session_t), ctypes.c_int]
706
init.argtypes = [PointerTo(ClientSession), ctypes.c_int]
658
707
init.restype = _error_code
660
709
set_default_priority = _library.gnutls_set_default_priority
661
set_default_priority.argtypes = [session_t]
710
set_default_priority.argtypes = [ClientSession]
662
711
set_default_priority.restype = _error_code
664
713
record_send = _library.gnutls_record_send
665
record_send.argtypes = [session_t, ctypes.c_void_p,
714
record_send.argtypes = [ClientSession, ctypes.c_void_p,
667
716
record_send.restype = ctypes.c_ssize_t
668
717
record_send.errcheck = _retry_on_error
670
719
certificate_allocate_credentials = (
671
720
_library.gnutls_certificate_allocate_credentials)
672
721
certificate_allocate_credentials.argtypes = [
673
ctypes.POINTER(certificate_credentials_t)]
722
PointerTo(Credentials)]
674
723
certificate_allocate_credentials.restype = _error_code
676
725
certificate_free_credentials = (
677
726
_library.gnutls_certificate_free_credentials)
678
certificate_free_credentials.argtypes = [
679
certificate_credentials_t]
727
certificate_free_credentials.argtypes = [Credentials]
680
728
certificate_free_credentials.restype = None
682
730
handshake_set_private_extensions = (
683
731
_library.gnutls_handshake_set_private_extensions)
684
handshake_set_private_extensions.argtypes = [session_t,
732
handshake_set_private_extensions.argtypes = [ClientSession,
686
734
handshake_set_private_extensions.restype = None
688
736
credentials_set = _library.gnutls_credentials_set
689
credentials_set.argtypes = [session_t, credentials_type_t,
737
credentials_set.argtypes = [ClientSession, credentials_type_t,
738
CastToVoidPointer(Credentials)]
691
739
credentials_set.restype = _error_code
693
741
strerror = _library.gnutls_strerror
712
760
global_set_log_function.restype = None
714
762
deinit = _library.gnutls_deinit
715
deinit.argtypes = [session_t]
763
deinit.argtypes = [ClientSession]
716
764
deinit.restype = None
718
766
handshake = _library.gnutls_handshake
719
handshake.argtypes = [session_t]
720
handshake.restype = _error_code
767
handshake.argtypes = [ClientSession]
768
handshake.restype = ctypes.c_int
721
769
handshake.errcheck = _retry_on_error
723
771
transport_set_ptr = _library.gnutls_transport_set_ptr
724
transport_set_ptr.argtypes = [session_t, transport_ptr_t]
772
transport_set_ptr.argtypes = [ClientSession, transport_ptr_t]
725
773
transport_set_ptr.restype = None
727
775
bye = _library.gnutls_bye
728
bye.argtypes = [session_t, close_request_t]
729
bye.restype = _error_code
776
bye.argtypes = [ClientSession, close_request_t]
777
bye.restype = ctypes.c_int
730
778
bye.errcheck = _retry_on_error
732
780
check_version = _library.gnutls_check_version
2216
class ProxyClient(object):
2217
2273
def __init__(self, child_pipe, key_id, fpr, address):
2218
2274
self._pipe = child_pipe
2219
self._pipe.send(('init', key_id, fpr, address))
2275
self._pipe.send(("init", key_id, fpr, address))
2220
2276
if not self._pipe.recv():
2221
2277
raise KeyError(key_id or fpr)
2223
2279
def __getattribute__(self, name):
2225
2281
return super(ProxyClient, self).__getattribute__(name)
2226
self._pipe.send(('getattr', name))
2282
self._pipe.send(("getattr", name))
2227
2283
data = self._pipe.recv()
2228
if data[0] == 'data':
2284
if data[0] == "data":
2230
if data[0] == 'function':
2286
if data[0] == "function":
2232
2288
def func(*args, **kwargs):
2233
self._pipe.send(('funcall', name, args, kwargs))
2289
self._pipe.send(("funcall", name, args, kwargs))
2234
2290
return self._pipe.recv()[1]
2238
2294
def __setattr__(self, name, value):
2240
2296
return super(ProxyClient, self).__setattr__(name, value)
2241
self._pipe.send(('setattr', name, value))
2297
self._pipe.send(("setattr", name, value))
2244
2300
class ClientHandler(socketserver.BaseRequestHandler, object):
2725
2784
# remove the old hook in favor of the new above hook on
2728
if command == 'funcall':
2787
if command == "funcall":
2729
2788
funcname = request[1]
2730
2789
args = request[2]
2731
2790
kwargs = request[3]
2733
parent_pipe.send(('data', getattr(client_object,
2792
parent_pipe.send(("data", getattr(client_object,
2734
2793
funcname)(*args,
2737
if command == 'getattr':
2796
if command == "getattr":
2738
2797
attrname = request[1]
2739
2798
if isinstance(client_object.__getattribute__(attrname),
2740
collections.Callable):
2741
parent_pipe.send(('function', ))
2799
collections.abc.Callable):
2800
parent_pipe.send(("function", ))
2743
2802
parent_pipe.send((
2744
'data', client_object.__getattribute__(attrname)))
2803
"data", client_object.__getattribute__(attrname)))
2746
if command == 'setattr':
2805
if command == "setattr":
2747
2806
attrname = request[1]
2748
2807
value = request[2]
2749
2808
setattr(client_object, attrname, value)
2754
2813
def rfc3339_duration_to_delta(duration):
2755
2814
"""Parse an RFC 3339 "duration" and return a datetime.timedelta
2757
>>> rfc3339_duration_to_delta("P7D")
2758
datetime.timedelta(7)
2759
>>> rfc3339_duration_to_delta("PT60S")
2760
datetime.timedelta(0, 60)
2761
>>> rfc3339_duration_to_delta("PT60M")
2762
datetime.timedelta(0, 3600)
2763
>>> rfc3339_duration_to_delta("PT24H")
2764
datetime.timedelta(1)
2765
>>> rfc3339_duration_to_delta("P1W")
2766
datetime.timedelta(7)
2767
>>> rfc3339_duration_to_delta("PT5M30S")
2768
datetime.timedelta(0, 330)
2769
>>> rfc3339_duration_to_delta("P1DT3M20S")
2770
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)
2773
2834
# Parsing an RFC 3339 duration with regular expressions is not
2853
2914
def string_to_delta(interval):
2854
2915
"""Parse a string and return a datetime.timedelta
2856
>>> string_to_delta('7d')
2857
datetime.timedelta(7)
2858
>>> string_to_delta('60s')
2859
datetime.timedelta(0, 60)
2860
>>> string_to_delta('60m')
2861
datetime.timedelta(0, 3600)
2862
>>> string_to_delta('24h')
2863
datetime.timedelta(1)
2864
>>> string_to_delta('1w')
2865
datetime.timedelta(7)
2866
>>> string_to_delta('5m 30s')
2867
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)
3616
3676
# Must run before the D-Bus bus name gets deregistered
3620
if __name__ == '__main__':
3680
def should_only_run_tests():
3681
parser = argparse.ArgumentParser(add_help=False)
3682
parser.add_argument("--check", action="store_true")
3683
args, unknown_args = parser.parse_known_args()
3684
run_tests = args.check
3686
# Remove --check argument from sys.argv
3687
sys.argv[1:] = unknown_args
3690
# Add all tests from doctest strings
3691
def load_tests(loader, tests, none):
3693
tests.addTests(doctest.DocTestSuite())
3696
if __name__ == "__main__":
3698
if should_only_run_tests():
3699
# Call using ./mandos --check [--verbose]