193
191
self.group.Commit()
194
192
def entry_group_state_changed(self, state, error):
195
193
"""Derived from the Avahi example code"""
196
logger.debug(u"Avahi entry group state change: %i", state)
194
logger.debug(u"Avahi state change: %i", state)
198
196
if state == avahi.ENTRY_GROUP_ESTABLISHED:
199
197
logger.debug(u"Zeroconf service established.")
246
243
last_checked_ok: datetime.datetime(); (UTC) or None
247
244
timeout: datetime.timedelta(); How long from last_checked_ok
248
until this client is disabled
245
until this client is invalid
249
246
interval: datetime.timedelta(); How often to start a new checker
250
247
disable_hook: If set, called by disable() as disable_hook(self)
251
248
checker: subprocess.Popen(); a running checker process used
327
325
self.checker_initiator_tag = (gobject.timeout_add
328
326
(self.interval_milliseconds(),
329
327
self.start_checker))
328
# Also start a new checker *right now*.
330
330
# Schedule a disable() when 'timeout' has passed
331
331
self.disable_initiator_tag = (gobject.timeout_add
332
332
(self.timeout_milliseconds(),
334
334
self.enabled = True
335
# Also start a new checker *right now*.
338
def disable(self, quiet=True):
339
337
"""Disable this client."""
340
338
if not getattr(self, "enabled", False):
343
logger.info(u"Disabling client %s", self.name)
340
logger.info(u"Disabling client %s", self.name)
344
341
if getattr(self, u"disable_initiator_tag", False):
345
342
gobject.source_remove(self.disable_initiator_tag)
346
343
self.disable_initiator_tag = None
398
395
# client would inevitably timeout, since no checker would get
399
396
# a chance to run to completion. If we instead leave running
400
397
# checkers alone, the checker would have to take more time
401
# than 'timeout' for the client to be disabled, which is as it
398
# than 'timeout' for the client to be declared invalid, which
399
# is as it should be.
404
401
# If a checker exists, make sure it is not a zombie
470
467
logger.debug(u"Stopping checker for %(name)s", vars(self))
472
469
os.kill(self.checker.pid, signal.SIGTERM)
474
471
#if self.checker.poll() is None:
475
472
# os.kill(self.checker.pid, signal.SIGKILL)
476
473
except OSError, error:
477
474
if error.errno != errno.ESRCH: # No such process
479
476
self.checker = None
478
def still_valid(self):
479
"""Has the timeout not yet passed for this client?"""
480
if not getattr(self, u"enabled", False):
482
now = datetime.datetime.utcnow()
483
if self.last_checked_ok is None:
484
return now < (self.created + self.timeout)
486
return now < (self.last_checked_ok + self.timeout)
482
489
def dbus_service_property(dbus_interface, signature=u"v",
491
498
dbus.service.method, except there is only "signature", since the
492
499
type from Get() and the type sent to Set() is the same.
494
# Encoding deeply encoded byte arrays is not supported yet by the
495
# "Set" method, so we fail early here:
496
if byte_arrays and signature != u"ay":
497
raise ValueError(u"Byte arrays not supported for non-'ay'"
498
u" signature %r" % signature)
499
501
def decorator(func):
500
502
func._dbus_is_property = True
501
503
func._dbus_interface = dbus_interface
707
705
variant_level=1))
710
def disable(self, quiet = False):
708
def disable(self, signal = True):
711
709
oldstate = getattr(self, u"enabled", False)
712
r = Client.disable(self, quiet=quiet)
713
if not quiet and oldstate != self.enabled:
710
r = Client.disable(self)
711
if signal and oldstate != self.enabled:
714
712
# Emit D-Bus signal
715
713
self.PropertyChanged(dbus.String(u"enabled"),
716
714
dbus.Boolean(False, variant_level=1))
782
780
dbus.Boolean(False, variant_level=1))
785
## D-Bus methods, signals & properties
783
## D-Bus methods & signals
786
784
_interface = u"se.bsnet.fukt.Mandos.Client"
787
@dbus.service.method(_interface)
789
return self.checked_ok()
790
791
# CheckerCompleted - signal
791
792
@dbus.service.signal(_interface, signature=u"nxs")
997
989
def handle(self):
998
990
logger.info(u"TCP connection from: %s",
999
991
unicode(self.client_address))
1000
logger.debug(u"IPC Pipe FD: %d",
1001
self.server.child_pipe[1].fileno())
992
logger.debug(u"IPC Pipe FD: %d", self.server.pipe[1])
1002
993
# Open IPC pipe to parent process
1003
with contextlib.nested(self.server.child_pipe[1],
1004
self.server.parent_pipe[0]
1005
) as (ipc, ipc_return):
994
with closing(os.fdopen(self.server.pipe[1], u"w", 1)) as ipc:
1006
995
session = (gnutls.connection
1007
996
.ClientSession(self.request,
1008
997
gnutls.connection
1009
998
.X509Credentials()))
1000
line = self.request.makefile().readline()
1001
logger.debug(u"Protocol version: %r", line)
1003
if int(line.strip().split()[0]) > 1:
1005
except (ValueError, IndexError, RuntimeError), error:
1006
logger.error(u"Unknown protocol version: %s", error)
1011
1009
# Note: gnutls.connection.X509Credentials is really a
1012
1010
# generic GnuTLS certificate credentials object so long as
1013
1011
# no X.509 keys are added to it. Therefore, we can use it
1025
1023
.gnutls_priority_set_direct(session._c_object,
1026
1024
priority, None))
1028
# Start communication using the Mandos protocol
1029
# Get protocol number
1030
line = self.request.makefile().readline()
1031
logger.debug(u"Protocol version: %r", line)
1033
if int(line.strip().split()[0]) > 1:
1035
except (ValueError, IndexError, RuntimeError), error:
1036
logger.error(u"Unknown protocol version: %s", error)
1039
# Start GnuTLS connection
1041
1027
session.handshake()
1042
1028
except gnutls.errors.GNUTLSError, error:
1047
1033
logger.debug(u"Handshake succeeded")
1050
fpr = self.fingerprint(self.peer_certificate
1052
except (TypeError, gnutls.errors.GNUTLSError), error:
1053
logger.warning(u"Bad certificate: %s", error)
1055
logger.debug(u"Fingerprint: %s", fpr)
1057
for c in self.server.clients:
1058
if c.fingerprint == fpr:
1062
ipc.write(u"NOTFOUND %s %s\n"
1063
% (fpr, unicode(self.client_address)))
1066
class ClientProxy(object):
1067
"""Client proxy object. Not for calling methods."""
1068
def __init__(self, client):
1069
self.client = client
1070
def __getattr__(self, name):
1071
if name.startswith("ipc_"):
1073
ipc.write("%s %s\n" % (name[4:].upper(),
1076
if not hasattr(self.client, name):
1077
raise AttributeError
1078
ipc.write(u"GETATTR %s %s\n"
1079
% (name, self.client.fingerprint))
1080
return pickle.load(ipc_return)
1081
clientproxy = ClientProxy(client)
1082
# Have to check if client.enabled, since it is
1083
# possible that the client was disabled since the
1084
# GnuTLS session was established.
1085
if not clientproxy.enabled:
1086
clientproxy.ipc_disabled()
1089
clientproxy.ipc_sending()
1091
while sent_size < len(client.secret):
1092
sent = session.send(client.secret[sent_size:])
1093
logger.debug(u"Sent: %d, remaining: %d",
1094
sent, len(client.secret)
1095
- (sent_size + sent))
1035
fpr = self.fingerprint(self.peer_certificate(session))
1036
except (TypeError, gnutls.errors.GNUTLSError), error:
1037
logger.warning(u"Bad certificate: %s", error)
1040
logger.debug(u"Fingerprint: %s", fpr)
1042
for c in self.server.clients:
1043
if c.fingerprint == fpr:
1047
ipc.write(u"NOTFOUND %s %s\n"
1048
% (fpr, unicode(self.client_address)))
1051
# Have to check if client.still_valid(), since it is
1052
# possible that the client timed out while establishing
1053
# the GnuTLS session.
1054
if not client.still_valid():
1055
ipc.write(u"INVALID %s\n" % client.name)
1058
ipc.write(u"SENDING %s\n" % client.name)
1060
while sent_size < len(client.secret):
1061
sent = session.send(client.secret[sent_size:])
1062
logger.debug(u"Sent: %d, remaining: %d",
1063
sent, len(client.secret)
1064
- (sent_size + sent))
1101
1069
def peer_certificate(session):
1164
class ForkingMixInWithPipes(socketserver.ForkingMixIn, object):
1165
"""Like socketserver.ForkingMixIn, but also pass a pipe pair."""
1132
class ForkingMixInWithPipe(socketserver.ForkingMixIn, object):
1133
"""Like socketserver.ForkingMixIn, but also pass a pipe."""
1166
1134
def process_request(self, request, client_address):
1167
1135
"""Overrides and wraps the original process_request().
1169
1137
This function creates a new pipe in self.pipe
1171
# Child writes to child_pipe
1172
self.child_pipe = map(os.fdopen, os.pipe(), u"rw", (1, 0))
1173
# Parent writes to parent_pipe
1174
self.parent_pipe = map(os.fdopen, os.pipe(), u"rw", (1, 0))
1175
super(ForkingMixInWithPipes,
1139
self.pipe = os.pipe()
1140
super(ForkingMixInWithPipe,
1176
1141
self).process_request(request, client_address)
1177
# Close unused ends for parent
1178
self.parent_pipe[0].close() # close read end
1179
self.child_pipe[1].close() # close write end
1180
self.add_pipe_fds(self.child_pipe[0], self.parent_pipe[1])
1181
def add_pipe_fds(self, child_pipe_fd, parent_pipe_fd):
1142
os.close(self.pipe[1]) # close write end
1143
self.add_pipe(self.pipe[0])
1144
def add_pipe(self, pipe):
1182
1145
"""Dummy function; override as necessary"""
1183
child_pipe_fd.close()
1184
parent_pipe_fd.close()
1187
class IPv6_TCPServer(ForkingMixInWithPipes,
1149
class IPv6_TCPServer(ForkingMixInWithPipe,
1188
1150
socketserver.TCPServer, object):
1189
1151
"""IPv6-capable TCP server. Accepts 'None' as address and/or port
1275
1237
return socketserver.TCPServer.server_activate(self)
1276
1238
def enable(self):
1277
1239
self.enabled = True
1278
def add_pipe_fds(self, child_pipe_fd, parent_pipe_fd):
1240
def add_pipe(self, pipe):
1279
1241
# Call "handle_ipc" for both data and EOF events
1280
gobject.io_add_watch(child_pipe_fd.fileno(),
1281
gobject.IO_IN | gobject.IO_HUP,
1282
functools.partial(self.handle_ipc,
1283
reply = parent_pipe_fd,
1284
sender= child_pipe_fd))
1285
def handle_ipc(self, source, condition, reply=None, sender=None):
1242
gobject.io_add_watch(pipe, gobject.IO_IN | gobject.IO_HUP,
1244
def handle_ipc(self, source, condition, file_objects={}):
1286
1245
condition_names = {
1287
1246
gobject.IO_IN: u"IN", # There is data to read.
1288
1247
gobject.IO_OUT: u"OUT", # Data can be written (without
1300
1259
logger.debug(u"Handling IPC: FD = %d, condition = %s", source,
1301
1260
conditions_string)
1262
# Turn the pipe file descriptor into a Python file object
1263
if source not in file_objects:
1264
file_objects[source] = os.fdopen(source, u"r", 1)
1303
1266
# Read a line from the file object
1304
cmdline = sender.readline()
1267
cmdline = file_objects[source].readline()
1305
1268
if not cmdline: # Empty line means end of file
1306
# close the IPC pipes
1269
# close the IPC pipe
1270
file_objects[source].close()
1271
del file_objects[source]
1310
1273
# Stop calling this function
1316
1279
cmd, args = cmdline.rstrip(u"\r\n").split(None, 1)
1318
1281
if cmd == u"NOTFOUND":
1319
fpr, address = args.split(None, 1)
1320
logger.warning(u"Client not found for fingerprint: %s, ad"
1321
u"dress: %s", fpr, address)
1282
logger.warning(u"Client not found for fingerprint: %s",
1322
1284
if self.use_dbus:
1323
1285
# Emit D-Bus signal
1324
mandos_dbus_service.ClientNotFound(fpr, address)
1325
elif cmd == u"DISABLED":
1286
mandos_dbus_service.ClientNotFound(args)
1287
elif cmd == u"INVALID":
1326
1288
for client in self.clients:
1327
1289
if client.name == args:
1328
logger.warning(u"Client %s is disabled", args)
1290
logger.warning(u"Client %s is invalid", args)
1329
1291
if self.use_dbus:
1330
1292
# Emit D-Bus signal
1331
1293
client.Rejected()
1334
logger.error(u"Unknown client %s is disabled", args)
1296
logger.error(u"Unknown client %s is invalid", args)
1335
1297
elif cmd == u"SENDING":
1336
1298
for client in self.clients:
1337
1299
if client.name == args:
1345
1307
logger.error(u"Sending secret to unknown client %s",
1347
elif cmd == u"GETATTR":
1348
attr_name, fpr = args.split(None, 1)
1349
for client in self.clients:
1350
if client.fingerprint == fpr:
1351
attr_value = getattr(client, attr_name, None)
1352
logger.debug("IPC reply: %r", attr_value)
1353
pickle.dump(attr_value, reply)
1356
logger.error(u"Client %s on address %s requesting "
1357
u"attribute %s not found", fpr, address,
1359
pickle.dump(None, reply)
1361
1310
logger.error(u"Unknown IPC command: %r", cmdline)
1396
1345
elif suffix == u"w":
1397
1346
delta = datetime.timedelta(0, 0, 0, 0, 0, 0, value)
1399
raise ValueError(u"Unknown suffix %r" % suffix)
1400
except (ValueError, IndexError), e:
1401
raise ValueError(e.message)
1349
except (ValueError, IndexError):
1402
1351
timevalue += delta
1403
1352
return timevalue
1417
1366
def if_nametoindex(interface):
1418
1367
"Get an interface index the hard way, i.e. using fcntl()"
1419
1368
SIOCGIFINDEX = 0x8933 # From /usr/include/linux/sockios.h
1420
with contextlib.closing(socket.socket()) as s:
1369
with closing(socket.socket()) as s:
1421
1370
ifreq = fcntl.ioctl(s, SIOCGIFINDEX,
1422
1371
struct.pack(str(u"16s16x"),
1618
1566
bus = dbus.SystemBus()
1619
1567
# End of Avahi example code
1622
bus_name = dbus.service.BusName(u"se.bsnet.fukt.Mandos",
1623
bus, do_not_queue=True)
1624
except dbus.exceptions.NameExistsException, e:
1625
logger.error(unicode(e) + u", disabling D-Bus")
1627
server_settings[u"use_dbus"] = False
1628
tcp_server.use_dbus = False
1569
bus_name = dbus.service.BusName(u"se.bsnet.fukt.Mandos", bus)
1629
1570
protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
1630
1571
service = AvahiService(name = server_settings[u"servicename"],
1631
1572
servicetype = u"_mandos._tcp",
1670
1611
del pidfilename
1614
"Cleanup function; run on exit"
1617
while tcp_server.clients:
1618
client = tcp_server.clients.pop()
1619
client.disable_hook = None
1622
atexit.register(cleanup)
1673
1625
signal.signal(signal.SIGINT, signal.SIG_IGN)
1674
1626
signal.signal(signal.SIGHUP, lambda signum, frame: sys.exit())
1681
1633
dbus.service.Object.__init__(self, bus, u"/")
1682
1634
_interface = u"se.bsnet.fukt.Mandos"
1684
@dbus.service.signal(_interface, signature=u"o")
1685
def ClientAdded(self, objpath):
1636
@dbus.service.signal(_interface, signature=u"oa{sv}")
1637
def ClientAdded(self, objpath, properties):
1689
@dbus.service.signal(_interface, signature=u"ss")
1690
def ClientNotFound(self, fingerprint, address):
1641
@dbus.service.signal(_interface, signature=u"s")
1642
def ClientNotFound(self, fingerprint):
1719
1671
tcp_server.clients.remove(c)
1720
1672
c.remove_from_connection()
1721
1673
# Don't signal anything except ClientRemoved
1722
c.disable(quiet=True)
1674
c.disable(signal=False)
1723
1675
# Emit D-Bus signal
1724
1676
self.ClientRemoved(object_path, c.name)
1726
raise KeyError(object_path)
1730
1682
mandos_dbus_service = MandosDBusService()
1733
"Cleanup function; run on exit"
1736
while tcp_server.clients:
1737
client = tcp_server.clients.pop()
1739
client.remove_from_connection()
1740
client.disable_hook = None
1741
# Don't signal anything except ClientRemoved
1742
client.disable(quiet=True)
1745
mandos_dbus_service.ClientRemoved(client.dbus_object_path,
1748
atexit.register(cleanup)
1750
1684
for client in tcp_server.clients:
1752
1686
# Emit D-Bus signal
1753
mandos_dbus_service.ClientAdded(client.dbus_object_path)
1687
mandos_dbus_service.ClientAdded(client.dbus_object_path,
1754
1689
client.enable()
1756
1691
tcp_server.enable()
1787
1721
main_loop.run()
1788
1722
except AvahiError, error:
1789
1723
logger.critical(u"AvahiError: %s", error)
1792
1725
except KeyboardInterrupt:
1794
1727
print >> sys.stderr
1795
1728
logger.debug(u"Server received KeyboardInterrupt")
1796
1729
logger.debug(u"Server exiting")
1797
# Must run before the D-Bus bus name gets deregistered
1800
1731
if __name__ == '__main__':