290
300
if u"secret" in config:
291
301
self.secret = config[u"secret"].decode(u"base64")
292
302
elif u"secfile" in config:
293
with closing(open(os.path.expanduser
295
(config[u"secfile"])))) as secfile:
303
with open(os.path.expanduser(os.path.expandvars
304
(config[u"secfile"])),
296
306
self.secret = secfile.read()
308
#XXX Need to allow secret on demand!
298
309
raise TypeError(u"No secret or secfile for client %s"
300
311
self.host = config.get(u"host", u"")
312
323
self.checker_command = config[u"checker"]
313
324
self.current_checker_command = None
314
325
self.last_connect = None
326
self.approvals_pending = 0
327
self._approved = None
328
self.approved_by_default = config.get(u"approved_by_default",
330
self.approved_delay = string_to_delta(
331
config[u"approved_delay"])
332
self.approved_duration = string_to_delta(
333
config[u"approved_duration"])
334
self.changedstate = multiprocessing_manager.Condition(multiprocessing_manager.Lock())
336
def send_changedstate(self):
337
self.changedstate.acquire()
338
self.changedstate.notify_all()
339
self.changedstate.release()
316
341
def enable(self):
317
342
"""Start this client's checker and timeout hooks"""
318
343
if getattr(self, u"enabled", False):
319
344
# Already enabled
346
self.send_changedstate()
321
347
self.last_enabled = datetime.datetime.utcnow()
322
348
# Schedule a new checker to be started an 'interval' from now,
323
349
# and every interval from then on.
324
350
self.checker_initiator_tag = (gobject.timeout_add
325
351
(self.interval_milliseconds(),
326
352
self.start_checker))
327
# Also start a new checker *right now*.
329
353
# Schedule a disable() when 'timeout' has passed
330
354
self.disable_initiator_tag = (gobject.timeout_add
331
355
(self.timeout_milliseconds(),
333
357
self.enabled = True
358
# Also start a new checker *right now*.
361
def disable(self, quiet=True):
336
362
"""Disable this client."""
337
363
if not getattr(self, "enabled", False):
339
logger.info(u"Disabling client %s", self.name)
366
self.send_changedstate()
368
logger.info(u"Disabling client %s", self.name)
340
369
if getattr(self, u"disable_initiator_tag", False):
341
370
gobject.source_remove(self.disable_initiator_tag)
342
371
self.disable_initiator_tag = None
466
495
logger.debug(u"Stopping checker for %(name)s", vars(self))
468
497
os.kill(self.checker.pid, signal.SIGTERM)
470
499
#if self.checker.poll() is None:
471
500
# os.kill(self.checker.pid, signal.SIGKILL)
472
501
except OSError, error:
473
502
if error.errno != errno.ESRCH: # No such process
475
504
self.checker = None
477
def still_valid(self):
478
"""Has the timeout not yet passed for this client?"""
479
if not getattr(self, u"enabled", False):
481
now = datetime.datetime.utcnow()
482
if self.last_checked_ok is None:
483
return now < (self.created + self.timeout)
485
return now < (self.last_checked_ok + self.timeout)
488
506
def dbus_service_property(dbus_interface, signature=u"v",
489
507
access=u"readwrite", byte_arrays=False):
497
515
dbus.service.method, except there is only "signature", since the
498
516
type from Get() and the type sent to Set() is the same.
518
# Encoding deeply encoded byte arrays is not supported yet by the
519
# "Set" method, so we fail early here:
520
if byte_arrays and signature != u"ay":
521
raise ValueError(u"Byte arrays not supported for non-'ay'"
522
u" signature %r" % signature)
500
523
def decorator(func):
501
524
func._dbus_is_property = True
502
525
func._dbus_interface = dbus_interface
625
652
"""Standard D-Bus method, overloaded to insert property tags.
627
654
xmlstring = dbus.service.Object.Introspect(self, object_path,
629
document = xml.dom.minidom.parseString(xmlstring)
631
def make_tag(document, name, prop):
632
e = document.createElement(u"property")
633
e.setAttribute(u"name", name)
634
e.setAttribute(u"type", prop._dbus_signature)
635
e.setAttribute(u"access", prop._dbus_access)
637
for if_tag in document.getElementsByTagName(u"interface"):
638
for tag in (make_tag(document, name, prop)
640
in self._get_all_dbus_properties()
641
if prop._dbus_interface
642
== if_tag.getAttribute(u"name")):
643
if_tag.appendChild(tag)
644
xmlstring = document.toxml(u"utf-8")
657
document = xml.dom.minidom.parseString(xmlstring)
658
def make_tag(document, name, prop):
659
e = document.createElement(u"property")
660
e.setAttribute(u"name", name)
661
e.setAttribute(u"type", prop._dbus_signature)
662
e.setAttribute(u"access", prop._dbus_access)
664
for if_tag in document.getElementsByTagName(u"interface"):
665
for tag in (make_tag(document, name, prop)
667
in self._get_all_dbus_properties()
668
if prop._dbus_interface
669
== if_tag.getAttribute(u"name")):
670
if_tag.appendChild(tag)
671
# Add the names to the return values for the
672
# "org.freedesktop.DBus.Properties" methods
673
if (if_tag.getAttribute(u"name")
674
== u"org.freedesktop.DBus.Properties"):
675
for cn in if_tag.getElementsByTagName(u"method"):
676
if cn.getAttribute(u"name") == u"Get":
677
for arg in cn.getElementsByTagName(u"arg"):
678
if (arg.getAttribute(u"direction")
680
arg.setAttribute(u"name", u"value")
681
elif cn.getAttribute(u"name") == u"GetAll":
682
for arg in cn.getElementsByTagName(u"arg"):
683
if (arg.getAttribute(u"direction")
685
arg.setAttribute(u"name", u"props")
686
xmlstring = document.toxml(u"utf-8")
688
except (AttributeError, xml.dom.DOMException,
689
xml.parsers.expat.ExpatError), error:
690
logger.error(u"Failed to override Introspection method",
685
731
variant_level=1))
688
def disable(self, signal = True):
734
def disable(self, quiet = False):
689
735
oldstate = getattr(self, u"enabled", False)
690
r = Client.disable(self)
691
if signal and oldstate != self.enabled:
736
r = Client.disable(self, quiet=quiet)
737
if not quiet and oldstate != self.enabled:
692
738
# Emit D-Bus signal
693
739
self.PropertyChanged(dbus.String(u"enabled"),
694
740
dbus.Boolean(False, variant_level=1))
759
805
self.PropertyChanged(dbus.String(u"checker_running"),
760
806
dbus.Boolean(False, variant_level=1))
763
## D-Bus methods & signals
809
def _reset_approved(self):
810
self._approved = None
813
def approve(self, value=True):
814
self._approved = value
815
gobject.timeout_add(self._timedelta_to_milliseconds(self.approved_duration, self._reset_approved))
817
def approved_pending(self):
818
return self.approvals_pending > 0
821
## D-Bus methods, signals & properties
764
822
_interface = u"se.bsnet.fukt.Mandos.Client"
767
@dbus.service.method(_interface)
769
return self.checked_ok()
771
826
# CheckerCompleted - signal
772
827
@dbus.service.signal(_interface, signature=u"nxs")
789
# ReceivedSecret - signal
790
845
@dbus.service.signal(_interface)
791
def ReceivedSecret(self):
848
if self.approved_pending():
849
self.PropertyChanged(dbus.String(u"checker_running"),
850
dbus.Boolean(False, variant_level=1))
795
852
# Rejected - signal
796
@dbus.service.signal(_interface)
853
@dbus.service.signal(_interface, signature=u"s")
854
def Rejected(self, reason):
856
if self.approved_pending():
857
self.PropertyChanged(dbus.String(u"checker_running"),
858
dbus.Boolean(False, variant_level=1))
860
# NeedApproval - signal
861
@dbus.service.signal(_interface, signature=u"db")
862
def NeedApproval(self, timeout, default):
864
if not self.approved_pending():
865
self.PropertyChanged(dbus.String(u"approved_pending"),
866
dbus.Boolean(True, variant_level=1))
871
@dbus.service.method(_interface, in_signature=u"b")
872
def Approve(self, value):
876
@dbus.service.method(_interface)
878
return self.checked_ok()
801
880
# Enable - method
802
881
@dbus.service.method(_interface)
821
900
def StopChecker(self):
822
901
self.stop_checker()
905
# approved_pending - property
906
@dbus_service_property(_interface, signature=u"b", access=u"read")
907
def approved_pending_dbus_property(self):
908
return dbus.Boolean(self.approved_pending())
910
# approved_by_default - property
911
@dbus_service_property(_interface, signature=u"b",
913
def approved_by_default_dbus_property(self):
914
return dbus.Boolean(self.approved_by_default)
916
# approved_delay - property
917
@dbus_service_property(_interface, signature=u"t",
919
def approved_delay_dbus_property(self):
920
return dbus.UInt64(self.approved_delay_milliseconds())
922
# approved_duration - property
923
@dbus_service_property(_interface, signature=u"t",
925
def approved_duration_dbus_property(self):
926
return dbus.UInt64(self._timedelta_to_milliseconds(
927
self.approved_duration))
824
929
# name - property
825
930
@dbus_service_property(_interface, signature=u"s", access=u"read")
826
931
def name_dbus_property(self):
1068
class ProxyClient(object):
1069
def __init__(self, child_pipe, fpr, address):
1070
self._pipe = child_pipe
1071
self._pipe.send(('init', fpr, address))
1072
if not self._pipe.recv():
1075
def __getattribute__(self, name):
1076
if(name == '_pipe'):
1077
return super(ProxyClient, self).__getattribute__(name)
1078
self._pipe.send(('getattr', name))
1079
data = self._pipe.recv()
1080
if data[0] == 'data':
1082
if data[0] == 'function':
1083
def func(*args, **kwargs):
1084
self._pipe.send(('funcall', name, args, kwargs))
1085
return self._pipe.recv()[1]
1088
def __setattr__(self, name, value):
1089
if(name == '_pipe'):
1090
return super(ProxyClient, self).__setattr__(name, value)
1091
self._pipe.send(('setattr', name, value))
963
1094
class ClientHandler(socketserver.BaseRequestHandler, object):
964
1095
"""A class to handle client connections.
967
1098
Note: This will run in its own forked process."""
969
1100
def handle(self):
970
logger.info(u"TCP connection from: %s",
971
unicode(self.client_address))
972
logger.debug(u"IPC Pipe FD: %d", self.server.pipe[1])
973
# Open IPC pipe to parent process
974
with closing(os.fdopen(self.server.pipe[1], u"w", 1)) as ipc:
1101
with contextlib.closing(self.server.child_pipe) as child_pipe:
1102
logger.info(u"TCP connection from: %s",
1103
unicode(self.client_address))
1104
logger.debug(u"Pipe FD: %d",
1105
self.server.child_pipe.fileno())
975
1107
session = (gnutls.connection
976
1108
.ClientSession(self.request,
977
1109
gnutls.connection
978
1110
.X509Credentials()))
980
line = self.request.makefile().readline()
981
logger.debug(u"Protocol version: %r", line)
983
if int(line.strip().split()[0]) > 1:
985
except (ValueError, IndexError, RuntimeError), error:
986
logger.error(u"Unknown protocol version: %s", error)
989
1112
# Note: gnutls.connection.X509Credentials is really a
990
1113
# generic GnuTLS certificate credentials object so long as
991
1114
# no X.509 keys are added to it. Therefore, we can use it
992
1115
# here despite using OpenPGP certificates.
994
1117
#priority = u':'.join((u"NONE", u"+VERS-TLS1.1",
995
1118
# u"+AES-256-CBC", u"+SHA1",
996
1119
# u"+COMP-NULL", u"+CTYPE-OPENPGP",
1002
1125
(gnutls.library.functions
1003
1126
.gnutls_priority_set_direct(session._c_object,
1004
1127
priority, None))
1129
# Start communication using the Mandos protocol
1130
# Get protocol number
1131
line = self.request.makefile().readline()
1132
logger.debug(u"Protocol version: %r", line)
1134
if int(line.strip().split()[0]) > 1:
1136
except (ValueError, IndexError, RuntimeError), error:
1137
logger.error(u"Unknown protocol version: %s", error)
1140
# Start GnuTLS connection
1007
1142
session.handshake()
1008
1143
except gnutls.errors.GNUTLSError, error:
1011
1146
# established. Just abandon the request.
1013
1148
logger.debug(u"Handshake succeeded")
1150
approval_required = False
1015
fpr = self.fingerprint(self.peer_certificate(session))
1016
except (TypeError, gnutls.errors.GNUTLSError), error:
1017
logger.warning(u"Bad certificate: %s", error)
1020
logger.debug(u"Fingerprint: %s", fpr)
1153
fpr = self.fingerprint(self.peer_certificate
1155
except (TypeError, gnutls.errors.GNUTLSError), error:
1156
logger.warning(u"Bad certificate: %s", error)
1158
logger.debug(u"Fingerprint: %s", fpr)
1161
client = ProxyClient(child_pipe, fpr,
1162
self.client_address)
1166
if client.approved_delay:
1167
delay = client.approved_delay
1168
client.approvals_pending += 1
1169
approval_required = True
1172
if not client.enabled:
1173
logger.warning(u"Client %s is disabled",
1175
if self.server.use_dbus:
1177
client.Rejected("Disabled")
1180
if client._approved or not client.approved_delay:
1181
#We are approved or approval is disabled
1183
elif client._approved is None:
1184
logger.info(u"Client %s need approval",
1186
if self.server.use_dbus:
1188
client.NeedApproval(
1189
client.approved_delay_milliseconds(),
1190
client.approved_by_default)
1192
logger.warning(u"Client %s was not approved",
1194
if self.server.use_dbus:
1196
client.Rejected("Disapproved")
1199
#wait until timeout or approved
1200
#x = float(client._timedelta_to_milliseconds(delay))
1201
time = datetime.datetime.now()
1202
client.changedstate.acquire()
1203
client.changedstate.wait(float(client._timedelta_to_milliseconds(delay) / 1000))
1204
client.changedstate.release()
1205
time2 = datetime.datetime.now()
1206
if (time2 - time) >= delay:
1207
if not client.approved_by_default:
1208
logger.warning("Client %s timed out while"
1209
" waiting for approval",
1211
if self.server.use_dbus:
1213
client.Rejected("Time out")
1218
delay -= time2 - time
1221
while sent_size < len(client.secret):
1222
# XXX handle session exception
1223
sent = session.send(client.secret[sent_size:])
1224
logger.debug(u"Sent: %d, remaining: %d",
1225
sent, len(client.secret)
1226
- (sent_size + sent))
1229
logger.info(u"Sending secret to %s", client.name)
1230
# bump the timeout as if seen
1232
if self.server.use_dbus:
1022
for c in self.server.clients:
1023
if c.fingerprint == fpr:
1027
ipc.write(u"NOTFOUND %s %s\n"
1028
% (fpr, unicode(self.client_address)))
1031
# Have to check if client.still_valid(), since it is
1032
# possible that the client timed out while establishing
1033
# the GnuTLS session.
1034
if not client.still_valid():
1035
ipc.write(u"INVALID %s\n" % client.name)
1038
ipc.write(u"SENDING %s\n" % client.name)
1040
while sent_size < len(client.secret):
1041
sent = session.send(client.secret[sent_size:])
1042
logger.debug(u"Sent: %d, remaining: %d",
1043
sent, len(client.secret)
1044
- (sent_size + sent))
1237
if approval_required:
1238
client.approvals_pending -= 1
1049
1242
def peer_certificate(session):
1112
class ForkingMixInWithPipe(socketserver.ForkingMixIn, object):
1113
"""Like socketserver.ForkingMixIn, but also pass a pipe."""
1305
class MultiprocessingMixIn(object):
1306
"""Like socketserver.ThreadingMixIn, but with multiprocessing"""
1307
def sub_process_main(self, request, address):
1309
self.finish_request(request, address)
1311
self.handle_error(request, address)
1312
self.close_request(request)
1314
def process_request(self, request, address):
1315
"""Start a new process to process the request."""
1316
multiprocessing.Process(target = self.sub_process_main,
1317
args = (request, address)).start()
1319
class MultiprocessingMixInWithPipe(MultiprocessingMixIn, object):
1320
""" adds a pipe to the MixIn """
1114
1321
def process_request(self, request, client_address):
1115
1322
"""Overrides and wraps the original process_request().
1117
1324
This function creates a new pipe in self.pipe
1119
self.pipe = os.pipe()
1120
super(ForkingMixInWithPipe,
1326
parent_pipe, self.child_pipe = multiprocessing.Pipe()
1328
super(MultiprocessingMixInWithPipe,
1121
1329
self).process_request(request, client_address)
1122
os.close(self.pipe[1]) # close write end
1123
self.add_pipe(self.pipe[0])
1124
def add_pipe(self, pipe):
1330
self.add_pipe(parent_pipe)
1331
def add_pipe(self, parent_pipe):
1125
1332
"""Dummy function; override as necessary"""
1129
class IPv6_TCPServer(ForkingMixInWithPipe,
1335
class IPv6_TCPServer(MultiprocessingMixInWithPipe,
1130
1336
socketserver.TCPServer, object):
1131
1337
"""IPv6-capable TCP server. Accepts 'None' as address and/or port
1217
1423
return socketserver.TCPServer.server_activate(self)
1218
1424
def enable(self):
1219
1425
self.enabled = True
1220
def add_pipe(self, pipe):
1426
def add_pipe(self, parent_pipe):
1221
1427
# Call "handle_ipc" for both data and EOF events
1222
gobject.io_add_watch(pipe, gobject.IO_IN | gobject.IO_HUP,
1224
def handle_ipc(self, source, condition, file_objects={}):
1428
gobject.io_add_watch(parent_pipe.fileno(),
1429
gobject.IO_IN | gobject.IO_HUP,
1430
functools.partial(self.handle_ipc,
1431
parent_pipe = parent_pipe))
1433
def handle_ipc(self, source, condition, parent_pipe=None,
1434
client_object=None):
1225
1435
condition_names = {
1226
1436
gobject.IO_IN: u"IN", # There is data to read.
1227
1437
gobject.IO_OUT: u"OUT", # Data can be written (without
1239
1449
logger.debug(u"Handling IPC: FD = %d, condition = %s", source,
1240
1450
conditions_string)
1242
# Turn the pipe file descriptor into a Python file object
1243
if source not in file_objects:
1244
file_objects[source] = os.fdopen(source, u"r", 1)
1452
# Read a request from the child
1453
request = parent_pipe.recv()
1454
command = request[0]
1246
# Read a line from the file object
1247
cmdline = file_objects[source].readline()
1248
if not cmdline: # Empty line means end of file
1249
# close the IPC pipe
1250
file_objects[source].close()
1251
del file_objects[source]
1253
# Stop calling this function
1456
if command == 'init':
1458
address = request[2]
1460
for c in self.clients:
1461
if c.fingerprint == fpr:
1465
logger.warning(u"Client not found for fingerprint: %s, ad"
1466
u"dress: %s", fpr, address)
1469
mandos_dbus_service.ClientNotFound(fpr, address)
1470
parent_pipe.send(False)
1473
gobject.io_add_watch(parent_pipe.fileno(),
1474
gobject.IO_IN | gobject.IO_HUP,
1475
functools.partial(self.handle_ipc,
1476
parent_pipe = parent_pipe,
1477
client_object = client))
1478
parent_pipe.send(True)
1479
# remove the old hook in favor of the new above hook on same fileno
1256
logger.debug(u"IPC command: %r", cmdline)
1258
# Parse and act on command
1259
cmd, args = cmdline.rstrip(u"\r\n").split(None, 1)
1261
if cmd == u"NOTFOUND":
1262
logger.warning(u"Client not found for fingerprint: %s",
1266
mandos_dbus_service.ClientNotFound(args)
1267
elif cmd == u"INVALID":
1268
for client in self.clients:
1269
if client.name == args:
1270
logger.warning(u"Client %s is invalid", args)
1276
logger.error(u"Unknown client %s is invalid", args)
1277
elif cmd == u"SENDING":
1278
for client in self.clients:
1279
if client.name == args:
1280
logger.info(u"Sending secret to %s", client.name)
1284
client.ReceivedSecret()
1287
logger.error(u"Sending secret to unknown client %s",
1290
logger.error(u"Unknown IPC command: %r", cmdline)
1292
# Keep calling this function
1481
if command == 'funcall':
1482
funcname = request[1]
1486
parent_pipe.send(('data', getattr(client_object, funcname)(*args, **kwargs)))
1488
if command == 'getattr':
1489
attrname = request[1]
1490
if callable(client_object.__getattribute__(attrname)):
1491
parent_pipe.send(('function',))
1493
parent_pipe.send(('data', client_object.__getattribute__(attrname)))
1495
if command == 'setattr':
1496
attrname = request[1]
1498
setattr(client_object, attrname, value)
1372
1579
null = os.open(os.path.devnull, os.O_NOCTTY | os.O_RDWR)
1373
1580
if not stat.S_ISCHR(os.fstat(null).st_mode):
1374
1581
raise OSError(errno.ENODEV,
1375
u"/dev/null not a character device")
1582
u"%s not a character device"
1376
1584
os.dup2(null, sys.stdin.fileno())
1377
1585
os.dup2(null, sys.stdout.fileno())
1378
1586
os.dup2(null, sys.stderr.fileno())
1545
1755
bus = dbus.SystemBus()
1546
1756
# End of Avahi example code
1548
bus_name = dbus.service.BusName(u"se.bsnet.fukt.Mandos", bus)
1759
bus_name = dbus.service.BusName(u"se.bsnet.fukt.Mandos",
1760
bus, do_not_queue=True)
1761
except dbus.exceptions.NameExistsException, e:
1762
logger.error(unicode(e) + u", disabling D-Bus")
1764
server_settings[u"use_dbus"] = False
1765
tcp_server.use_dbus = False
1549
1766
protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
1550
1767
service = AvahiService(name = server_settings[u"servicename"],
1551
1768
servicetype = u"_mandos._tcp",
1557
1774
client_class = Client
1559
1776
client_class = functools.partial(ClientDBus, bus = bus)
1777
def client_config_items(config, section):
1778
special_settings = {
1779
"approved_by_default":
1780
lambda: config.getboolean(section,
1781
"approved_by_default"),
1783
for name, value in config.items(section):
1785
yield (name, special_settings[name]())
1560
1789
tcp_server.clients.update(set(
1561
1790
client_class(name = section,
1562
config= dict(client_config.items(section)))
1791
config= dict(client_config_items(
1792
client_config, section)))
1563
1793
for section in client_config.sections()))
1564
1794
if not tcp_server.clients:
1565
1795
logger.warning(u"No clients defined")
1612
1831
dbus.service.Object.__init__(self, bus, u"/")
1613
1832
_interface = u"se.bsnet.fukt.Mandos"
1615
@dbus.service.signal(_interface, signature=u"oa{sv}")
1616
def ClientAdded(self, objpath, properties):
1834
@dbus.service.signal(_interface, signature=u"o")
1835
def ClientAdded(self, objpath):
1620
@dbus.service.signal(_interface, signature=u"s")
1621
def ClientNotFound(self, fingerprint):
1839
@dbus.service.signal(_interface, signature=u"ss")
1840
def ClientNotFound(self, fingerprint, address):
1650
1869
tcp_server.clients.remove(c)
1651
1870
c.remove_from_connection()
1652
1871
# Don't signal anything except ClientRemoved
1653
c.disable(signal=False)
1872
c.disable(quiet=True)
1654
1873
# Emit D-Bus signal
1655
1874
self.ClientRemoved(object_path, c.name)
1876
raise KeyError(object_path)
1661
1880
mandos_dbus_service = MandosDBusService()
1883
"Cleanup function; run on exit"
1886
while tcp_server.clients:
1887
client = tcp_server.clients.pop()
1889
client.remove_from_connection()
1890
client.disable_hook = None
1891
# Don't signal anything except ClientRemoved
1892
client.disable(quiet=True)
1895
mandos_dbus_service.ClientRemoved(client.dbus_object_path,
1898
atexit.register(cleanup)
1663
1900
for client in tcp_server.clients:
1665
1902
# Emit D-Bus signal
1666
mandos_dbus_service.ClientAdded(client.dbus_object_path,
1903
mandos_dbus_service.ClientAdded(client.dbus_object_path)
1668
1904
client.enable()
1670
1906
tcp_server.enable()