481
435
.format(self.name)))
484
# Pretend that we have a GnuTLS module
485
class GnuTLS(object):
486
"""This isn't so much a class as it is a module-like namespace.
487
It is instantiated once, and simulates having a GnuTLS module."""
489
_library = ctypes.cdll.LoadLibrary(
490
ctypes.util.find_library("gnutls"))
491
_need_version = b"3.3.0"
493
# Need to use class name "GnuTLS" here, since this method is
494
# called before the assignment to the "gnutls" global variable
496
if GnuTLS.check_version(self._need_version) is None:
497
raise GnuTLS.Error("Needs GnuTLS {} or later"
498
.format(self._need_version))
500
# Unless otherwise indicated, the constants and types below are
501
# all from the gnutls/gnutls.h C header file.
511
E_NO_CERTIFICATE_FOUND = -49
512
OPENPGP_FMT_RAW = 0 # gnutls/openpgp.h
515
class session_int(ctypes.Structure):
517
session_t = ctypes.POINTER(session_int)
518
class certificate_credentials_st(ctypes.Structure):
520
certificate_credentials_t = ctypes.POINTER(
521
certificate_credentials_st)
522
certificate_type_t = ctypes.c_int
523
class datum_t(ctypes.Structure):
524
_fields_ = [('data', ctypes.POINTER(ctypes.c_ubyte)),
525
('size', ctypes.c_uint)]
526
class openpgp_crt_int(ctypes.Structure):
528
openpgp_crt_t = ctypes.POINTER(openpgp_crt_int)
529
openpgp_crt_fmt_t = ctypes.c_int # gnutls/openpgp.h
530
log_func = ctypes.CFUNCTYPE(None, ctypes.c_int, ctypes.c_char_p)
531
credentials_type_t = ctypes.c_int
532
transport_ptr_t = ctypes.c_void_p
533
close_request_t = ctypes.c_int
536
class Error(Exception):
537
# We need to use the class name "GnuTLS" here, since this
538
# exception might be raised from within GnuTLS.__init__,
539
# which is called before the assignment to the "gnutls"
540
# global variable has happened.
541
def __init__(self, message = None, code = None, args=()):
542
# Default usage is by a message string, but if a return
543
# code is passed, convert it to a string with
546
if message is None and code is not None:
547
message = GnuTLS.strerror(code)
548
return super(GnuTLS.Error, self).__init__(
551
class CertificateSecurityError(Error):
555
class Credentials(object):
557
self._c_object = gnutls.certificate_credentials_t()
558
gnutls.certificate_allocate_credentials(
559
ctypes.byref(self._c_object))
560
self.type = gnutls.CRD_CERTIFICATE
563
gnutls.certificate_free_credentials(self._c_object)
565
class ClientSession(object):
566
def __init__(self, socket, credentials = None):
567
self._c_object = gnutls.session_t()
568
gnutls.init(ctypes.byref(self._c_object), gnutls.CLIENT)
569
gnutls.set_default_priority(self._c_object)
570
gnutls.transport_set_ptr(self._c_object, socket.fileno())
571
gnutls.handshake_set_private_extensions(self._c_object,
574
if credentials is None:
575
credentials = gnutls.Credentials()
576
gnutls.credentials_set(self._c_object, credentials.type,
577
ctypes.cast(credentials._c_object,
579
self.credentials = credentials
582
gnutls.deinit(self._c_object)
585
return gnutls.handshake(self._c_object)
587
def send(self, data):
591
data_len -= gnutls.record_send(self._c_object,
596
return gnutls.bye(self._c_object, gnutls.SHUT_RDWR)
598
# Error handling functions
599
def _error_code(result):
600
"""A function to raise exceptions on errors, suitable
601
for the 'restype' attribute on ctypes functions"""
604
if result == gnutls.E_NO_CERTIFICATE_FOUND:
605
raise gnutls.CertificateSecurityError(code = result)
606
raise gnutls.Error(code = result)
608
def _retry_on_error(result, func, arguments):
609
"""A function to retry on some errors, suitable
610
for the 'errcheck' attribute on ctypes functions"""
612
if result not in (gnutls.E_INTERRUPTED, gnutls.E_AGAIN):
613
return _error_code(result)
614
result = func(*arguments)
617
# Unless otherwise indicated, the function declarations below are
618
# all from the gnutls/gnutls.h C header file.
621
priority_set_direct = _library.gnutls_priority_set_direct
622
priority_set_direct.argtypes = [session_t, ctypes.c_char_p,
623
ctypes.POINTER(ctypes.c_char_p)]
624
priority_set_direct.restype = _error_code
626
init = _library.gnutls_init
627
init.argtypes = [ctypes.POINTER(session_t), ctypes.c_int]
628
init.restype = _error_code
630
set_default_priority = _library.gnutls_set_default_priority
631
set_default_priority.argtypes = [session_t]
632
set_default_priority.restype = _error_code
634
record_send = _library.gnutls_record_send
635
record_send.argtypes = [session_t, ctypes.c_void_p,
637
record_send.restype = ctypes.c_ssize_t
638
record_send.errcheck = _retry_on_error
640
certificate_allocate_credentials = (
641
_library.gnutls_certificate_allocate_credentials)
642
certificate_allocate_credentials.argtypes = [
643
ctypes.POINTER(certificate_credentials_t)]
644
certificate_allocate_credentials.restype = _error_code
646
certificate_free_credentials = (
647
_library.gnutls_certificate_free_credentials)
648
certificate_free_credentials.argtypes = [certificate_credentials_t]
649
certificate_free_credentials.restype = None
651
handshake_set_private_extensions = (
652
_library.gnutls_handshake_set_private_extensions)
653
handshake_set_private_extensions.argtypes = [session_t,
655
handshake_set_private_extensions.restype = None
657
credentials_set = _library.gnutls_credentials_set
658
credentials_set.argtypes = [session_t, credentials_type_t,
660
credentials_set.restype = _error_code
662
strerror = _library.gnutls_strerror
663
strerror.argtypes = [ctypes.c_int]
664
strerror.restype = ctypes.c_char_p
666
certificate_type_get = _library.gnutls_certificate_type_get
667
certificate_type_get.argtypes = [session_t]
668
certificate_type_get.restype = _error_code
670
certificate_get_peers = _library.gnutls_certificate_get_peers
671
certificate_get_peers.argtypes = [session_t,
672
ctypes.POINTER(ctypes.c_uint)]
673
certificate_get_peers.restype = ctypes.POINTER(datum_t)
675
global_set_log_level = _library.gnutls_global_set_log_level
676
global_set_log_level.argtypes = [ctypes.c_int]
677
global_set_log_level.restype = None
679
global_set_log_function = _library.gnutls_global_set_log_function
680
global_set_log_function.argtypes = [log_func]
681
global_set_log_function.restype = None
683
deinit = _library.gnutls_deinit
684
deinit.argtypes = [session_t]
685
deinit.restype = None
687
handshake = _library.gnutls_handshake
688
handshake.argtypes = [session_t]
689
handshake.restype = _error_code
690
handshake.errcheck = _retry_on_error
692
transport_set_ptr = _library.gnutls_transport_set_ptr
693
transport_set_ptr.argtypes = [session_t, transport_ptr_t]
694
transport_set_ptr.restype = None
696
bye = _library.gnutls_bye
697
bye.argtypes = [session_t, close_request_t]
698
bye.restype = _error_code
699
bye.errcheck = _retry_on_error
701
check_version = _library.gnutls_check_version
702
check_version.argtypes = [ctypes.c_char_p]
703
check_version.restype = ctypes.c_char_p
705
# All the function declarations below are from gnutls/openpgp.h
707
openpgp_crt_init = _library.gnutls_openpgp_crt_init
708
openpgp_crt_init.argtypes = [ctypes.POINTER(openpgp_crt_t)]
709
openpgp_crt_init.restype = _error_code
711
openpgp_crt_import = _library.gnutls_openpgp_crt_import
712
openpgp_crt_import.argtypes = [openpgp_crt_t,
713
ctypes.POINTER(datum_t),
715
openpgp_crt_import.restype = _error_code
717
openpgp_crt_verify_self = _library.gnutls_openpgp_crt_verify_self
718
openpgp_crt_verify_self.argtypes = [openpgp_crt_t, ctypes.c_uint,
719
ctypes.POINTER(ctypes.c_uint)]
720
openpgp_crt_verify_self.restype = _error_code
722
openpgp_crt_deinit = _library.gnutls_openpgp_crt_deinit
723
openpgp_crt_deinit.argtypes = [openpgp_crt_t]
724
openpgp_crt_deinit.restype = None
726
openpgp_crt_get_fingerprint = (
727
_library.gnutls_openpgp_crt_get_fingerprint)
728
openpgp_crt_get_fingerprint.argtypes = [openpgp_crt_t,
732
openpgp_crt_get_fingerprint.restype = _error_code
734
# Remove non-public functions
735
del _error_code, _retry_on_error
736
# Create the global "gnutls" object, simulating a module
739
438
def call_pipe(connection, # : multiprocessing.Connection
740
439
func, *args, **kwargs):
741
440
"""This function is meant to be called by multiprocessing.Process
1200
896
for name, athing in
1201
897
inspect.getmembers(cls, self._is_dbus_thing(thing)))
1203
@dbus.service.method(dbus.INTROSPECTABLE_IFACE,
1204
out_signature = "s",
1205
path_keyword = 'object_path',
1206
connection_keyword = 'connection')
1207
def Introspect(self, object_path, connection):
1208
"""Overloading of standard D-Bus method.
1210
Inserts annotation tags on methods and signals.
1212
xmlstring = dbus.service.Object.Introspect(self, object_path,
1215
document = xml.dom.minidom.parseString(xmlstring)
1217
for if_tag in document.getElementsByTagName("interface"):
1218
# Add annotation tags
1219
for typ in ("method", "signal"):
1220
for tag in if_tag.getElementsByTagName(typ):
1222
for name, prop in (self.
1223
_get_all_dbus_things(typ)):
1224
if (name == tag.getAttribute("name")
1225
and prop._dbus_interface
1226
== if_tag.getAttribute("name")):
1227
annots.update(getattr(
1228
prop, "_dbus_annotations", {}))
1229
for name, value in annots.items():
1230
ann_tag = document.createElement(
1232
ann_tag.setAttribute("name", name)
1233
ann_tag.setAttribute("value", value)
1234
tag.appendChild(ann_tag)
1235
# Add interface annotation tags
1236
for annotation, value in dict(
1237
itertools.chain.from_iterable(
1238
annotations().items()
1239
for name, annotations
1240
in self._get_all_dbus_things("interface")
1241
if name == if_tag.getAttribute("name")
1243
ann_tag = document.createElement("annotation")
1244
ann_tag.setAttribute("name", annotation)
1245
ann_tag.setAttribute("value", value)
1246
if_tag.appendChild(ann_tag)
1247
# Fix argument name for the Introspect method itself
1248
if (if_tag.getAttribute("name")
1249
== dbus.INTROSPECTABLE_IFACE):
1250
for cn in if_tag.getElementsByTagName("method"):
1251
if cn.getAttribute("name") == "Introspect":
1252
for arg in cn.getElementsByTagName("arg"):
1253
if (arg.getAttribute("direction")
1255
arg.setAttribute("name",
1257
xmlstring = document.toxml("utf-8")
1259
except (AttributeError, xml.dom.DOMException,
1260
xml.parsers.expat.ExpatError) as error:
1261
logger.error("Failed to override Introspection method",
1266
class DBusObjectWithProperties(DBusObjectWithAnnotations):
1267
"""A D-Bus object with properties.
1269
Classes inheriting from this can use the dbus_service_property
1270
decorator to expose methods as D-Bus properties. It exposes the
1271
standard Get(), Set(), and GetAll() methods on the D-Bus.
1274
899
def _get_dbus_property(self, interface_name, property_name):
1275
900
"""Returns a bound method if one exists which is a D-Bus
1276
901
property with the specified name and interface.
1391
1006
if prop._dbus_interface
1392
1007
== if_tag.getAttribute("name")):
1393
1008
if_tag.appendChild(tag)
1394
# Add annotation tags for properties
1395
for tag in if_tag.getElementsByTagName("property"):
1397
for name, prop in self._get_all_dbus_things(
1399
if (name == tag.getAttribute("name")
1400
and prop._dbus_interface
1401
== if_tag.getAttribute("name")):
1402
annots.update(getattr(
1403
prop, "_dbus_annotations", {}))
1404
for name, value in annots.items():
1405
ann_tag = document.createElement(
1407
ann_tag.setAttribute("name", name)
1408
ann_tag.setAttribute("value", value)
1409
tag.appendChild(ann_tag)
1009
# Add annotation tags
1010
for typ in ("method", "signal", "property"):
1011
for tag in if_tag.getElementsByTagName(typ):
1013
for name, prop in (self.
1014
_get_all_dbus_things(typ)):
1015
if (name == tag.getAttribute("name")
1016
and prop._dbus_interface
1017
== if_tag.getAttribute("name")):
1018
annots.update(getattr(
1019
prop, "_dbus_annotations", {}))
1020
for name, value in annots.items():
1021
ann_tag = document.createElement(
1023
ann_tag.setAttribute("name", name)
1024
ann_tag.setAttribute("value", value)
1025
tag.appendChild(ann_tag)
1026
# Add interface annotation tags
1027
for annotation, value in dict(
1028
itertools.chain.from_iterable(
1029
annotations().items()
1030
for name, annotations
1031
in self._get_all_dbus_things("interface")
1032
if name == if_tag.getAttribute("name")
1034
ann_tag = document.createElement("annotation")
1035
ann_tag.setAttribute("name", annotation)
1036
ann_tag.setAttribute("value", value)
1037
if_tag.appendChild(ann_tag)
1410
1038
# Add the names to the return values for the
1411
1039
# "org.freedesktop.DBus.Properties" methods
1412
1040
if (if_tag.getAttribute("name")
1430
1058
exc_info=error)
1431
1059
return xmlstring
1434
dbus.OBJECT_MANAGER_IFACE
1435
except AttributeError:
1436
dbus.OBJECT_MANAGER_IFACE = "org.freedesktop.DBus.ObjectManager"
1438
class DBusObjectWithObjectManager(DBusObjectWithAnnotations):
1439
"""A D-Bus object with an ObjectManager.
1441
Classes inheriting from this exposes the standard
1442
GetManagedObjects call and the InterfacesAdded and
1443
InterfacesRemoved signals on the standard
1444
"org.freedesktop.DBus.ObjectManager" interface.
1446
Note: No signals are sent automatically; they must be sent
1449
@dbus.service.method(dbus.OBJECT_MANAGER_IFACE,
1450
out_signature = "a{oa{sa{sv}}}")
1451
def GetManagedObjects(self):
1452
"""This function must be overridden"""
1453
raise NotImplementedError()
1455
@dbus.service.signal(dbus.OBJECT_MANAGER_IFACE,
1456
signature = "oa{sa{sv}}")
1457
def InterfacesAdded(self, object_path, interfaces_and_properties):
1460
@dbus.service.signal(dbus.OBJECT_MANAGER_IFACE, signature = "oas")
1461
def InterfacesRemoved(self, object_path, interfaces):
1464
@dbus.service.method(dbus.INTROSPECTABLE_IFACE,
1465
out_signature = "s",
1466
path_keyword = 'object_path',
1467
connection_keyword = 'connection')
1468
def Introspect(self, object_path, connection):
1469
"""Overloading of standard D-Bus method.
1471
Override return argument name of GetManagedObjects to be
1472
"objpath_interfaces_and_properties"
1474
xmlstring = DBusObjectWithAnnotations.Introspect(self,
1478
document = xml.dom.minidom.parseString(xmlstring)
1480
for if_tag in document.getElementsByTagName("interface"):
1481
# Fix argument name for the GetManagedObjects method
1482
if (if_tag.getAttribute("name")
1483
== dbus.OBJECT_MANAGER_IFACE):
1484
for cn in if_tag.getElementsByTagName("method"):
1485
if (cn.getAttribute("name")
1486
== "GetManagedObjects"):
1487
for arg in cn.getElementsByTagName("arg"):
1488
if (arg.getAttribute("direction")
1492
"objpath_interfaces"
1494
xmlstring = document.toxml("utf-8")
1496
except (AttributeError, xml.dom.DOMException,
1497
xml.parsers.expat.ExpatError) as error:
1498
logger.error("Failed to override Introspection method",
1502
1062
def datetime_to_dbus(dt, variant_level=0):
1503
1063
"""Convert a UTC datetime.datetime() to a D-Bus type."""
2312
1883
def fingerprint(openpgp):
2313
1884
"Convert an OpenPGP bytestring to a hexdigit fingerprint"
2314
1885
# New GnuTLS "datum" with the OpenPGP public key
2315
datum = gnutls.datum_t(
1886
datum = gnutls.library.types.gnutls_datum_t(
2316
1887
ctypes.cast(ctypes.c_char_p(openpgp),
2317
1888
ctypes.POINTER(ctypes.c_ubyte)),
2318
1889
ctypes.c_uint(len(openpgp)))
2319
1890
# New empty GnuTLS certificate
2320
crt = gnutls.openpgp_crt_t()
2321
gnutls.openpgp_crt_init(ctypes.byref(crt))
1891
crt = gnutls.library.types.gnutls_openpgp_crt_t()
1892
gnutls.library.functions.gnutls_openpgp_crt_init(
2322
1894
# Import the OpenPGP public key into the certificate
2323
gnutls.openpgp_crt_import(crt, ctypes.byref(datum),
2324
gnutls.OPENPGP_FMT_RAW)
1895
gnutls.library.functions.gnutls_openpgp_crt_import(
1896
crt, ctypes.byref(datum),
1897
gnutls.library.constants.GNUTLS_OPENPGP_FMT_RAW)
2325
1898
# Verify the self signature in the key
2326
1899
crtverify = ctypes.c_uint()
2327
gnutls.openpgp_crt_verify_self(crt, 0,
2328
ctypes.byref(crtverify))
1900
gnutls.library.functions.gnutls_openpgp_crt_verify_self(
1901
crt, 0, ctypes.byref(crtverify))
2329
1902
if crtverify.value != 0:
2330
gnutls.openpgp_crt_deinit(crt)
2331
raise gnutls.CertificateSecurityError("Verify failed")
1903
gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
1904
raise gnutls.errors.CertificateSecurityError(
2332
1906
# New buffer for the fingerprint
2333
1907
buf = ctypes.create_string_buffer(20)
2334
1908
buf_len = ctypes.c_size_t()
2335
1909
# Get the fingerprint from the certificate into the buffer
2336
gnutls.openpgp_crt_get_fingerprint(crt, ctypes.byref(buf),
2337
ctypes.byref(buf_len))
1910
gnutls.library.functions.gnutls_openpgp_crt_get_fingerprint(
1911
crt, ctypes.byref(buf), ctypes.byref(buf_len))
2338
1912
# Deinit the certificate
2339
gnutls.openpgp_crt_deinit(crt)
1913
gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
2340
1914
# Convert the buffer to a Python bytestring
2341
1915
fpr = ctypes.string_at(buf, buf_len.value)
2342
1916
# Convert the bytestring to hexadecimal notation
3231
@dbus_annotations({"org.freedesktop.DBus.Deprecated":
3233
2761
@dbus.service.signal(_interface, signature="os")
3234
2762
def ClientRemoved(self, objpath, name):
3238
@dbus_annotations({"org.freedesktop.DBus.Deprecated":
3240
2766
@dbus.service.method(_interface, out_signature="ao")
3241
2767
def GetAllClients(self):
3243
2769
return dbus.Array(c.dbus_object_path for c in
3244
tcp_server.clients.values())
2770
tcp_server.clients.itervalues())
3246
@dbus_annotations({"org.freedesktop.DBus.Deprecated":
3248
2772
@dbus.service.method(_interface,
3249
2773
out_signature="a{oa{sv}}")
3250
2774
def GetAllClientsWithProperties(self):
3252
2776
return dbus.Dictionary(
3253
{ c.dbus_object_path: c.GetAll(
3254
"se.recompile.Mandos.Client")
3255
for c in tcp_server.clients.values() },
2777
{ c.dbus_object_path: c.GetAll("")
2778
for c in tcp_server.clients.itervalues() },
3256
2779
signature="oa{sv}")
3258
2781
@dbus.service.method(_interface, in_signature="o")
3259
2782
def RemoveClient(self, object_path):
3261
for c in tcp_server.clients.values():
2784
for c in tcp_server.clients.itervalues():
3262
2785
if c.dbus_object_path == object_path:
3263
2786
del tcp_server.clients[c.name]
3264
2787
c.remove_from_connection()
3265
# Don't signal the disabling
2788
# Don't signal anything except ClientRemoved
3266
2789
c.disable(quiet=True)
3267
# Emit D-Bus signal for removal
3268
self.client_removed_signal(c)
2791
self.ClientRemoved(object_path, c.name)
3270
2793
raise KeyError(object_path)
3274
@dbus.service.method(dbus.OBJECT_MANAGER_IFACE,
3275
out_signature = "a{oa{sa{sv}}}")
3276
def GetManagedObjects(self):
3278
return dbus.Dictionary(
3279
{ client.dbus_object_path:
3281
{ interface: client.GetAll(interface)
3283
client._get_all_interface_names()})
3284
for client in tcp_server.clients.values()})
3286
def client_added_signal(self, client):
3287
"""Send the new standard signal and the old signal"""
3289
# New standard signal
3290
self.InterfacesAdded(
3291
client.dbus_object_path,
3293
{ interface: client.GetAll(interface)
3295
client._get_all_interface_names()}))
3297
self.ClientAdded(client.dbus_object_path)
3299
def client_removed_signal(self, client):
3300
"""Send the new standard signal and the old signal"""
3302
# New standard signal
3303
self.InterfacesRemoved(
3304
client.dbus_object_path,
3305
client._get_all_interface_names())
3307
self.ClientRemoved(client.dbus_object_path,
3310
2797
mandos_dbus_service = MandosDBusService()