218
189
output = subprocess.check_output(["gpgconf"])
219
190
for line in output.splitlines():
220
191
name, text, path = line.split(b":")
224
195
except OSError as e:
225
196
if e.errno != errno.ENOENT:
227
self.gnupgargs = ["--batch",
228
"--homedir", self.tempdir,
198
self.gnupgargs = ['--batch',
199
'--homedir', self.tempdir,
231
202
# Only GPG version 1 has the --no-use-agent option.
232
if self.gpg == b"gpg" or self.gpg.endswith(b"/gpg"):
203
if self.gpg == "gpg" or self.gpg.endswith("/gpg"):
233
204
self.gnupgargs.append("--no-use-agent")
235
206
def __enter__(self):
594
564
# gnutls.strerror()
596
566
if message is None and code is not None:
597
message = gnutls.strerror(code).decode(
598
"utf-8", errors="replace")
567
message = gnutls.strerror(code)
599
568
return super(gnutls.Error, self).__init__(
602
571
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):
575
class Credentials(object):
632
576
def __init__(self):
633
self._as_parameter_ = gnutls.certificate_credentials_t()
634
gnutls.certificate_allocate_credentials(self)
577
self._c_object = gnutls.certificate_credentials_t()
578
gnutls.certificate_allocate_credentials(
579
ctypes.byref(self._c_object))
635
580
self.type = gnutls.CRD_CERTIFICATE
637
582
def __del__(self):
638
gnutls.certificate_free_credentials(self)
583
gnutls.certificate_free_credentials(self._c_object)
640
class ClientSession(With_from_param):
585
class ClientSession(object):
641
586
def __init__(self, socket, credentials=None):
642
self._as_parameter_ = gnutls.session_t()
587
self._c_object = gnutls.session_t()
643
588
gnutls_flags = gnutls.CLIENT
644
if gnutls.check_version(b"3.5.6"):
589
if gnutls.check_version("3.5.6"):
645
590
gnutls_flags |= gnutls.NO_TICKETS
646
591
if gnutls.has_rawpk:
647
592
gnutls_flags |= gnutls.ENABLE_RAWPK
648
gnutls.init(self, gnutls_flags)
593
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)
595
gnutls.set_default_priority(self._c_object)
596
gnutls.transport_set_ptr(self._c_object, socket.fileno())
597
gnutls.handshake_set_private_extensions(self._c_object,
653
599
self.socket = socket
654
600
if credentials is None:
655
601
credentials = gnutls.Credentials()
656
gnutls.credentials_set(self, credentials.type,
602
gnutls.credentials_set(self._c_object, credentials.type,
603
ctypes.cast(credentials._c_object,
658
605
self.credentials = credentials
660
607
def __del__(self):
608
gnutls.deinit(self._c_object)
663
610
def handshake(self):
664
return gnutls.handshake(self)
611
return gnutls.handshake(self._c_object)
666
613
def send(self, data):
667
614
data = bytes(data)
668
615
data_len = len(data)
669
616
while data_len > 0:
670
data_len -= gnutls.record_send(self, data[-data_len:],
617
data_len -= gnutls.record_send(self._c_object,
674
return gnutls.bye(self, gnutls.SHUT_RDWR)
622
return gnutls.bye(self._c_object, gnutls.SHUT_RDWR)
676
624
# Error handling functions
677
625
def _error_code(result):
678
626
"""A function to raise exceptions on errors, suitable
679
for the "restype" attribute on ctypes functions"""
680
if result >= gnutls.E_SUCCESS:
627
for the 'restype' attribute on ctypes functions"""
682
630
if result == gnutls.E_NO_CERTIFICATE_FOUND:
683
631
raise gnutls.CertificateSecurityError(code=result)
684
632
raise gnutls.Error(code=result)
686
def _retry_on_error(result, func, arguments,
687
_error_code=_error_code):
634
def _retry_on_error(result, func, arguments):
688
635
"""A function to retry on some errors, suitable
689
for the "errcheck" attribute on ctypes functions"""
690
while result < gnutls.E_SUCCESS:
636
for the 'errcheck' attribute on ctypes functions"""
691
638
if result not in (gnutls.E_INTERRUPTED, gnutls.E_AGAIN):
692
639
return _error_code(result)
693
640
result = func(*arguments)
700
647
priority_set_direct = _library.gnutls_priority_set_direct
701
priority_set_direct.argtypes = [ClientSession, ctypes.c_char_p,
648
priority_set_direct.argtypes = [session_t, ctypes.c_char_p,
702
649
ctypes.POINTER(ctypes.c_char_p)]
703
650
priority_set_direct.restype = _error_code
705
652
init = _library.gnutls_init
706
init.argtypes = [PointerTo(ClientSession), ctypes.c_int]
653
init.argtypes = [ctypes.POINTER(session_t), ctypes.c_int]
707
654
init.restype = _error_code
709
656
set_default_priority = _library.gnutls_set_default_priority
710
set_default_priority.argtypes = [ClientSession]
657
set_default_priority.argtypes = [session_t]
711
658
set_default_priority.restype = _error_code
713
660
record_send = _library.gnutls_record_send
714
record_send.argtypes = [ClientSession, ctypes.c_void_p,
661
record_send.argtypes = [session_t, ctypes.c_void_p,
716
663
record_send.restype = ctypes.c_ssize_t
717
664
record_send.errcheck = _retry_on_error
719
666
certificate_allocate_credentials = (
720
667
_library.gnutls_certificate_allocate_credentials)
721
668
certificate_allocate_credentials.argtypes = [
722
PointerTo(Credentials)]
669
ctypes.POINTER(certificate_credentials_t)]
723
670
certificate_allocate_credentials.restype = _error_code
725
672
certificate_free_credentials = (
726
673
_library.gnutls_certificate_free_credentials)
727
certificate_free_credentials.argtypes = [Credentials]
674
certificate_free_credentials.argtypes = [
675
certificate_credentials_t]
728
676
certificate_free_credentials.restype = None
730
678
handshake_set_private_extensions = (
731
679
_library.gnutls_handshake_set_private_extensions)
732
handshake_set_private_extensions.argtypes = [ClientSession,
680
handshake_set_private_extensions.argtypes = [session_t,
734
682
handshake_set_private_extensions.restype = None
736
684
credentials_set = _library.gnutls_credentials_set
737
credentials_set.argtypes = [ClientSession, credentials_type_t,
738
CastToVoidPointer(Credentials)]
685
credentials_set.argtypes = [session_t, credentials_type_t,
739
687
credentials_set.restype = _error_code
741
689
strerror = _library.gnutls_strerror
760
708
global_set_log_function.restype = None
762
710
deinit = _library.gnutls_deinit
763
deinit.argtypes = [ClientSession]
711
deinit.argtypes = [session_t]
764
712
deinit.restype = None
766
714
handshake = _library.gnutls_handshake
767
handshake.argtypes = [ClientSession]
768
handshake.restype = ctypes.c_int
715
handshake.argtypes = [session_t]
716
handshake.restype = _error_code
769
717
handshake.errcheck = _retry_on_error
771
719
transport_set_ptr = _library.gnutls_transport_set_ptr
772
transport_set_ptr.argtypes = [ClientSession, transport_ptr_t]
720
transport_set_ptr.argtypes = [session_t, transport_ptr_t]
773
721
transport_set_ptr.restype = None
775
723
bye = _library.gnutls_bye
776
bye.argtypes = [ClientSession, close_request_t]
777
bye.restype = ctypes.c_int
724
bye.argtypes = [session_t, close_request_t]
725
bye.restype = _error_code
778
726
bye.errcheck = _retry_on_error
780
728
check_version = _library.gnutls_check_version
2211
class ProxyClient(object):
2273
2212
def __init__(self, child_pipe, key_id, fpr, address):
2274
2213
self._pipe = child_pipe
2275
self._pipe.send(("init", key_id, fpr, address))
2214
self._pipe.send(('init', key_id, fpr, address))
2276
2215
if not self._pipe.recv():
2277
2216
raise KeyError(key_id or fpr)
2279
2218
def __getattribute__(self, name):
2281
2220
return super(ProxyClient, self).__getattribute__(name)
2282
self._pipe.send(("getattr", name))
2221
self._pipe.send(('getattr', name))
2283
2222
data = self._pipe.recv()
2284
if data[0] == "data":
2223
if data[0] == 'data':
2286
if data[0] == "function":
2225
if data[0] == 'function':
2288
2227
def func(*args, **kwargs):
2289
self._pipe.send(("funcall", name, args, kwargs))
2228
self._pipe.send(('funcall', name, args, kwargs))
2290
2229
return self._pipe.recv()[1]
2294
2233
def __setattr__(self, name, value):
2296
2235
return super(ProxyClient, self).__setattr__(name, value)
2297
self._pipe.send(("setattr", name, value))
2236
self._pipe.send(('setattr', name, value))
2300
2239
class ClientHandler(socketserver.BaseRequestHandler, object):
2813
2749
def rfc3339_duration_to_delta(duration):
2814
2750
"""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)
2752
>>> rfc3339_duration_to_delta("P7D")
2753
datetime.timedelta(7)
2754
>>> rfc3339_duration_to_delta("PT60S")
2755
datetime.timedelta(0, 60)
2756
>>> rfc3339_duration_to_delta("PT60M")
2757
datetime.timedelta(0, 3600)
2758
>>> rfc3339_duration_to_delta("PT24H")
2759
datetime.timedelta(1)
2760
>>> rfc3339_duration_to_delta("P1W")
2761
datetime.timedelta(7)
2762
>>> rfc3339_duration_to_delta("PT5M30S")
2763
datetime.timedelta(0, 330)
2764
>>> rfc3339_duration_to_delta("P1DT3M20S")
2765
datetime.timedelta(1, 200)
2834
2768
# Parsing an RFC 3339 duration with regular expressions is not
2914
2848
def string_to_delta(interval):
2915
2849
"""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)
2851
>>> string_to_delta('7d')
2852
datetime.timedelta(7)
2853
>>> string_to_delta('60s')
2854
datetime.timedelta(0, 60)
2855
>>> string_to_delta('60m')
2856
datetime.timedelta(0, 3600)
2857
>>> string_to_delta('24h')
2858
datetime.timedelta(1)
2859
>>> string_to_delta('1w')
2860
datetime.timedelta(7)
2861
>>> string_to_delta('5m 30s')
2862
datetime.timedelta(0, 330)
3676
3611
# 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]
3615
if __name__ == '__main__':