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