81
85
except ImportError:
82
86
SO_BINDTODEVICE = None
87
#logger = logging.getLogger('mandos')
88
logger = logging.Logger('mandos')
89
stored_state_file = "clients.pickle"
91
logger = logging.getLogger()
89
92
syslogger = (logging.handlers.SysLogHandler
90
93
(facility = logging.handlers.SysLogHandler.LOG_DAEMON,
91
94
address = str("/dev/log")))
92
syslogger.setFormatter(logging.Formatter
93
('Mandos [%(process)d]: %(levelname)s:'
95
logger.addHandler(syslogger)
97
console = logging.StreamHandler()
98
console.setFormatter(logging.Formatter('%(name)s [%(process)d]:'
101
logger.addHandler(console)
97
if_nametoindex = (ctypes.cdll.LoadLibrary
98
(ctypes.util.find_library("c"))
100
except (OSError, AttributeError):
101
def if_nametoindex(interface):
102
"Get an interface index the hard way, i.e. using fcntl()"
103
SIOCGIFINDEX = 0x8933 # From /usr/include/linux/sockios.h
104
with contextlib.closing(socket.socket()) as s:
105
ifreq = fcntl.ioctl(s, SIOCGIFINDEX,
106
struct.pack(str("16s16x"),
108
interface_index = struct.unpack(str("I"),
110
return interface_index
113
def initlogger(debug, level=logging.WARNING):
114
"""init logger and add loglevel"""
116
syslogger.setFormatter(logging.Formatter
117
('Mandos [%(process)d]: %(levelname)s:'
119
logger.addHandler(syslogger)
122
console = logging.StreamHandler()
123
console.setFormatter(logging.Formatter('%(asctime)s %(name)s'
127
logger.addHandler(console)
128
logger.setLevel(level)
131
class PGPError(Exception):
132
"""Exception if encryption/decryption fails"""
136
class PGPEngine(object):
137
"""A simple class for OpenPGP symmetric encryption & decryption"""
139
self.gnupg = GnuPGInterface.GnuPG()
140
self.tempdir = tempfile.mkdtemp(prefix="mandos-")
141
self.gnupg = GnuPGInterface.GnuPG()
142
self.gnupg.options.meta_interactive = False
143
self.gnupg.options.homedir = self.tempdir
144
self.gnupg.options.extra_args.extend(['--force-mdc',
151
def __exit__ (self, exc_type, exc_value, traceback):
159
if self.tempdir is not None:
160
# Delete contents of tempdir
161
for root, dirs, files in os.walk(self.tempdir,
163
for filename in files:
164
os.remove(os.path.join(root, filename))
166
os.rmdir(os.path.join(root, dirname))
168
os.rmdir(self.tempdir)
171
def password_encode(self, password):
172
# Passphrase can not be empty and can not contain newlines or
173
# NUL bytes. So we prefix it and hex encode it.
174
return b"mandos" + binascii.hexlify(password)
176
def encrypt(self, data, password):
177
self.gnupg.passphrase = self.password_encode(password)
178
with open(os.devnull) as devnull:
180
proc = self.gnupg.run(['--symmetric'],
181
create_fhs=['stdin', 'stdout'],
182
attach_fhs={'stderr': devnull})
183
with contextlib.closing(proc.handles['stdin']) as f:
185
with contextlib.closing(proc.handles['stdout']) as f:
186
ciphertext = f.read()
190
self.gnupg.passphrase = None
193
def decrypt(self, data, password):
194
self.gnupg.passphrase = self.password_encode(password)
195
with open(os.devnull) as devnull:
197
proc = self.gnupg.run(['--decrypt'],
198
create_fhs=['stdin', 'stdout'],
199
attach_fhs={'stderr': devnull})
200
with contextlib.closing(proc.handles['stdin'] ) as f:
202
with contextlib.closing(proc.handles['stdout']) as f:
203
decrypted_plaintext = f.read()
207
self.gnupg.passphrase = None
208
return decrypted_plaintext
103
212
class AvahiError(Exception):
104
213
def __init__(self, value, *args, **kwargs):
158
268
" after %i retries, exiting.",
159
269
self.rename_count)
160
270
raise AvahiServiceError("Too many renames")
161
self.name = unicode(self.server.GetAlternativeServiceName(self.name))
271
self.name = unicode(self.server
272
.GetAlternativeServiceName(self.name))
162
273
logger.info("Changing Zeroconf service name to %r ...",
164
syslogger.setFormatter(logging.Formatter
165
('Mandos (%s) [%%(process)d]:'
166
' %%(levelname)s: %%(message)s'
171
except dbus.exceptions.DBusException, error:
278
except dbus.exceptions.DBusException as error:
172
279
logger.critical("DBusException: %s", error)
175
282
self.rename_count += 1
176
283
def remove(self):
177
284
"""Derived from the Avahi example code"""
285
if self.entry_group_state_changed_match is not None:
286
self.entry_group_state_changed_match.remove()
287
self.entry_group_state_changed_match = None
178
288
if self.group is not None:
179
289
self.group.Reset()
181
291
"""Derived from the Avahi example code"""
182
293
if self.group is None:
183
294
self.group = dbus.Interface(
184
295
self.bus.get_object(avahi.DBUS_NAME,
185
296
self.server.EntryGroupNew()),
186
297
avahi.DBUS_INTERFACE_ENTRY_GROUP)
187
self.group.connect_to_signal('StateChanged',
189
.entry_group_state_changed)
298
self.entry_group_state_changed_match = (
299
self.group.connect_to_signal(
300
'StateChanged', self.entry_group_state_changed))
190
301
logger.debug("Adding Zeroconf service '%s' of type '%s' ...",
191
302
self.name, self.type)
192
303
self.group.AddService(
215
326
def cleanup(self):
216
327
"""Derived from the Avahi example code"""
217
328
if self.group is not None:
331
except (dbus.exceptions.UnknownMethodException,
332
dbus.exceptions.DBusException):
219
334
self.group = None
220
def server_state_changed(self, state):
336
def server_state_changed(self, state, error=None):
221
337
"""Derived from the Avahi example code"""
222
338
logger.debug("Avahi server state change: %i", state)
223
if state == avahi.SERVER_COLLISION:
224
logger.error("Zeroconf server name collision")
339
bad_states = { avahi.SERVER_INVALID:
340
"Zeroconf server invalid",
341
avahi.SERVER_REGISTERING: None,
342
avahi.SERVER_COLLISION:
343
"Zeroconf server name collision",
344
avahi.SERVER_FAILURE:
345
"Zeroconf server failure" }
346
if state in bad_states:
347
if bad_states[state] is not None:
349
logger.error(bad_states[state])
351
logger.error(bad_states[state] + ": %r", error)
226
353
elif state == avahi.SERVER_RUNNING:
357
logger.debug("Unknown state: %r", state)
359
logger.debug("Unknown state: %r: %r", state, error)
228
360
def activate(self):
229
361
"""Derived from the Avahi example code"""
230
362
if self.server is None:
231
363
self.server = dbus.Interface(
232
364
self.bus.get_object(avahi.DBUS_NAME,
233
avahi.DBUS_PATH_SERVER),
365
avahi.DBUS_PATH_SERVER,
366
follow_name_owner_changes=True),
234
367
avahi.DBUS_INTERFACE_SERVER)
235
368
self.server.connect_to_signal("StateChanged",
236
369
self.server_state_changed)
237
370
self.server_state_changed(self.server.GetState())
372
class AvahiServiceToSyslog(AvahiService):
374
"""Add the new name to the syslog messages"""
375
ret = AvahiService.rename(self)
376
syslogger.setFormatter(logging.Formatter
377
('Mandos (%s) [%%(process)d]:'
378
' %%(levelname)s: %%(message)s'
382
def timedelta_to_milliseconds(td):
383
"Convert a datetime.timedelta() to milliseconds"
384
return ((td.days * 24 * 60 * 60 * 1000)
385
+ (td.seconds * 1000)
386
+ (td.microseconds // 1000))
240
388
class Client(object):
241
389
"""A representation of a client host served by this server.
244
_approved: bool(); 'None' if not yet approved/disapproved
392
approved: bool(); 'None' if not yet approved/disapproved
245
393
approval_delay: datetime.timedelta(); Time to wait for approval
246
394
approval_duration: datetime.timedelta(); Duration of one approval
247
395
checker: subprocess.Popen(); a running checker process used
264
413
interval: datetime.timedelta(); How often to start a new checker
265
414
last_approval_request: datetime.datetime(); (UTC) or None
266
415
last_checked_ok: datetime.datetime(); (UTC) or None
267
last_enabled: datetime.datetime(); (UTC)
416
last_checker_status: integer between 0 and 255 reflecting exit
417
status of last checker. -1 reflects crashed
419
last_enabled: datetime.datetime(); (UTC) or None
268
420
name: string; from the config file, used in log messages and
269
421
D-Bus identifiers
270
422
secret: bytestring; sent verbatim (over TLS) to client
271
423
timeout: datetime.timedelta(); How long from last_checked_ok
272
424
until this client is disabled
425
extended_timeout: extra long timeout when password has been sent
273
426
runtime_expansions: Allowed attributes for runtime expansion.
427
expires: datetime.datetime(); time (UTC) when a client will be
276
431
runtime_expansions = ("approval_delay", "approval_duration",
277
432
"created", "enabled", "fingerprint",
278
433
"host", "interval", "last_checked_ok",
279
434
"last_enabled", "name", "timeout")
282
def _timedelta_to_milliseconds(td):
283
"Convert a datetime.timedelta() to milliseconds"
284
return ((td.days * 24 * 60 * 60 * 1000)
285
+ (td.seconds * 1000)
286
+ (td.microseconds // 1000))
435
client_defaults = { "timeout": "5m",
436
"extended_timeout": "15m",
438
"checker": "fping -q -- %%(host)s",
440
"approval_delay": "0s",
441
"approval_duration": "1s",
442
"approved_by_default": "True",
288
446
def timeout_milliseconds(self):
289
447
"Return the 'timeout' attribute in milliseconds"
290
return self._timedelta_to_milliseconds(self.timeout)
448
return timedelta_to_milliseconds(self.timeout)
450
def extended_timeout_milliseconds(self):
451
"Return the 'extended_timeout' attribute in milliseconds"
452
return timedelta_to_milliseconds(self.extended_timeout)
292
454
def interval_milliseconds(self):
293
455
"Return the 'interval' attribute in milliseconds"
294
return self._timedelta_to_milliseconds(self.interval)
456
return timedelta_to_milliseconds(self.interval)
296
458
def approval_delay_milliseconds(self):
297
return self._timedelta_to_milliseconds(self.approval_delay)
299
def __init__(self, name = None, disable_hook=None, config=None):
459
return timedelta_to_milliseconds(self.approval_delay)
462
def config_parser(config):
463
"""Construct a new dict of client settings of this form:
464
{ client_name: {setting_name: value, ...}, ...}
465
with exceptions for any special settings as defined above.
466
NOTE: Must be a pure function. Must return the same result
467
value given the same arguments.
470
for client_name in config.sections():
471
section = dict(config.items(client_name))
472
client = settings[client_name] = {}
474
client["host"] = section["host"]
475
# Reformat values from string types to Python types
476
client["approved_by_default"] = config.getboolean(
477
client_name, "approved_by_default")
478
client["enabled"] = config.getboolean(client_name,
481
client["fingerprint"] = (section["fingerprint"].upper()
483
if "secret" in section:
484
client["secret"] = section["secret"].decode("base64")
485
elif "secfile" in section:
486
with open(os.path.expanduser(os.path.expandvars
487
(section["secfile"])),
489
client["secret"] = secfile.read()
491
raise TypeError("No secret or secfile for section %s"
493
client["timeout"] = string_to_delta(section["timeout"])
494
client["extended_timeout"] = string_to_delta(
495
section["extended_timeout"])
496
client["interval"] = string_to_delta(section["interval"])
497
client["approval_delay"] = string_to_delta(
498
section["approval_delay"])
499
client["approval_duration"] = string_to_delta(
500
section["approval_duration"])
501
client["checker_command"] = section["checker"]
502
client["last_approval_request"] = None
503
client["last_checked_ok"] = None
504
client["last_checker_status"] = None
509
def __init__(self, settings, name = None):
300
510
"""Note: the 'checker' key in 'config' sets the
301
511
'checker_command' attribute and *not* the 'checker'
514
# adding all client settings
515
for setting, value in settings.iteritems():
516
setattr(self, setting, value)
519
if not hasattr(self, "last_enabled"):
520
self.last_enabled = datetime.datetime.utcnow()
521
if not hasattr(self, "expires"):
522
self.expires = (datetime.datetime.utcnow()
525
self.last_enabled = None
306
528
logger.debug("Creating client %r", self.name)
307
529
# Uppercase and remove spaces from fingerprint for later
308
530
# comparison purposes with return value from the fingerprint()
310
self.fingerprint = (config["fingerprint"].upper()
312
532
logger.debug(" Fingerprint: %s", self.fingerprint)
313
if "secret" in config:
314
self.secret = config["secret"].decode("base64")
315
elif "secfile" in config:
316
with open(os.path.expanduser(os.path.expandvars
317
(config["secfile"])),
319
self.secret = secfile.read()
321
raise TypeError("No secret or secfile for client %s"
323
self.host = config.get("host", "")
324
self.created = datetime.datetime.utcnow()
326
self.last_approval_request = None
327
self.last_enabled = None
328
self.last_checked_ok = None
329
self.timeout = string_to_delta(config["timeout"])
330
self.interval = string_to_delta(config["interval"])
331
self.disable_hook = disable_hook
533
self.created = settings.get("created",
534
datetime.datetime.utcnow())
536
# attributes specific for this server instance
332
537
self.checker = None
333
538
self.checker_initiator_tag = None
334
539
self.disable_initiator_tag = None
335
540
self.checker_callback_tag = None
336
self.checker_command = config["checker"]
337
541
self.current_checker_command = None
338
self.last_connect = None
339
self._approved = None
340
self.approved_by_default = config.get("approved_by_default",
342
543
self.approvals_pending = 0
343
self.approval_delay = string_to_delta(
344
config["approval_delay"])
345
self.approval_duration = string_to_delta(
346
config["approval_duration"])
347
self.changedstate = multiprocessing_manager.Condition(multiprocessing_manager.Lock())
544
self.changedstate = (multiprocessing_manager
545
.Condition(multiprocessing_manager
547
self.client_structure = [attr for attr in
548
self.__dict__.iterkeys()
549
if not attr.startswith("_")]
550
self.client_structure.append("client_structure")
552
for name, t in inspect.getmembers(type(self),
556
if not name.startswith("_"):
557
self.client_structure.append(name)
559
# Send notice to process children that client state has changed
349
560
def send_changedstate(self):
350
self.changedstate.acquire()
351
self.changedstate.notify_all()
352
self.changedstate.release()
561
with self.changedstate:
562
self.changedstate.notify_all()
354
564
def enable(self):
355
565
"""Start this client's checker and timeout hooks"""
356
566
if getattr(self, "enabled", False):
357
567
# Already enabled
359
569
self.send_changedstate()
570
self.expires = datetime.datetime.utcnow() + self.timeout
360
572
self.last_enabled = datetime.datetime.utcnow()
361
# Schedule a new checker to be started an 'interval' from now,
362
# and every interval from then on.
363
self.checker_initiator_tag = (gobject.timeout_add
364
(self.interval_milliseconds(),
366
# Schedule a disable() when 'timeout' has passed
367
self.disable_initiator_tag = (gobject.timeout_add
368
(self.timeout_milliseconds(),
371
# Also start a new checker *right now*.
374
575
def disable(self, quiet=True):
375
576
"""Disable this client."""
704
921
xmlstring = document.toxml("utf-8")
705
922
document.unlink()
706
923
except (AttributeError, xml.dom.DOMException,
707
xml.parsers.expat.ExpatError), error:
924
xml.parsers.expat.ExpatError) as error:
708
925
logger.error("Failed to override Introspection method",
930
def datetime_to_dbus (dt, variant_level=0):
931
"""Convert a UTC datetime.datetime() to a D-Bus type."""
933
return dbus.String("", variant_level = variant_level)
934
return dbus.String(dt.isoformat(),
935
variant_level=variant_level)
938
class AlternateDBusNamesMetaclass(DBusObjectWithProperties
940
"""Applied to an empty subclass of a D-Bus object, this metaclass
941
will add additional D-Bus attributes matching a certain pattern.
943
def __new__(mcs, name, bases, attr):
944
# Go through all the base classes which could have D-Bus
945
# methods, signals, or properties in them
946
for base in (b for b in bases
947
if issubclass(b, dbus.service.Object)):
948
# Go though all attributes of the base class
949
for attrname, attribute in inspect.getmembers(base):
950
# Ignore non-D-Bus attributes, and D-Bus attributes
951
# with the wrong interface name
952
if (not hasattr(attribute, "_dbus_interface")
953
or not attribute._dbus_interface
954
.startswith("se.recompile.Mandos")):
956
# Create an alternate D-Bus interface name based on
958
alt_interface = (attribute._dbus_interface
959
.replace("se.recompile.Mandos",
960
"se.bsnet.fukt.Mandos"))
961
# Is this a D-Bus signal?
962
if getattr(attribute, "_dbus_is_signal", False):
963
# Extract the original non-method function by
965
nonmethod_func = (dict(
966
zip(attribute.func_code.co_freevars,
967
attribute.__closure__))["func"]
969
# Create a new, but exactly alike, function
970
# object, and decorate it to be a new D-Bus signal
971
# with the alternate D-Bus interface name
972
new_function = (dbus.service.signal
974
attribute._dbus_signature)
976
nonmethod_func.func_code,
977
nonmethod_func.func_globals,
978
nonmethod_func.func_name,
979
nonmethod_func.func_defaults,
980
nonmethod_func.func_closure)))
981
# Define a creator of a function to call both the
982
# old and new functions, so both the old and new
983
# signals gets sent when the function is called
984
def fixscope(func1, func2):
985
"""This function is a scope container to pass
986
func1 and func2 to the "call_both" function
987
outside of its arguments"""
988
def call_both(*args, **kwargs):
989
"""This function will emit two D-Bus
990
signals by calling func1 and func2"""
991
func1(*args, **kwargs)
992
func2(*args, **kwargs)
994
# Create the "call_both" function and add it to
996
attr[attrname] = fixscope(attribute,
998
# Is this a D-Bus method?
999
elif getattr(attribute, "_dbus_is_method", False):
1000
# Create a new, but exactly alike, function
1001
# object. Decorate it to be a new D-Bus method
1002
# with the alternate D-Bus interface name. Add it
1004
attr[attrname] = (dbus.service.method
1006
attribute._dbus_in_signature,
1007
attribute._dbus_out_signature)
1009
(attribute.func_code,
1010
attribute.func_globals,
1011
attribute.func_name,
1012
attribute.func_defaults,
1013
attribute.func_closure)))
1014
# Is this a D-Bus property?
1015
elif getattr(attribute, "_dbus_is_property", False):
1016
# Create a new, but exactly alike, function
1017
# object, and decorate it to be a new D-Bus
1018
# property with the alternate D-Bus interface
1019
# name. Add it to the class.
1020
attr[attrname] = (dbus_service_property
1022
attribute._dbus_signature,
1023
attribute._dbus_access,
1025
._dbus_get_args_options
1028
(attribute.func_code,
1029
attribute.func_globals,
1030
attribute.func_name,
1031
attribute.func_defaults,
1032
attribute.func_closure)))
1033
return type.__new__(mcs, name, bases, attr)
713
1036
class ClientDBus(Client, DBusObjectWithProperties):
714
1037
"""A Client class using D-Bus
737
1062
DBusObjectWithProperties.__init__(self, self.bus,
738
1063
self.dbus_object_path)
740
def _get_approvals_pending(self):
741
return self._approvals_pending
742
def _set_approvals_pending(self, value):
743
old_value = self._approvals_pending
744
self._approvals_pending = value
746
if (hasattr(self, "dbus_object_path")
747
and bval is not bool(old_value)):
748
dbus_bool = dbus.Boolean(bval, variant_level=1)
749
self.PropertyChanged(dbus.String("ApprovalPending"),
752
approvals_pending = property(_get_approvals_pending,
753
_set_approvals_pending)
754
del _get_approvals_pending, _set_approvals_pending
757
def _datetime_to_dbus(dt, variant_level=0):
758
"""Convert a UTC datetime.datetime() to a D-Bus type."""
759
return dbus.String(dt.isoformat(),
760
variant_level=variant_level)
763
oldstate = getattr(self, "enabled", False)
764
r = Client.enable(self)
765
if oldstate != self.enabled:
767
self.PropertyChanged(dbus.String("Enabled"),
768
dbus.Boolean(True, variant_level=1))
769
self.PropertyChanged(
770
dbus.String("LastEnabled"),
771
self._datetime_to_dbus(self.last_enabled,
775
def disable(self, quiet = False):
776
oldstate = getattr(self, "enabled", False)
777
r = Client.disable(self, quiet=quiet)
778
if not quiet and oldstate != self.enabled:
780
self.PropertyChanged(dbus.String("Enabled"),
781
dbus.Boolean(False, variant_level=1))
1065
def notifychangeproperty(transform_func,
1066
dbus_name, type_func=lambda x: x,
1068
""" Modify a variable so that it's a property which announces
1069
its changes to DBus.
1071
transform_fun: Function that takes a value and a variant_level
1072
and transforms it to a D-Bus type.
1073
dbus_name: D-Bus name of the variable
1074
type_func: Function that transform the value before sending it
1075
to the D-Bus. Default: no transform
1076
variant_level: D-Bus variant level. Default: 1
1078
attrname = "_{0}".format(dbus_name)
1079
def setter(self, value):
1080
if hasattr(self, "dbus_object_path"):
1081
if (not hasattr(self, attrname) or
1082
type_func(getattr(self, attrname, None))
1083
!= type_func(value)):
1084
dbus_value = transform_func(type_func(value),
1087
self.PropertyChanged(dbus.String(dbus_name),
1089
setattr(self, attrname, value)
1091
return property(lambda self: getattr(self, attrname), setter)
1094
expires = notifychangeproperty(datetime_to_dbus, "Expires")
1095
approvals_pending = notifychangeproperty(dbus.Boolean,
1098
enabled = notifychangeproperty(dbus.Boolean, "Enabled")
1099
last_enabled = notifychangeproperty(datetime_to_dbus,
1101
checker = notifychangeproperty(dbus.Boolean, "CheckerRunning",
1102
type_func = lambda checker:
1103
checker is not None)
1104
last_checked_ok = notifychangeproperty(datetime_to_dbus,
1106
last_approval_request = notifychangeproperty(
1107
datetime_to_dbus, "LastApprovalRequest")
1108
approved_by_default = notifychangeproperty(dbus.Boolean,
1109
"ApprovedByDefault")
1110
approval_delay = notifychangeproperty(dbus.UInt64,
1113
timedelta_to_milliseconds)
1114
approval_duration = notifychangeproperty(
1115
dbus.UInt64, "ApprovalDuration",
1116
type_func = timedelta_to_milliseconds)
1117
host = notifychangeproperty(dbus.String, "Host")
1118
timeout = notifychangeproperty(dbus.UInt64, "Timeout",
1120
timedelta_to_milliseconds)
1121
extended_timeout = notifychangeproperty(
1122
dbus.UInt64, "ExtendedTimeout",
1123
type_func = timedelta_to_milliseconds)
1124
interval = notifychangeproperty(dbus.UInt64,
1127
timedelta_to_milliseconds)
1128
checker_command = notifychangeproperty(dbus.String, "Checker")
1130
del notifychangeproperty
784
1132
def __del__(self, *args, **kwargs):
1060
1367
if value is None: # get
1061
1368
return dbus.UInt64(self.timeout_milliseconds())
1062
1369
self.timeout = datetime.timedelta(0, 0, 0, value)
1064
self.PropertyChanged(dbus.String("Timeout"),
1065
dbus.UInt64(value, variant_level=1))
1066
if getattr(self, "disable_initiator_tag", None) is None:
1068
1370
# Reschedule timeout
1069
gobject.source_remove(self.disable_initiator_tag)
1070
self.disable_initiator_tag = None
1071
time_to_die = (self.
1072
_timedelta_to_milliseconds((self
1077
if time_to_die <= 0:
1078
# The timeout has passed
1081
self.disable_initiator_tag = (gobject.timeout_add
1082
(time_to_die, self.disable))
1372
now = datetime.datetime.utcnow()
1373
time_to_die = timedelta_to_milliseconds(
1374
(self.last_checked_ok + self.timeout) - now)
1375
if time_to_die <= 0:
1376
# The timeout has passed
1379
self.expires = (now +
1380
datetime.timedelta(milliseconds =
1382
if (getattr(self, "disable_initiator_tag", None)
1385
gobject.source_remove(self.disable_initiator_tag)
1386
self.disable_initiator_tag = (gobject.timeout_add
1390
# ExtendedTimeout - property
1391
@dbus_service_property(_interface, signature="t",
1393
def ExtendedTimeout_dbus_property(self, value=None):
1394
if value is None: # get
1395
return dbus.UInt64(self.extended_timeout_milliseconds())
1396
self.extended_timeout = datetime.timedelta(0, 0, 0, value)
1084
1398
# Interval - property
1085
1399
@dbus_service_property(_interface, signature="t",
1088
1402
if value is None: # get
1089
1403
return dbus.UInt64(self.interval_milliseconds())
1090
1404
self.interval = datetime.timedelta(0, 0, 0, value)
1092
self.PropertyChanged(dbus.String("Interval"),
1093
dbus.UInt64(value, variant_level=1))
1094
1405
if getattr(self, "checker_initiator_tag", None) is None:
1096
# Reschedule checker run
1097
gobject.source_remove(self.checker_initiator_tag)
1098
self.checker_initiator_tag = (gobject.timeout_add
1099
(value, self.start_checker))
1100
self.start_checker() # Start one now, too
1408
# Reschedule checker run
1409
gobject.source_remove(self.checker_initiator_tag)
1410
self.checker_initiator_tag = (gobject.timeout_add
1411
(value, self.start_checker))
1412
self.start_checker() # Start one now, too
1102
1414
# Checker - property
1103
1415
@dbus_service_property(_interface, signature="s",
1104
1416
access="readwrite")
1105
1417
def Checker_dbus_property(self, value=None):
1106
1418
if value is None: # get
1107
1419
return dbus.String(self.checker_command)
1108
self.checker_command = value
1110
self.PropertyChanged(dbus.String("Checker"),
1111
dbus.String(self.checker_command,
1420
self.checker_command = unicode(value)
1114
1422
# CheckerRunning - property
1115
1423
@dbus_service_property(_interface, signature="b",
1537
1866
fpr = request[1]
1538
1867
address = request[2]
1540
for c in self.clients:
1869
for c in self.clients.itervalues():
1541
1870
if c.fingerprint == fpr:
1545
logger.warning("Client not found for fingerprint: %s, ad"
1546
"dress: %s", fpr, address)
1874
logger.info("Client not found for fingerprint: %s, ad"
1875
"dress: %s", fpr, address)
1547
1876
if self.use_dbus:
1548
1877
# Emit D-Bus signal
1549
mandos_dbus_service.ClientNotFound(fpr, address[0])
1878
mandos_dbus_service.ClientNotFound(fpr,
1550
1880
parent_pipe.send(False)
1553
1883
gobject.io_add_watch(parent_pipe.fileno(),
1554
1884
gobject.IO_IN | gobject.IO_HUP,
1555
1885
functools.partial(self.handle_ipc,
1556
parent_pipe = parent_pipe,
1557
client_object = client))
1558
1891
parent_pipe.send(True)
1559
# remove the old hook in favor of the new above hook on same fileno
1892
# remove the old hook in favor of the new above hook on
1561
1895
if command == 'funcall':
1562
1896
funcname = request[1]
1563
1897
args = request[2]
1564
1898
kwargs = request[3]
1566
parent_pipe.send(('data', getattr(client_object, funcname)(*args, **kwargs)))
1900
parent_pipe.send(('data', getattr(client_object,
1568
1904
if command == 'getattr':
1569
1905
attrname = request[1]
1570
1906
if callable(client_object.__getattribute__(attrname)):
1571
1907
parent_pipe.send(('function',))
1573
parent_pipe.send(('data', client_object.__getattribute__(attrname)))
1909
parent_pipe.send(('data', client_object
1910
.__getattribute__(attrname)))
1575
1912
if command == 'setattr':
1576
1913
attrname = request[1]
1577
1914
value = request[2]
1578
1915
setattr(client_object, attrname, value)
1885
2207
client_class = Client
1887
client_class = functools.partial(ClientDBus, bus = bus)
1888
def client_config_items(config, section):
1889
special_settings = {
1890
"approved_by_default":
1891
lambda: config.getboolean(section,
1892
"approved_by_default"),
1894
for name, value in config.items(section):
2209
client_class = functools.partial(ClientDBusTransitional,
2212
client_settings = Client.config_parser(client_config)
2213
old_client_settings = {}
2216
# Get client data and settings from last running state.
2217
if server_settings["restore"]:
2219
with open(stored_state_path, "rb") as stored_state:
2220
clients_data, old_client_settings = (pickle.load
2222
os.remove(stored_state_path)
2223
except IOError as e:
2224
logger.warning("Could not load persistent state: {0}"
2226
if e.errno != errno.ENOENT:
2228
except EOFError as e:
2229
logger.warning("Could not load persistent state: "
2230
"EOFError: {0}".format(e))
2232
with PGPEngine() as pgp:
2233
for client_name, client in clients_data.iteritems():
2234
# Decide which value to use after restoring saved state.
2235
# We have three different values: Old config file,
2236
# new config file, and saved state.
2237
# New config value takes precedence if it differs from old
2238
# config value, otherwise use saved state.
2239
for name, value in client_settings[client_name].items():
2241
# For each value in new config, check if it
2242
# differs from the old config value (Except for
2243
# the "secret" attribute)
2244
if (name != "secret" and
2245
value != old_client_settings[client_name]
2247
client[name] = value
2251
# Clients who has passed its expire date can still be
2252
# enabled if its last checker was successful. Clients
2253
# whose checker failed before we stored its state is
2254
# assumed to have failed all checkers during downtime.
2255
if client["enabled"]:
2256
if datetime.datetime.utcnow() >= client["expires"]:
2257
if not client["last_checked_ok"]:
2259
"disabling client {0} - Client never "
2260
"performed a successfull checker"
2261
.format(client["name"]))
2262
client["enabled"] = False
2263
elif client["last_checker_status"] != 0:
2265
"disabling client {0} - Client "
2266
"last checker failed with error code {1}"
2267
.format(client["name"],
2268
client["last_checker_status"]))
2269
client["enabled"] = False
2271
client["expires"] = (datetime.datetime
2273
+ client["timeout"])
2274
logger.debug("Last checker succeeded,"
2275
" keeping {0} enabled"
2276
.format(client["name"]))
1896
yield (name, special_settings[name]())
1900
tcp_server.clients.update(set(
1901
client_class(name = section,
1902
config= dict(client_config_items(
1903
client_config, section)))
1904
for section in client_config.sections()))
2278
client["secret"] = (
2279
pgp.decrypt(client["encrypted_secret"],
2280
client_settings[client_name]
2283
# If decryption fails, we use secret from new settings
2284
logger.debug("Failed to decrypt {0} old secret"
2285
.format(client_name))
2286
client["secret"] = (
2287
client_settings[client_name]["secret"])
2290
# Add/remove clients based on new changes made to config
2291
for client_name in (set(old_client_settings)
2292
- set(client_settings)):
2293
del clients_data[client_name]
2294
for client_name in (set(client_settings)
2295
- set(old_client_settings)):
2296
clients_data[client_name] = client_settings[client_name]
2298
# Create clients all clients
2299
for client_name, client in clients_data.iteritems():
2300
tcp_server.clients[client_name] = client_class(
2301
name = client_name, settings = client)
1905
2303
if not tcp_server.clients:
1906
2304
logger.warning("No clients defined")
1980
mandos_dbus_service = MandosDBusService()
2378
class MandosDBusServiceTransitional(MandosDBusService):
2379
__metaclass__ = AlternateDBusNamesMetaclass
2380
mandos_dbus_service = MandosDBusServiceTransitional()
1983
2383
"Cleanup function; run on exit"
1984
2384
service.cleanup()
2386
multiprocessing.active_children()
2387
if not (tcp_server.clients or client_settings):
2390
# Store client before exiting. Secrets are encrypted with key
2391
# based on what config file has. If config file is
2392
# removed/edited, old secret will thus be unrecovable.
2394
with PGPEngine() as pgp:
2395
for client in tcp_server.clients.itervalues():
2396
key = client_settings[client.name]["secret"]
2397
client.encrypted_secret = pgp.encrypt(client.secret,
2401
# A list of attributes that can not be pickled
2403
exclude = set(("bus", "changedstate", "secret",
2405
for name, typ in (inspect.getmembers
2406
(dbus.service.Object)):
2409
client_dict["encrypted_secret"] = (client
2411
for attr in client.client_structure:
2412
if attr not in exclude:
2413
client_dict[attr] = getattr(client, attr)
2415
clients[client.name] = client_dict
2416
del client_settings[client.name]["secret"]
2419
tempfd, tempname = tempfile.mkstemp(suffix=".pickle",
2422
(stored_state_path))
2423
with os.fdopen(tempfd, "wb") as stored_state:
2424
pickle.dump((clients, client_settings), stored_state)
2425
os.rename(tempname, stored_state_path)
2426
except (IOError, OSError) as e:
2427
logger.warning("Could not save persistent state: {0}"
2434
if e.errno not in set((errno.ENOENT, errno.EACCES,
2438
# Delete all clients, and settings from config
1986
2439
while tcp_server.clients:
1987
client = tcp_server.clients.pop()
2440
name, client = tcp_server.clients.popitem()
1989
2442
client.remove_from_connection()
1990
client.disable_hook = None
1991
2443
# Don't signal anything except ClientRemoved
1992
2444
client.disable(quiet=True)
1994
2446
# Emit D-Bus signal
1995
mandos_dbus_service.ClientRemoved(client.dbus_object_path,
2447
mandos_dbus_service.ClientRemoved(client
2450
client_settings.clear()
1998
2452
atexit.register(cleanup)
2000
for client in tcp_server.clients:
2454
for client in tcp_server.clients.itervalues():
2002
2456
# Emit D-Bus signal
2003
2457
mandos_dbus_service.ClientAdded(client.dbus_object_path)
2458
# Need to initiate checking of clients
2460
client.init_checker()
2006
2462
tcp_server.enable()
2007
2463
tcp_server.server_activate()