196
218
output = subprocess.check_output(["gpgconf"])
197
219
for line in output.splitlines():
198
220
name, text, path = line.split(b":")
202
224
except OSError as e:
203
225
if e.errno != errno.ENOENT:
205
self.gnupgargs = ['--batch',
206
'--homedir', self.tempdir,
227
self.gnupgargs = ["--batch",
228
"--homedir", self.tempdir,
209
231
# Only GPG version 1 has the --no-use-agent option.
210
if self.gpg == "gpg" or self.gpg.endswith("/gpg"):
232
if self.gpg == b"gpg" or self.gpg.endswith(b"/gpg"):
211
233
self.gnupgargs.append("--no-use-agent")
213
235
def __enter__(self):
571
594
# gnutls.strerror()
573
596
if message is None and code is not None:
574
message = gnutls.strerror(code)
597
message = gnutls.strerror(code).decode(
598
"utf-8", errors="replace")
575
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_
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)
640
class ClientSession(With_from_param):
593
641
def __init__(self, socket, credentials=None):
594
self._c_object = gnutls.session_t()
642
self._as_parameter_ = gnutls.session_t()
595
643
gnutls_flags = gnutls.CLIENT
596
644
if gnutls.check_version(b"3.5.6"):
597
645
gnutls_flags |= gnutls.NO_TICKETS
598
646
if gnutls.has_rawpk:
599
647
gnutls_flags |= gnutls.ENABLE_RAWPK
600
gnutls.init(ctypes.byref(self._c_object), gnutls_flags)
648
gnutls.init(self, gnutls_flags)
602
gnutls.set_default_priority(self._c_object)
603
gnutls.transport_set_ptr(self._c_object, socket.fileno())
604
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)
606
653
self.socket = socket
607
654
if credentials is None:
608
655
credentials = gnutls.Credentials()
609
gnutls.credentials_set(self._c_object, credentials.type,
610
ctypes.cast(credentials._c_object,
656
gnutls.credentials_set(self, credentials.type,
612
658
self.credentials = credentials
614
660
def __del__(self):
615
gnutls.deinit(self._c_object)
617
663
def handshake(self):
618
return gnutls.handshake(self._c_object)
664
return gnutls.handshake(self)
620
666
def send(self, data):
621
667
data = bytes(data)
622
668
data_len = len(data)
623
669
while data_len > 0:
624
data_len -= gnutls.record_send(self._c_object,
670
data_len -= gnutls.record_send(self, data[-data_len:],
629
return gnutls.bye(self._c_object, gnutls.SHUT_RDWR)
674
return gnutls.bye(self, gnutls.SHUT_RDWR)
631
676
# Error handling functions
632
677
def _error_code(result):
633
678
"""A function to raise exceptions on errors, suitable
634
for the 'restype' attribute on ctypes functions"""
679
for the "restype" attribute on ctypes functions"""
680
if result >= gnutls.E_SUCCESS:
637
682
if result == gnutls.E_NO_CERTIFICATE_FOUND:
638
683
raise gnutls.CertificateSecurityError(code=result)
639
684
raise gnutls.Error(code=result)
641
def _retry_on_error(result, func, arguments):
686
def _retry_on_error(result, func, arguments,
687
_error_code=_error_code):
642
688
"""A function to retry on some errors, suitable
643
for the 'errcheck' attribute on ctypes functions"""
689
for the "errcheck" attribute on ctypes functions"""
690
while result < gnutls.E_SUCCESS:
645
691
if result not in (gnutls.E_INTERRUPTED, gnutls.E_AGAIN):
646
692
return _error_code(result)
647
693
result = func(*arguments)
654
700
priority_set_direct = _library.gnutls_priority_set_direct
655
priority_set_direct.argtypes = [session_t, ctypes.c_char_p,
701
priority_set_direct.argtypes = [ClientSession, ctypes.c_char_p,
656
702
ctypes.POINTER(ctypes.c_char_p)]
657
703
priority_set_direct.restype = _error_code
659
705
init = _library.gnutls_init
660
init.argtypes = [ctypes.POINTER(session_t), ctypes.c_int]
706
init.argtypes = [PointerTo(ClientSession), ctypes.c_int]
661
707
init.restype = _error_code
663
709
set_default_priority = _library.gnutls_set_default_priority
664
set_default_priority.argtypes = [session_t]
710
set_default_priority.argtypes = [ClientSession]
665
711
set_default_priority.restype = _error_code
667
713
record_send = _library.gnutls_record_send
668
record_send.argtypes = [session_t, ctypes.c_void_p,
714
record_send.argtypes = [ClientSession, ctypes.c_void_p,
670
716
record_send.restype = ctypes.c_ssize_t
671
717
record_send.errcheck = _retry_on_error
673
719
certificate_allocate_credentials = (
674
720
_library.gnutls_certificate_allocate_credentials)
675
721
certificate_allocate_credentials.argtypes = [
676
ctypes.POINTER(certificate_credentials_t)]
722
PointerTo(Credentials)]
677
723
certificate_allocate_credentials.restype = _error_code
679
725
certificate_free_credentials = (
680
726
_library.gnutls_certificate_free_credentials)
681
certificate_free_credentials.argtypes = [
682
certificate_credentials_t]
727
certificate_free_credentials.argtypes = [Credentials]
683
728
certificate_free_credentials.restype = None
685
730
handshake_set_private_extensions = (
686
731
_library.gnutls_handshake_set_private_extensions)
687
handshake_set_private_extensions.argtypes = [session_t,
732
handshake_set_private_extensions.argtypes = [ClientSession,
689
734
handshake_set_private_extensions.restype = None
691
736
credentials_set = _library.gnutls_credentials_set
692
credentials_set.argtypes = [session_t, credentials_type_t,
737
credentials_set.argtypes = [ClientSession, credentials_type_t,
738
CastToVoidPointer(Credentials)]
694
739
credentials_set.restype = _error_code
696
741
strerror = _library.gnutls_strerror
715
760
global_set_log_function.restype = None
717
762
deinit = _library.gnutls_deinit
718
deinit.argtypes = [session_t]
763
deinit.argtypes = [ClientSession]
719
764
deinit.restype = None
721
766
handshake = _library.gnutls_handshake
722
handshake.argtypes = [session_t]
723
handshake.restype = _error_code
767
handshake.argtypes = [ClientSession]
768
handshake.restype = ctypes.c_int
724
769
handshake.errcheck = _retry_on_error
726
771
transport_set_ptr = _library.gnutls_transport_set_ptr
727
transport_set_ptr.argtypes = [session_t, transport_ptr_t]
772
transport_set_ptr.argtypes = [ClientSession, transport_ptr_t]
728
773
transport_set_ptr.restype = None
730
775
bye = _library.gnutls_bye
731
bye.argtypes = [session_t, close_request_t]
732
bye.restype = _error_code
776
bye.argtypes = [ClientSession, close_request_t]
777
bye.restype = ctypes.c_int
733
778
bye.errcheck = _retry_on_error
735
780
check_version = _library.gnutls_check_version
2219
2272
class ProxyClient:
2220
2273
def __init__(self, child_pipe, key_id, fpr, address):
2221
2274
self._pipe = child_pipe
2222
self._pipe.send(('init', key_id, fpr, address))
2275
self._pipe.send(("init", key_id, fpr, address))
2223
2276
if not self._pipe.recv():
2224
2277
raise KeyError(key_id or fpr)
2226
2279
def __getattribute__(self, name):
2228
2281
return super(ProxyClient, self).__getattribute__(name)
2229
self._pipe.send(('getattr', name))
2282
self._pipe.send(("getattr", name))
2230
2283
data = self._pipe.recv()
2231
if data[0] == 'data':
2284
if data[0] == "data":
2233
if data[0] == 'function':
2286
if data[0] == "function":
2235
2288
def func(*args, **kwargs):
2236
self._pipe.send(('funcall', name, args, kwargs))
2289
self._pipe.send(("funcall", name, args, kwargs))
2237
2290
return self._pipe.recv()[1]
2241
2294
def __setattr__(self, name, value):
2243
2296
return super(ProxyClient, self).__setattr__(name, value)
2244
self._pipe.send(('setattr', name, value))
2297
self._pipe.send(("setattr", name, value))
2247
2300
class ClientHandler(socketserver.BaseRequestHandler, object):
2728
2784
# remove the old hook in favor of the new above hook on
2731
if command == 'funcall':
2787
if command == "funcall":
2732
2788
funcname = request[1]
2733
2789
args = request[2]
2734
2790
kwargs = request[3]
2736
parent_pipe.send(('data', getattr(client_object,
2792
parent_pipe.send(("data", getattr(client_object,
2737
2793
funcname)(*args,
2740
if command == 'getattr':
2796
if command == "getattr":
2741
2797
attrname = request[1]
2742
2798
if isinstance(client_object.__getattribute__(attrname),
2743
collections.Callable):
2744
parent_pipe.send(('function', ))
2799
collections.abc.Callable):
2800
parent_pipe.send(("function", ))
2746
2802
parent_pipe.send((
2747
'data', client_object.__getattribute__(attrname)))
2803
"data", client_object.__getattribute__(attrname)))
2749
if command == 'setattr':
2805
if command == "setattr":
2750
2806
attrname = request[1]
2751
2807
value = request[2]
2752
2808
setattr(client_object, attrname, value)
2757
2813
def rfc3339_duration_to_delta(duration):
2758
2814
"""Parse an RFC 3339 "duration" and return a datetime.timedelta
2760
>>> rfc3339_duration_to_delta("P7D")
2761
datetime.timedelta(7)
2762
>>> rfc3339_duration_to_delta("PT60S")
2763
datetime.timedelta(0, 60)
2764
>>> rfc3339_duration_to_delta("PT60M")
2765
datetime.timedelta(0, 3600)
2766
>>> rfc3339_duration_to_delta("PT24H")
2767
datetime.timedelta(1)
2768
>>> rfc3339_duration_to_delta("P1W")
2769
datetime.timedelta(7)
2770
>>> rfc3339_duration_to_delta("PT5M30S")
2771
datetime.timedelta(0, 330)
2772
>>> rfc3339_duration_to_delta("P1DT3M20S")
2773
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)
2776
2834
# Parsing an RFC 3339 duration with regular expressions is not
2856
2914
def string_to_delta(interval):
2857
2915
"""Parse a string and return a datetime.timedelta
2859
>>> string_to_delta('7d')
2860
datetime.timedelta(7)
2861
>>> string_to_delta('60s')
2862
datetime.timedelta(0, 60)
2863
>>> string_to_delta('60m')
2864
datetime.timedelta(0, 3600)
2865
>>> string_to_delta('24h')
2866
datetime.timedelta(1)
2867
>>> string_to_delta('1w')
2868
datetime.timedelta(7)
2869
>>> string_to_delta('5m 30s')
2870
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)
3619
3676
# Must run before the D-Bus bus name gets deregistered
3623
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]