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