174
168
# End of Avahi example code
177
def _datetime_to_dbus(dt, variant_level=0):
178
"""Convert a UTC datetime.datetime() to a D-Bus type."""
179
return dbus.String(dt.isoformat(), variant_level=variant_level)
182
171
class Client(object):
183
172
"""A representation of a client host served by this server.
185
name: string; from the config file, used in log messages and
174
name: string; from the config file, used in log messages
187
175
fingerprint: string (40 or 32 hexadecimal digits); used to
188
176
uniquely identify the client
189
secret: bytestring; sent verbatim (over TLS) to client
190
host: string; available for use by the checker command
191
created: datetime.datetime(); (UTC) object creation
192
last_enabled: datetime.datetime(); (UTC)
194
last_checked_ok: datetime.datetime(); (UTC) or None
195
timeout: datetime.timedelta(); How long from last_checked_ok
196
until this client is invalid
197
interval: datetime.timedelta(); How often to start a new checker
198
disable_hook: If set, called by disable() as disable_hook(self)
199
checker: subprocess.Popen(); a running checker process used
200
to see if the client lives.
201
'None' if no process is running.
177
secret: bytestring; sent verbatim (over TLS) to client
178
host: string; available for use by the checker command
179
created: datetime.datetime(); object creation, not client host
180
last_checked_ok: datetime.datetime() or None if not yet checked OK
181
timeout: datetime.timedelta(); How long from last_checked_ok
182
until this client is invalid
183
interval: datetime.timedelta(); How often to start a new checker
184
stop_hook: If set, called by stop() as stop_hook(self)
185
checker: subprocess.Popen(); a running checker process used
186
to see if the client lives.
187
'None' if no process is running.
202
188
checker_initiator_tag: a gobject event source tag, or None
203
disable_initiator_tag: - '' -
189
stop_initiator_tag: - '' -
204
190
checker_callback_tag: - '' -
205
191
checker_command: string; External command which is run to check if
206
192
client lives. %() expansions are done at
207
193
runtime with vars(self) as dict, so that for
208
194
instance %(name)s can be used in the command.
209
current_checker_command: string; current running checker_command
196
_timeout: Real variable for 'timeout'
197
_interval: Real variable for 'interval'
198
_timeout_milliseconds: Used when calling gobject.timeout_add()
199
_interval_milliseconds: - '' -
211
def timeout_milliseconds(self):
212
"Return the 'timeout' attribute in milliseconds"
213
return ((self.timeout.days * 24 * 60 * 60 * 1000)
214
+ (self.timeout.seconds * 1000)
215
+ (self.timeout.microseconds // 1000))
217
def interval_milliseconds(self):
218
"Return the 'interval' attribute in milliseconds"
219
return ((self.interval.days * 24 * 60 * 60 * 1000)
220
+ (self.interval.seconds * 1000)
221
+ (self.interval.microseconds // 1000))
223
def __init__(self, name = None, disable_hook=None, config=None):
201
def _set_timeout(self, timeout):
202
"Setter function for 'timeout' attribute"
203
self._timeout = timeout
204
self._timeout_milliseconds = ((self.timeout.days
205
* 24 * 60 * 60 * 1000)
206
+ (self.timeout.seconds * 1000)
207
+ (self.timeout.microseconds
209
timeout = property(lambda self: self._timeout,
212
def _set_interval(self, interval):
213
"Setter function for 'interval' attribute"
214
self._interval = interval
215
self._interval_milliseconds = ((self.interval.days
216
* 24 * 60 * 60 * 1000)
217
+ (self.interval.seconds
219
+ (self.interval.microseconds
221
interval = property(lambda self: self._interval,
224
def __init__(self, name = None, stop_hook=None, config={}):
224
225
"""Note: the 'checker' key in 'config' sets the
225
226
'checker_command' attribute and *not* the 'checker'
230
229
logger.debug(u"Creating client %r", self.name)
231
230
# Uppercase and remove spaces from fingerprint for later
232
231
# comparison purposes with return value from the fingerprint()
234
self.fingerprint = (config["fingerprint"].upper()
233
self.fingerprint = config["fingerprint"].upper()\
236
235
logger.debug(u" Fingerprint: %s", self.fingerprint)
237
236
if "secret" in config:
238
237
self.secret = config["secret"].decode(u"base64")
239
238
elif "secfile" in config:
240
with closing(open(os.path.expanduser
242
(config["secfile"])))) as secfile:
243
self.secret = secfile.read()
239
sf = open(config["secfile"])
240
self.secret = sf.read()
245
243
raise TypeError(u"No secret or secfile for client %s"
247
245
self.host = config.get("host", "")
248
self.created = datetime.datetime.utcnow()
250
self.last_enabled = None
246
self.created = datetime.datetime.now()
251
247
self.last_checked_ok = None
252
248
self.timeout = string_to_delta(config["timeout"])
253
249
self.interval = string_to_delta(config["interval"])
254
self.disable_hook = disable_hook
250
self.stop_hook = stop_hook
255
251
self.checker = None
256
252
self.checker_initiator_tag = None
257
self.disable_initiator_tag = None
253
self.stop_initiator_tag = None
258
254
self.checker_callback_tag = None
259
self.checker_command = config["checker"]
260
self.current_checker_command = None
261
self.last_connect = None
255
self.check_command = config["checker"]
264
257
"""Start this client's checker and timeout hooks"""
265
self.last_enabled = datetime.datetime.utcnow()
266
258
# Schedule a new checker to be started an 'interval' from now,
267
259
# and every interval from then on.
268
self.checker_initiator_tag = (gobject.timeout_add
269
(self.interval_milliseconds(),
260
self.checker_initiator_tag = gobject.timeout_add\
261
(self._interval_milliseconds,
271
263
# Also start a new checker *right now*.
272
264
self.start_checker()
273
# Schedule a disable() when 'timeout' has passed
274
self.disable_initiator_tag = (gobject.timeout_add
275
(self.timeout_milliseconds(),
280
"""Disable this client."""
281
if not getattr(self, "enabled", False):
265
# Schedule a stop() when 'timeout' has passed
266
self.stop_initiator_tag = gobject.timeout_add\
267
(self._timeout_milliseconds,
271
The possibility that a client might be restarted is left open,
272
but not currently used."""
273
# If this client doesn't have a secret, it is already stopped.
274
if hasattr(self, "secret") and self.secret:
275
logger.info(u"Stopping client %s", self.name)
283
logger.info(u"Disabling client %s", self.name)
284
if getattr(self, "disable_initiator_tag", False):
285
gobject.source_remove(self.disable_initiator_tag)
286
self.disable_initiator_tag = None
279
if getattr(self, "stop_initiator_tag", False):
280
gobject.source_remove(self.stop_initiator_tag)
281
self.stop_initiator_tag = None
287
282
if getattr(self, "checker_initiator_tag", False):
288
283
gobject.source_remove(self.checker_initiator_tag)
289
284
self.checker_initiator_tag = None
290
285
self.stop_checker()
291
if self.disable_hook:
292
self.disable_hook(self)
294
288
# Do not run this again if called by a gobject.timeout_add
297
290
def __del__(self):
298
self.disable_hook = None
301
def checker_callback(self, pid, condition, command):
291
self.stop_hook = None
293
def checker_callback(self, pid, condition):
302
294
"""The checker has completed, so take appropriate actions."""
295
now = datetime.datetime.now()
303
296
self.checker_callback_tag = None
304
297
self.checker = None
305
if os.WIFEXITED(condition):
306
exitstatus = os.WEXITSTATUS(condition)
308
logger.info(u"Checker for %(name)s succeeded",
312
logger.info(u"Checker for %(name)s failed",
298
if os.WIFEXITED(condition) \
299
and (os.WEXITSTATUS(condition) == 0):
300
logger.info(u"Checker for %(name)s succeeded",
302
self.last_checked_ok = now
303
gobject.source_remove(self.stop_initiator_tag)
304
self.stop_initiator_tag = gobject.timeout_add\
305
(self._timeout_milliseconds,
307
elif not os.WIFEXITED(condition):
315
308
logger.warning(u"Checker for %(name)s crashed?",
318
def checked_ok(self):
319
"""Bump up the timeout for this client.
320
This should only be called when the client has been seen,
323
self.last_checked_ok = datetime.datetime.utcnow()
324
gobject.source_remove(self.disable_initiator_tag)
325
self.disable_initiator_tag = (gobject.timeout_add
326
(self.timeout_milliseconds(),
311
logger.info(u"Checker for %(name)s failed",
329
313
def start_checker(self):
330
314
"""Start a new checker subprocess if one is not running.
331
315
If a checker already exists, leave it running and do
407
372
if error.errno != errno.ESRCH: # No such process
409
374
self.checker = None
411
375
def still_valid(self):
412
376
"""Has the timeout not yet passed for this client?"""
413
if not getattr(self, "enabled", False):
415
now = datetime.datetime.utcnow()
377
now = datetime.datetime.now()
416
378
if self.last_checked_ok is None:
417
379
return now < (self.created + self.timeout)
419
381
return now < (self.last_checked_ok + self.timeout)
422
class ClientDBus(Client, dbus.service.Object):
423
"""A Client class using D-Bus
425
dbus_object_path: dbus.ObjectPath ; only set if self.use_dbus
427
# dbus.service.Object doesn't use super(), so we can't either.
429
def __init__(self, *args, **kwargs):
430
Client.__init__(self, *args, **kwargs)
431
# Only now, when this client is initialized, can it show up on
433
self.dbus_object_path = (dbus.ObjectPath
435
+ self.name.replace(".", "_")))
436
dbus.service.Object.__init__(self, bus,
437
self.dbus_object_path)
439
oldstate = getattr(self, "enabled", False)
440
r = Client.enable(self)
441
if oldstate != self.enabled:
443
self.PropertyChanged(dbus.String(u"enabled"),
444
dbus.Boolean(True, variant_level=1))
445
self.PropertyChanged(dbus.String(u"last_enabled"),
446
(_datetime_to_dbus(self.last_enabled,
450
def disable(self, signal = True):
451
oldstate = getattr(self, "enabled", False)
452
r = Client.disable(self)
453
if signal and oldstate != self.enabled:
455
self.PropertyChanged(dbus.String(u"enabled"),
456
dbus.Boolean(False, variant_level=1))
459
def __del__(self, *args, **kwargs):
461
self.remove_from_connection()
462
except org.freedesktop.DBus.Python.LookupError:
464
dbus.service.Object.__del__(self, *args, **kwargs)
465
Client.__del__(self, *args, **kwargs)
467
def checker_callback(self, pid, condition, command,
469
self.checker_callback_tag = None
472
self.PropertyChanged(dbus.String(u"checker_running"),
473
dbus.Boolean(False, variant_level=1))
474
if os.WIFEXITED(condition):
475
exitstatus = os.WEXITSTATUS(condition)
477
self.CheckerCompleted(dbus.Int16(exitstatus),
478
dbus.Int64(condition),
479
dbus.String(command))
482
self.CheckerCompleted(dbus.Int16(-1),
483
dbus.Int64(condition),
484
dbus.String(command))
486
return Client.checker_callback(self, pid, condition, command,
489
def checked_ok(self, *args, **kwargs):
490
r = Client.checked_ok(self, *args, **kwargs)
492
self.PropertyChanged(
493
dbus.String(u"last_checked_ok"),
494
(_datetime_to_dbus(self.last_checked_ok,
498
def start_checker(self, *args, **kwargs):
499
old_checker = self.checker
500
if self.checker is not None:
501
old_checker_pid = self.checker.pid
503
old_checker_pid = None
504
r = Client.start_checker(self, *args, **kwargs)
505
# Only emit D-Bus signal if new checker process was started
506
if ((self.checker is not None)
507
and not (old_checker is not None
508
and old_checker_pid == self.checker.pid)):
509
self.CheckerStarted(self.current_checker_command)
510
self.PropertyChanged(
511
dbus.String("checker_running"),
512
dbus.Boolean(True, variant_level=1))
515
def stop_checker(self, *args, **kwargs):
516
old_checker = getattr(self, "checker", None)
517
r = Client.stop_checker(self, *args, **kwargs)
518
if (old_checker is not None
519
and getattr(self, "checker", None) is None):
520
self.PropertyChanged(dbus.String(u"checker_running"),
521
dbus.Boolean(False, variant_level=1))
524
## D-Bus methods & signals
525
_interface = u"se.bsnet.fukt.Mandos.Client"
528
CheckedOK = dbus.service.method(_interface)(checked_ok)
529
CheckedOK.__name__ = "CheckedOK"
531
# CheckerCompleted - signal
532
@dbus.service.signal(_interface, signature="nxs")
533
def CheckerCompleted(self, exitcode, waitstatus, command):
537
# CheckerStarted - signal
538
@dbus.service.signal(_interface, signature="s")
539
def CheckerStarted(self, command):
543
# GetAllProperties - method
544
@dbus.service.method(_interface, out_signature="a{sv}")
545
def GetAllProperties(self):
547
return dbus.Dictionary({
549
dbus.String(self.name, variant_level=1),
550
dbus.String("fingerprint"):
551
dbus.String(self.fingerprint, variant_level=1),
553
dbus.String(self.host, variant_level=1),
554
dbus.String("created"):
555
_datetime_to_dbus(self.created, variant_level=1),
556
dbus.String("last_enabled"):
557
(_datetime_to_dbus(self.last_enabled,
559
if self.last_enabled is not None
560
else dbus.Boolean(False, variant_level=1)),
561
dbus.String("enabled"):
562
dbus.Boolean(self.enabled, variant_level=1),
563
dbus.String("last_checked_ok"):
564
(_datetime_to_dbus(self.last_checked_ok,
566
if self.last_checked_ok is not None
567
else dbus.Boolean (False, variant_level=1)),
568
dbus.String("timeout"):
569
dbus.UInt64(self.timeout_milliseconds(),
571
dbus.String("interval"):
572
dbus.UInt64(self.interval_milliseconds(),
574
dbus.String("checker"):
575
dbus.String(self.checker_command,
577
dbus.String("checker_running"):
578
dbus.Boolean(self.checker is not None,
580
dbus.String("object_path"):
581
dbus.ObjectPath(self.dbus_object_path,
585
# IsStillValid - method
586
@dbus.service.method(_interface, out_signature="b")
587
def IsStillValid(self):
588
return self.still_valid()
590
# PropertyChanged - signal
591
@dbus.service.signal(_interface, signature="sv")
592
def PropertyChanged(self, property, value):
596
# ReceivedSecret - signal
597
@dbus.service.signal(_interface)
598
def ReceivedSecret(self):
603
@dbus.service.signal(_interface)
608
# SetChecker - method
609
@dbus.service.method(_interface, in_signature="s")
610
def SetChecker(self, checker):
611
"D-Bus setter method"
612
self.checker_command = checker
614
self.PropertyChanged(dbus.String(u"checker"),
615
dbus.String(self.checker_command,
619
@dbus.service.method(_interface, in_signature="s")
620
def SetHost(self, host):
621
"D-Bus setter method"
624
self.PropertyChanged(dbus.String(u"host"),
625
dbus.String(self.host, variant_level=1))
627
# SetInterval - method
628
@dbus.service.method(_interface, in_signature="t")
629
def SetInterval(self, milliseconds):
630
self.interval = datetime.timedelta(0, 0, 0, milliseconds)
632
self.PropertyChanged(dbus.String(u"interval"),
633
(dbus.UInt64(self.interval_milliseconds(),
637
@dbus.service.method(_interface, in_signature="ay",
639
def SetSecret(self, secret):
640
"D-Bus setter method"
641
self.secret = str(secret)
643
# SetTimeout - method
644
@dbus.service.method(_interface, in_signature="t")
645
def SetTimeout(self, milliseconds):
646
self.timeout = datetime.timedelta(0, 0, 0, milliseconds)
648
self.PropertyChanged(dbus.String(u"timeout"),
649
(dbus.UInt64(self.timeout_milliseconds(),
653
Enable = dbus.service.method(_interface)(enable)
654
Enable.__name__ = "Enable"
656
# StartChecker - method
657
@dbus.service.method(_interface)
658
def StartChecker(self):
663
@dbus.service.method(_interface)
668
# StopChecker - method
669
StopChecker = dbus.service.method(_interface)(stop_checker)
670
StopChecker.__name__ = "StopChecker"
675
384
def peer_certificate(session):
676
385
"Return the peer's OpenPGP certificate as a bytestring"
677
386
# If not an OpenPGP certificate...
678
if (gnutls.library.functions
679
.gnutls_certificate_type_get(session._c_object)
680
!= gnutls.library.constants.GNUTLS_CRT_OPENPGP):
387
if gnutls.library.functions.gnutls_certificate_type_get\
388
(session._c_object) \
389
!= gnutls.library.constants.GNUTLS_CRT_OPENPGP:
681
390
# ...do the normal thing
682
391
return session.peer_certificate
683
list_size = ctypes.c_uint(1)
684
cert_list = (gnutls.library.functions
685
.gnutls_certificate_get_peers
686
(session._c_object, ctypes.byref(list_size)))
687
if not bool(cert_list) and list_size.value != 0:
688
raise gnutls.errors.GNUTLSError("error getting peer"
392
list_size = ctypes.c_uint()
393
cert_list = gnutls.library.functions.gnutls_certificate_get_peers\
394
(session._c_object, ctypes.byref(list_size))
690
395
if list_size.value == 0:
692
397
cert = cert_list[0]
696
401
def fingerprint(openpgp):
697
402
"Convert an OpenPGP bytestring to a hexdigit fingerprint string"
698
403
# New GnuTLS "datum" with the OpenPGP public key
699
datum = (gnutls.library.types
700
.gnutls_datum_t(ctypes.cast(ctypes.c_char_p(openpgp),
703
ctypes.c_uint(len(openpgp))))
404
datum = gnutls.library.types.gnutls_datum_t\
405
(ctypes.cast(ctypes.c_char_p(openpgp),
406
ctypes.POINTER(ctypes.c_ubyte)),
407
ctypes.c_uint(len(openpgp)))
704
408
# New empty GnuTLS certificate
705
409
crt = gnutls.library.types.gnutls_openpgp_crt_t()
706
(gnutls.library.functions
707
.gnutls_openpgp_crt_init(ctypes.byref(crt)))
410
gnutls.library.functions.gnutls_openpgp_crt_init\
708
412
# Import the OpenPGP public key into the certificate
709
(gnutls.library.functions
710
.gnutls_openpgp_crt_import(crt, ctypes.byref(datum),
711
gnutls.library.constants
712
.GNUTLS_OPENPGP_FMT_RAW))
413
gnutls.library.functions.gnutls_openpgp_crt_import\
414
(crt, ctypes.byref(datum),
415
gnutls.library.constants.GNUTLS_OPENPGP_FMT_RAW)
713
416
# Verify the self signature in the key
714
crtverify = ctypes.c_uint()
715
(gnutls.library.functions
716
.gnutls_openpgp_crt_verify_self(crt, 0, ctypes.byref(crtverify)))
417
crtverify = ctypes.c_uint();
418
gnutls.library.functions.gnutls_openpgp_crt_verify_self\
419
(crt, 0, ctypes.byref(crtverify))
717
420
if crtverify.value != 0:
718
421
gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
719
422
raise gnutls.errors.CertificateSecurityError("Verify failed")
720
423
# New buffer for the fingerprint
721
buf = ctypes.create_string_buffer(20)
722
buf_len = ctypes.c_size_t()
424
buffer = ctypes.create_string_buffer(20)
425
buffer_length = ctypes.c_size_t()
723
426
# Get the fingerprint from the certificate into the buffer
724
(gnutls.library.functions
725
.gnutls_openpgp_crt_get_fingerprint(crt, ctypes.byref(buf),
726
ctypes.byref(buf_len)))
427
gnutls.library.functions.gnutls_openpgp_crt_get_fingerprint\
428
(crt, ctypes.byref(buffer), ctypes.byref(buffer_length))
727
429
# Deinit the certificate
728
430
gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
729
431
# Convert the buffer to a Python bytestring
730
fpr = ctypes.string_at(buf, buf_len.value)
432
fpr = ctypes.string_at(buffer, buffer_length.value)
731
433
# Convert the bytestring to hexadecimal notation
732
434
hex_fpr = u''.join(u"%02X" % ord(char) for char in fpr)
736
class TCP_handler(SocketServer.BaseRequestHandler, object):
438
class tcp_handler(SocketServer.BaseRequestHandler, object):
737
439
"""A TCP request handler class.
738
440
Instantiated by IPv6_TCPServer for each request to handle it.
739
441
Note: This will run in its own forked process."""
741
443
def handle(self):
742
444
logger.info(u"TCP connection from: %s",
743
unicode(self.client_address))
744
logger.debug(u"IPC Pipe FD: %d", self.server.pipe[1])
745
# Open IPC pipe to parent process
746
with closing(os.fdopen(self.server.pipe[1], "w", 1)) as ipc:
747
session = (gnutls.connection
748
.ClientSession(self.request,
752
line = self.request.makefile().readline()
753
logger.debug(u"Protocol version: %r", line)
755
if int(line.strip().split()[0]) > 1:
757
except (ValueError, IndexError, RuntimeError), error:
758
logger.error(u"Unknown protocol version: %s", error)
761
# Note: gnutls.connection.X509Credentials is really a
762
# generic GnuTLS certificate credentials object so long as
763
# no X.509 keys are added to it. Therefore, we can use it
764
# here despite using OpenPGP certificates.
766
#priority = ':'.join(("NONE", "+VERS-TLS1.1",
767
# "+AES-256-CBC", "+SHA1",
768
# "+COMP-NULL", "+CTYPE-OPENPGP",
770
# Use a fallback default, since this MUST be set.
771
priority = self.server.settings.get("priority", "NORMAL")
772
(gnutls.library.functions
773
.gnutls_priority_set_direct(session._c_object,
778
except gnutls.errors.GNUTLSError, error:
779
logger.warning(u"Handshake failed: %s", error)
780
# Do not run session.bye() here: the session is not
781
# established. Just abandon the request.
783
logger.debug(u"Handshake succeeded")
785
fpr = fingerprint(peer_certificate(session))
786
except (TypeError, gnutls.errors.GNUTLSError), error:
787
logger.warning(u"Bad certificate: %s", error)
790
logger.debug(u"Fingerprint: %s", fpr)
792
for c in self.server.clients:
793
if c.fingerprint == fpr:
797
logger.warning(u"Client not found for fingerprint: %s",
799
ipc.write("NOTFOUND %s\n" % fpr)
802
# Have to check if client.still_valid(), since it is
803
# possible that the client timed out while establishing
804
# the GnuTLS session.
805
if not client.still_valid():
806
logger.warning(u"Client %(name)s is invalid",
808
ipc.write("INVALID %s\n" % client.name)
811
ipc.write("SENDING %s\n" % client.name)
813
while sent_size < len(client.secret):
814
sent = session.send(client.secret[sent_size:])
815
logger.debug(u"Sent: %d, remaining: %d",
816
sent, len(client.secret)
817
- (sent_size + sent))
822
class ForkingMixInWithPipe(SocketServer.ForkingMixIn, object):
823
"""Like SocketServer.ForkingMixIn, but also pass a pipe.
824
Assumes a gobject.MainLoop event loop.
826
def process_request(self, request, client_address):
827
"""This overrides and wraps the original process_request().
828
This function creates a new pipe in self.pipe
830
self.pipe = os.pipe()
831
super(ForkingMixInWithPipe,
832
self).process_request(request, client_address)
833
os.close(self.pipe[1]) # close write end
834
# Call "handle_ipc" for both data and EOF events
835
gobject.io_add_watch(self.pipe[0],
836
gobject.IO_IN | gobject.IO_HUP,
838
def handle_ipc(source, condition):
839
"""Dummy function; override as necessary"""
844
class IPv6_TCPServer(ForkingMixInWithPipe,
845
SocketServer.TCPServer, object):
846
"""IPv6-capable TCP server. Accepts 'None' as address and/or port
445
unicode(self.client_address))
446
session = gnutls.connection.ClientSession\
447
(self.request, gnutls.connection.X509Credentials())
449
line = self.request.makefile().readline()
450
logger.debug(u"Protocol version: %r", line)
452
if int(line.strip().split()[0]) > 1:
454
except (ValueError, IndexError, RuntimeError), error:
455
logger.error(u"Unknown protocol version: %s", error)
458
# Note: gnutls.connection.X509Credentials is really a generic
459
# GnuTLS certificate credentials object so long as no X.509
460
# keys are added to it. Therefore, we can use it here despite
461
# using OpenPGP certificates.
463
#priority = ':'.join(("NONE", "+VERS-TLS1.1", "+AES-256-CBC",
464
# "+SHA1", "+COMP-NULL", "+CTYPE-OPENPGP",
466
priority = "NORMAL" # Fallback default, since this
468
if self.server.settings["priority"]:
469
priority = self.server.settings["priority"]
470
gnutls.library.functions.gnutls_priority_set_direct\
471
(session._c_object, priority, None);
475
except gnutls.errors.GNUTLSError, error:
476
logger.warning(u"Handshake failed: %s", error)
477
# Do not run session.bye() here: the session is not
478
# established. Just abandon the request.
481
fpr = fingerprint(peer_certificate(session))
482
except (TypeError, gnutls.errors.GNUTLSError), error:
483
logger.warning(u"Bad certificate: %s", error)
486
logger.debug(u"Fingerprint: %s", fpr)
488
for c in self.server.clients:
489
if c.fingerprint == fpr:
493
logger.warning(u"Client not found for fingerprint: %s",
497
# Have to check if client.still_valid(), since it is possible
498
# that the client timed out while establishing the GnuTLS
500
if not client.still_valid():
501
logger.warning(u"Client %(name)s is invalid",
506
while sent_size < len(client.secret):
507
sent = session.send(client.secret[sent_size:])
508
logger.debug(u"Sent: %d, remaining: %d",
509
sent, len(client.secret)
510
- (sent_size + sent))
515
class IPv6_TCPServer(SocketServer.ForkingTCPServer, object):
516
"""IPv6 TCP server. Accepts 'None' as address and/or port.
848
518
settings: Server settings
849
519
clients: Set() of Client objects
850
enabled: Boolean; whether this server is activated yet
852
521
address_family = socket.AF_INET6
853
522
def __init__(self, *args, **kwargs):
902
563
# ["interface"]))
903
return super(IPv6_TCPServer, self).server_bind()
904
def server_activate(self):
906
return super(IPv6_TCPServer, self).server_activate()
909
def handle_ipc(self, source, condition, file_objects={}):
911
gobject.IO_IN: "IN", # There is data to read.
912
gobject.IO_OUT: "OUT", # Data can be written (without
914
gobject.IO_PRI: "PRI", # There is urgent data to read.
915
gobject.IO_ERR: "ERR", # Error condition.
916
gobject.IO_HUP: "HUP" # Hung up (the connection has been
917
# broken, usually for pipes and
920
conditions_string = ' | '.join(name
922
condition_names.iteritems()
924
logger.debug("Handling IPC: FD = %d, condition = %s", source,
927
# Turn the pipe file descriptor into a Python file object
928
if source not in file_objects:
929
file_objects[source] = os.fdopen(source, "r", 1)
931
# Read a line from the file object
932
cmdline = file_objects[source].readline()
933
if not cmdline: # Empty line means end of file
935
file_objects[source].close()
936
del file_objects[source]
938
# Stop calling this function
941
logger.debug("IPC command: %r\n" % cmdline)
943
# Parse and act on command
944
cmd, args = cmdline.split(None, 1)
945
if cmd == "NOTFOUND":
946
if self.settings["use_dbus"]:
948
mandos_dbus_service.ClientNotFound(args)
949
elif cmd == "INVALID":
950
if self.settings["use_dbus"]:
951
for client in self.clients:
952
if client.name == args:
956
elif cmd == "SENDING":
957
for client in self.clients:
958
if client.name == args:
960
if self.settings["use_dbus"]:
962
client.ReceivedSecret()
965
logger.error("Unknown IPC command: %r", cmdline)
967
# Keep calling this function
564
return super(type(self), self).server_bind()
971
567
def string_to_delta(interval):
972
568
"""Parse a string and return a datetime.timedelta
974
570
>>> string_to_delta('7d')
975
571
datetime.timedelta(7)
976
572
>>> string_to_delta('60s')
1132
721
server_config.read(os.path.join(options.configdir, "mandos.conf"))
1133
722
# Convert the SafeConfigParser object to a dict
1134
723
server_settings = server_config.defaults()
1135
# Use the appropriate methods on the non-string config options
1136
server_settings["debug"] = server_config.getboolean("DEFAULT",
1138
server_settings["use_dbus"] = server_config.getboolean("DEFAULT",
1140
server_settings["use_ipv6"] = server_config.getboolean("DEFAULT",
1142
if server_settings["port"]:
1143
server_settings["port"] = server_config.getint("DEFAULT",
724
# Use getboolean on the boolean config option
725
server_settings["debug"] = server_config.getboolean\
1145
727
del server_config
1147
729
# Override the settings from the config file with command line
1148
730
# options, if set.
1149
731
for option in ("interface", "address", "port", "debug",
1150
"priority", "servicename", "configdir",
1151
"use_dbus", "use_ipv6"):
732
"priority", "servicename", "configdir"):
1152
733
value = getattr(options, option)
1153
734
if value is not None:
1154
735
server_settings[option] = value
1156
737
# Now we have our good server settings in "server_settings"
1158
##################################################################
1161
739
debug = server_settings["debug"]
1162
use_dbus = server_settings["use_dbus"]
1163
use_ipv6 = server_settings["use_ipv6"]
1166
742
syslogger.setLevel(logging.WARNING)
1167
743
console.setLevel(logging.WARNING)
1169
745
if server_settings["servicename"] != "Mandos":
1170
syslogger.setFormatter(logging.Formatter
1171
('Mandos (%s) [%%(process)d]:'
1172
' %%(levelname)s: %%(message)s'
746
syslogger.setFormatter(logging.Formatter\
747
('Mandos (%s): %%(levelname)s:'
1173
749
% server_settings["servicename"]))
1175
751
# Parse config file with clients
1176
752
client_defaults = { "timeout": "1h",
1177
753
"interval": "5m",
1178
"checker": "fping -q -- %%(host)s",
754
"checker": "fping -q -- %(host)s",
1181
757
client_config = ConfigParser.SafeConfigParser(client_defaults)
1182
758
client_config.read(os.path.join(server_settings["configdir"],
1183
759
"clients.conf"))
1185
global mandos_dbus_service
1186
mandos_dbus_service = None
1189
tcp_server = IPv6_TCPServer((server_settings["address"],
1190
server_settings["port"]),
1192
settings=server_settings,
1193
clients=clients, use_ipv6=use_ipv6)
1194
pidfilename = "/var/run/mandos.pid"
1196
pidfile = open(pidfilename, "w")
1198
logger.error("Could not open file %r", pidfilename)
1201
uid = pwd.getpwnam("_mandos").pw_uid
1202
gid = pwd.getpwnam("_mandos").pw_gid
1205
uid = pwd.getpwnam("mandos").pw_uid
1206
gid = pwd.getpwnam("mandos").pw_gid
1209
uid = pwd.getpwnam("nobody").pw_uid
1210
gid = pwd.getpwnam("nogroup").pw_gid
1217
except OSError, error:
1218
if error[0] != errno.EPERM:
1221
# Enable all possible GnuTLS debugging
1223
# "Use a log level over 10 to enable all debugging options."
1225
gnutls.library.functions.gnutls_global_set_log_level(11)
1227
@gnutls.library.types.gnutls_log_func
1228
def debug_gnutls(level, string):
1229
logger.debug("GnuTLS: %s", string[:-1])
1231
(gnutls.library.functions
1232
.gnutls_global_set_log_function(debug_gnutls))
1235
protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
1236
762
service = AvahiService(name = server_settings["servicename"],
1237
servicetype = "_mandos._tcp",
1238
protocol = protocol)
763
type = "_mandos._tcp", );
1239
764
if server_settings["interface"]:
1240
service.interface = (if_nametoindex
1241
(server_settings["interface"]))
765
service.interface = if_nametoindex\
766
(server_settings["interface"])
1243
768
global main_loop
1310
837
signal.signal(signal.SIGHUP, lambda signum, frame: sys.exit())
1311
838
signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit())
1314
class MandosDBusService(dbus.service.Object):
1315
"""A D-Bus proxy object"""
1317
dbus.service.Object.__init__(self, bus, "/")
1318
_interface = u"se.bsnet.fukt.Mandos"
1320
@dbus.service.signal(_interface, signature="oa{sv}")
1321
def ClientAdded(self, objpath, properties):
1325
@dbus.service.signal(_interface, signature="s")
1326
def ClientNotFound(self, fingerprint):
1330
@dbus.service.signal(_interface, signature="os")
1331
def ClientRemoved(self, objpath, name):
1335
@dbus.service.method(_interface, out_signature="ao")
1336
def GetAllClients(self):
1338
return dbus.Array(c.dbus_object_path for c in clients)
1340
@dbus.service.method(_interface, out_signature="a{oa{sv}}")
1341
def GetAllClientsWithProperties(self):
1343
return dbus.Dictionary(
1344
((c.dbus_object_path, c.GetAllProperties())
1348
@dbus.service.method(_interface, in_signature="o")
1349
def RemoveClient(self, object_path):
1352
if c.dbus_object_path == object_path:
1354
c.remove_from_connection()
1355
# Don't signal anything except ClientRemoved
1356
c.disable(signal=False)
1358
self.ClientRemoved(object_path, c.name)
1364
mandos_dbus_service = MandosDBusService()
1366
840
for client in clients:
1369
mandos_dbus_service.ClientAdded(client.dbus_object_path,
1370
client.GetAllProperties())
1374
tcp_server.server_activate()
843
tcp_server = IPv6_TCPServer((server_settings["address"],
844
server_settings["port"]),
846
settings=server_settings,
1376
848
# Find out what port we got
1377
849
service.port = tcp_server.socket.getsockname()[1]
1379
logger.info(u"Now listening on address %r, port %d,"
1380
" flowinfo %d, scope_id %d"
1381
% tcp_server.socket.getsockname())
1383
logger.info(u"Now listening on address %r, port %d"
1384
% tcp_server.socket.getsockname())
850
logger.info(u"Now listening on address %r, port %d, flowinfo %d,"
851
u" scope_id %d" % tcp_server.socket.getsockname())
1386
853
#service.interface = tcp_server.socket.getsockname()[3]