123
126
def rename(self):
124
127
"""Derived from the Avahi example code"""
125
128
if self.rename_count >= self.max_renames:
126
logger.critical(u"No suitable service name found after %i"
127
u" retries, exiting.", rename_count)
129
logger.critical(u"No suitable Zeroconf service name found"
130
u" after %i retries, exiting.",
128
132
raise AvahiServiceError("Too many renames")
129
133
self.name = server.GetAlternativeServiceName(self.name)
130
logger.info(u"Changing name to %r ...", str(self.name))
131
syslogger.setFormatter(logging.Formatter\
134
logger.info(u"Changing Zeroconf service name to %r ...",
136
syslogger.setFormatter(logging.Formatter
132
137
('Mandos (%s): %%(levelname)s:'
133
' %%(message)s' % self.name))
138
' %%(message)s' % self.name))
136
141
self.rename_count += 1
165
170
# End of Avahi example code
168
class Client(object):
173
def _datetime_to_dbus_struct(dt, variant_level=0):
174
"""Convert a UTC datetime.datetime() to a D-Bus struct.
175
The format is special to this application, since we could not find
176
any other standard way."""
177
return dbus.Struct((dbus.Int16(dt.year),
181
dbus.Byte(dt.minute),
182
dbus.Byte(dt.second),
183
dbus.UInt32(dt.microsecond)),
185
variant_level=variant_level)
188
class Client(dbus.service.Object):
169
189
"""A representation of a client host served by this server.
171
name: string; from the config file, used in log messages
191
name: string; from the config file, used in log messages
172
192
fingerprint: string (40 or 32 hexadecimal digits); used to
173
193
uniquely identify the client
174
secret: bytestring; sent verbatim (over TLS) to client
175
host: string; available for use by the checker command
176
created: datetime.datetime(); object creation, not client host
177
last_checked_ok: datetime.datetime() or None if not yet checked OK
178
timeout: datetime.timedelta(); How long from last_checked_ok
179
until this client is invalid
180
interval: datetime.timedelta(); How often to start a new checker
181
stop_hook: If set, called by stop() as stop_hook(self)
182
checker: subprocess.Popen(); a running checker process used
183
to see if the client lives.
184
'None' if no process is running.
194
secret: bytestring; sent verbatim (over TLS) to client
195
host: string; available for use by the checker command
196
created: datetime.datetime(); (UTC) object creation
197
last_started: datetime.datetime(); (UTC)
199
last_checked_ok: datetime.datetime(); (UTC) or None
200
timeout: datetime.timedelta(); How long from last_checked_ok
201
until this client is invalid
202
interval: datetime.timedelta(); How often to start a new checker
203
stop_hook: If set, called by stop() as stop_hook(self)
204
checker: subprocess.Popen(); a running checker process used
205
to see if the client lives.
206
'None' if no process is running.
185
207
checker_initiator_tag: a gobject event source tag, or None
186
208
stop_initiator_tag: - '' -
187
209
checker_callback_tag: - '' -
196
219
_interval_milliseconds: - '' -
198
221
def _set_timeout(self, timeout):
199
"Setter function for 'timeout' attribute"
222
"Setter function for the 'timeout' attribute"
200
223
self._timeout = timeout
201
224
self._timeout_milliseconds = ((self.timeout.days
202
225
* 24 * 60 * 60 * 1000)
203
226
+ (self.timeout.seconds * 1000)
204
227
+ (self.timeout.microseconds
206
timeout = property(lambda self: self._timeout,
230
self.PropertyChanged(dbus.String(u"timeout"),
231
(dbus.UInt64(self._timeout_milliseconds,
233
timeout = property(lambda self: self._timeout, _set_timeout)
209
236
def _set_interval(self, interval):
210
"Setter function for 'interval' attribute"
237
"Setter function for the 'interval' attribute"
211
238
self._interval = interval
212
239
self._interval_milliseconds = ((self.interval.days
213
240
* 24 * 60 * 60 * 1000)
216
243
+ (self.interval.microseconds
218
interval = property(lambda self: self._interval,
246
self.PropertyChanged(dbus.String(u"interval"),
247
(dbus.UInt64(self._interval_milliseconds,
249
interval = property(lambda self: self._interval, _set_interval)
220
250
del _set_interval
221
def __init__(self, name = None, stop_hook=None, config={}):
252
def __init__(self, name = None, stop_hook=None, config=None):
222
253
"""Note: the 'checker' key in 'config' sets the
223
254
'checker_command' attribute and *not* the 'checker'
256
self.dbus_object_path = (dbus.ObjectPath
258
+ name.replace(".", "_")))
259
dbus.service.Object.__init__(self, bus,
260
self.dbus_object_path)
226
264
logger.debug(u"Creating client %r", self.name)
227
265
# Uppercase and remove spaces from fingerprint for later
228
266
# comparison purposes with return value from the fingerprint()
230
self.fingerprint = config["fingerprint"].upper()\
268
self.fingerprint = (config["fingerprint"].upper()
232
270
logger.debug(u" Fingerprint: %s", self.fingerprint)
233
271
if "secret" in config:
234
272
self.secret = config["secret"].decode(u"base64")
235
273
elif "secfile" in config:
236
sf = open(config["secfile"])
237
self.secret = sf.read()
274
with closing(open(os.path.expanduser
276
(config["secfile"])))) as secfile:
277
self.secret = secfile.read()
240
279
raise TypeError(u"No secret or secfile for client %s"
242
281
self.host = config.get("host", "")
243
self.created = datetime.datetime.now()
282
self.created = datetime.datetime.utcnow()
284
self.last_started = None
244
285
self.last_checked_ok = None
245
286
self.timeout = string_to_delta(config["timeout"])
246
287
self.interval = string_to_delta(config["interval"])
249
290
self.checker_initiator_tag = None
250
291
self.stop_initiator_tag = None
251
292
self.checker_callback_tag = None
252
self.check_command = config["checker"]
293
self.checker_command = config["checker"]
254
296
"""Start this client's checker and timeout hooks"""
297
self.last_started = datetime.datetime.utcnow()
255
298
# Schedule a new checker to be started an 'interval' from now,
256
299
# and every interval from then on.
257
self.checker_initiator_tag = gobject.timeout_add\
258
(self._interval_milliseconds,
300
self.checker_initiator_tag = (gobject.timeout_add
301
(self._interval_milliseconds,
260
303
# Also start a new checker *right now*.
261
304
self.start_checker()
262
305
# Schedule a stop() when 'timeout' has passed
263
self.stop_initiator_tag = gobject.timeout_add\
264
(self._timeout_milliseconds,
306
self.stop_initiator_tag = (gobject.timeout_add
307
(self._timeout_milliseconds,
311
self.PropertyChanged(dbus.String(u"started"),
312
dbus.Boolean(True, variant_level=1))
313
self.PropertyChanged(dbus.String(u"last_started"),
314
(_datetime_to_dbus_struct
315
(self.last_started, variant_level=1)))
268
The possibility that a client might be restarted is left open,
269
but not currently used."""
270
# If this client doesn't have a secret, it is already stopped.
271
if hasattr(self, "secret") and self.secret:
272
logger.info(u"Stopping client %s", self.name)
318
"""Stop this client."""
319
if not getattr(self, "started", False):
321
logger.info(u"Stopping client %s", self.name)
276
322
if getattr(self, "stop_initiator_tag", False):
277
323
gobject.source_remove(self.stop_initiator_tag)
278
324
self.stop_initiator_tag = None
282
328
self.stop_checker()
283
329
if self.stop_hook:
284
330
self.stop_hook(self)
333
self.PropertyChanged(dbus.String(u"started"),
334
dbus.Boolean(False, variant_level=1))
285
335
# Do not run this again if called by a gobject.timeout_add
287
338
def __del__(self):
288
339
self.stop_hook = None
290
def checker_callback(self, pid, condition):
342
def checker_callback(self, pid, condition, command):
291
343
"""The checker has completed, so take appropriate actions."""
292
now = datetime.datetime.now()
293
344
self.checker_callback_tag = None
294
345
self.checker = None
295
if os.WIFEXITED(condition) \
296
and (os.WEXITSTATUS(condition) == 0):
347
self.PropertyChanged(dbus.String(u"checker_running"),
348
dbus.Boolean(False, variant_level=1))
349
if (os.WIFEXITED(condition)
350
and (os.WEXITSTATUS(condition) == 0)):
297
351
logger.info(u"Checker for %(name)s succeeded",
299
self.last_checked_ok = now
300
gobject.source_remove(self.stop_initiator_tag)
301
self.stop_initiator_tag = gobject.timeout_add\
302
(self._timeout_milliseconds,
354
self.CheckerCompleted(dbus.Boolean(True),
355
dbus.UInt16(condition),
356
dbus.String(command))
304
358
elif not os.WIFEXITED(condition):
305
359
logger.warning(u"Checker for %(name)s crashed?",
362
self.CheckerCompleted(dbus.Boolean(False),
363
dbus.UInt16(condition),
364
dbus.String(command))
308
366
logger.info(u"Checker for %(name)s failed",
369
self.CheckerCompleted(dbus.Boolean(False),
370
dbus.UInt16(condition),
371
dbus.String(command))
373
def bump_timeout(self):
374
"""Bump up the timeout for this client.
375
This should only be called when the client has been seen,
378
self.last_checked_ok = datetime.datetime.utcnow()
379
gobject.source_remove(self.stop_initiator_tag)
380
self.stop_initiator_tag = (gobject.timeout_add
381
(self._timeout_milliseconds,
383
self.PropertyChanged(dbus.String(u"last_checked_ok"),
384
(_datetime_to_dbus_struct
385
(self.last_checked_ok,
310
388
def start_checker(self):
311
389
"""Start a new checker subprocess if one is not running.
312
390
If a checker already exists, leave it running and do
369
453
if error.errno != errno.ESRCH: # No such process
371
455
self.checker = None
456
self.PropertyChanged(dbus.String(u"checker_running"),
457
dbus.Boolean(False, variant_level=1))
372
459
def still_valid(self):
373
460
"""Has the timeout not yet passed for this client?"""
374
now = datetime.datetime.now()
461
if not getattr(self, "started", False):
463
now = datetime.datetime.utcnow()
375
464
if self.last_checked_ok is None:
376
465
return now < (self.created + self.timeout)
378
467
return now < (self.last_checked_ok + self.timeout)
469
## D-Bus methods & signals
470
_interface = u"org.mandos_system.Mandos.Client"
472
# BumpTimeout - method
473
BumpTimeout = dbus.service.method(_interface)(bump_timeout)
474
BumpTimeout.__name__ = "BumpTimeout"
476
# CheckerCompleted - signal
477
@dbus.service.signal(_interface, signature="bqs")
478
def CheckerCompleted(self, success, condition, command):
482
# CheckerStarted - signal
483
@dbus.service.signal(_interface, signature="s")
484
def CheckerStarted(self, command):
488
# GetAllProperties - method
489
@dbus.service.method(_interface, out_signature="a{sv}")
490
def GetAllProperties(self):
492
return dbus.Dictionary({
494
dbus.String(self.name, variant_level=1),
495
dbus.String("fingerprint"):
496
dbus.String(self.fingerprint, variant_level=1),
498
dbus.String(self.host, variant_level=1),
499
dbus.String("created"):
500
_datetime_to_dbus_struct(self.created,
502
dbus.String("last_started"):
503
(_datetime_to_dbus_struct(self.last_started,
505
if self.last_started is not None
506
else dbus.Boolean(False, variant_level=1)),
507
dbus.String("started"):
508
dbus.Boolean(self.started, variant_level=1),
509
dbus.String("last_checked_ok"):
510
(_datetime_to_dbus_struct(self.last_checked_ok,
512
if self.last_checked_ok is not None
513
else dbus.Boolean (False, variant_level=1)),
514
dbus.String("timeout"):
515
dbus.UInt64(self._timeout_milliseconds,
517
dbus.String("interval"):
518
dbus.UInt64(self._interval_milliseconds,
520
dbus.String("checker"):
521
dbus.String(self.checker_command,
523
dbus.String("checker_running"):
524
dbus.Boolean(self.checker is not None,
528
# IsStillValid - method
529
IsStillValid = (dbus.service.method(_interface, out_signature="b")
531
IsStillValid.__name__ = "IsStillValid"
533
# PropertyChanged - signal
534
@dbus.service.signal(_interface, signature="sv")
535
def PropertyChanged(self, property, value):
539
# SetChecker - method
540
@dbus.service.method(_interface, in_signature="s")
541
def SetChecker(self, checker):
542
"D-Bus setter method"
543
self.checker_command = checker
546
@dbus.service.method(_interface, in_signature="s")
547
def SetHost(self, host):
548
"D-Bus setter method"
551
# SetInterval - method
552
@dbus.service.method(_interface, in_signature="t")
553
def SetInterval(self, milliseconds):
554
self.interval = datetime.timdeelta(0, 0, 0, milliseconds)
557
@dbus.service.method(_interface, in_signature="ay",
559
def SetSecret(self, secret):
560
"D-Bus setter method"
561
self.secret = str(secret)
563
# SetTimeout - method
564
@dbus.service.method(_interface, in_signature="t")
565
def SetTimeout(self, milliseconds):
566
self.timeout = datetime.timedelta(0, 0, 0, milliseconds)
569
Start = dbus.service.method(_interface)(start)
570
Start.__name__ = "Start"
572
# StartChecker - method
573
@dbus.service.method(_interface)
574
def StartChecker(self):
579
@dbus.service.method(_interface)
584
# StopChecker - method
585
StopChecker = dbus.service.method(_interface)(stop_checker)
586
StopChecker.__name__ = "StopChecker"
381
591
def peer_certificate(session):
382
592
"Return the peer's OpenPGP certificate as a bytestring"
383
593
# If not an OpenPGP certificate...
384
if gnutls.library.functions.gnutls_certificate_type_get\
385
(session._c_object) \
386
!= gnutls.library.constants.GNUTLS_CRT_OPENPGP:
594
if (gnutls.library.functions
595
.gnutls_certificate_type_get(session._c_object)
596
!= gnutls.library.constants.GNUTLS_CRT_OPENPGP):
387
597
# ...do the normal thing
388
598
return session.peer_certificate
389
599
list_size = ctypes.c_uint()
390
cert_list = gnutls.library.functions.gnutls_certificate_get_peers\
391
(session._c_object, ctypes.byref(list_size))
600
cert_list = (gnutls.library.functions
601
.gnutls_certificate_get_peers
602
(session._c_object, ctypes.byref(list_size)))
392
603
if list_size.value == 0:
394
605
cert = cert_list[0]
398
609
def fingerprint(openpgp):
399
610
"Convert an OpenPGP bytestring to a hexdigit fingerprint string"
400
611
# New GnuTLS "datum" with the OpenPGP public key
401
datum = gnutls.library.types.gnutls_datum_t\
402
(ctypes.cast(ctypes.c_char_p(openpgp),
403
ctypes.POINTER(ctypes.c_ubyte)),
404
ctypes.c_uint(len(openpgp)))
612
datum = (gnutls.library.types
613
.gnutls_datum_t(ctypes.cast(ctypes.c_char_p(openpgp),
616
ctypes.c_uint(len(openpgp))))
405
617
# New empty GnuTLS certificate
406
618
crt = gnutls.library.types.gnutls_openpgp_crt_t()
407
gnutls.library.functions.gnutls_openpgp_crt_init\
619
(gnutls.library.functions
620
.gnutls_openpgp_crt_init(ctypes.byref(crt)))
409
621
# Import the OpenPGP public key into the certificate
410
gnutls.library.functions.gnutls_openpgp_crt_import\
411
(crt, ctypes.byref(datum),
412
gnutls.library.constants.GNUTLS_OPENPGP_FMT_RAW)
622
(gnutls.library.functions
623
.gnutls_openpgp_crt_import(crt, ctypes.byref(datum),
624
gnutls.library.constants
625
.GNUTLS_OPENPGP_FMT_RAW))
413
626
# Verify the self signature in the key
414
crtverify = ctypes.c_uint();
415
gnutls.library.functions.gnutls_openpgp_crt_verify_self\
416
(crt, ctypes.c_uint(0), ctypes.byref(crtverify))
627
crtverify = ctypes.c_uint()
628
(gnutls.library.functions
629
.gnutls_openpgp_crt_verify_self(crt, 0, ctypes.byref(crtverify)))
417
630
if crtverify.value != 0:
418
631
gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
419
632
raise gnutls.errors.CertificateSecurityError("Verify failed")
420
633
# New buffer for the fingerprint
421
buffer = ctypes.create_string_buffer(20)
422
buffer_length = ctypes.c_size_t()
634
buf = ctypes.create_string_buffer(20)
635
buf_len = ctypes.c_size_t()
423
636
# Get the fingerprint from the certificate into the buffer
424
gnutls.library.functions.gnutls_openpgp_crt_get_fingerprint\
425
(crt, ctypes.byref(buffer), ctypes.byref(buffer_length))
637
(gnutls.library.functions
638
.gnutls_openpgp_crt_get_fingerprint(crt, ctypes.byref(buf),
639
ctypes.byref(buf_len)))
426
640
# Deinit the certificate
427
641
gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
428
642
# Convert the buffer to a Python bytestring
429
fpr = ctypes.string_at(buffer, buffer_length.value)
643
fpr = ctypes.string_at(buf, buf_len.value)
430
644
# Convert the bytestring to hexadecimal notation
431
645
hex_fpr = u''.join(u"%02X" % ord(char) for char in fpr)
435
class tcp_handler(SocketServer.BaseRequestHandler, object):
649
class TCP_handler(SocketServer.BaseRequestHandler, object):
436
650
"""A TCP request handler class.
437
651
Instantiated by IPv6_TCPServer for each request to handle it.
438
652
Note: This will run in its own forked process."""
440
654
def handle(self):
441
655
logger.info(u"TCP connection from: %s",
442
unicode(self.client_address))
443
session = gnutls.connection.ClientSession\
444
(self.request, gnutls.connection.X509Credentials())
656
unicode(self.client_address))
657
session = (gnutls.connection
658
.ClientSession(self.request,
446
662
line = self.request.makefile().readline()
447
663
logger.debug(u"Protocol version: %r", line)
755
974
client_config.read(os.path.join(server_settings["configdir"],
978
tcp_server = IPv6_TCPServer((server_settings["address"],
979
server_settings["port"]),
981
settings=server_settings,
983
pidfilename = "/var/run/mandos.pid"
985
pidfile = open(pidfilename, "w")
986
except IOError, error:
987
logger.error("Could not open file %r", pidfilename)
990
uid = pwd.getpwnam("_mandos").pw_uid
993
uid = pwd.getpwnam("mandos").pw_uid
996
uid = pwd.getpwnam("nobody").pw_uid
1000
gid = pwd.getpwnam("_mandos").pw_gid
1003
gid = pwd.getpwnam("mandos").pw_gid
1006
gid = pwd.getpwnam("nogroup").pw_gid
1012
except OSError, error:
1013
if error[0] != errno.EPERM:
759
1017
service = AvahiService(name = server_settings["servicename"],
760
type = "_mandos._tcp", );
1018
servicetype = "_mandos._tcp", )
761
1019
if server_settings["interface"]:
762
service.interface = if_nametoindex(server_settings["interface"])
1020
service.interface = (if_nametoindex
1021
(server_settings["interface"]))
764
1023
global main_loop
833
1087
signal.signal(signal.SIGHUP, lambda signum, frame: sys.exit())
834
1088
signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit())
1090
class MandosServer(dbus.service.Object):
1091
"""A D-Bus proxy object"""
1093
dbus.service.Object.__init__(self, bus,
1095
_interface = u"org.mandos_system.Mandos"
1097
@dbus.service.signal(_interface, signature="oa{sv}")
1098
def ClientAdded(self, objpath, properties):
1102
@dbus.service.signal(_interface, signature="o")
1103
def ClientRemoved(self, objpath):
1107
@dbus.service.method(_interface, out_signature="ao")
1108
def GetAllClients(self):
1109
return dbus.Array(c.dbus_object_path for c in clients)
1111
@dbus.service.method(_interface, out_signature="a{oa{sv}}")
1112
def GetAllClientsWithProperties(self):
1113
return dbus.Dictionary(
1114
((c.dbus_object_path, c.GetAllProperties())
1118
@dbus.service.method(_interface, in_signature="o")
1119
def RemoveClient(self, object_path):
1121
if c.dbus_object_path == object_path:
1129
mandos_server = MandosServer()
836
1131
for client in clients:
1133
mandos_server.ClientAdded(client.dbus_object_path,
1134
client.GetAllProperties())
839
tcp_server = IPv6_TCPServer((server_settings["address"],
840
server_settings["port"]),
842
settings=server_settings,
1138
tcp_server.server_activate()
844
1140
# Find out what port we got
845
1141
service.port = tcp_server.socket.getsockname()[1]
846
1142
logger.info(u"Now listening on address %r, port %d, flowinfo %d,"