85
81
except ImportError:
86
82
SO_BINDTODEVICE = None
89
stored_state_file = "clients.pickle"
91
logger = logging.getLogger()
87
#logger = logging.getLogger('mandos')
88
logger = logging.Logger('mandos')
92
89
syslogger = (logging.handlers.SysLogHandler
93
90
(facility = logging.handlers.SysLogHandler.LOG_DAEMON,
94
91
address = str("/dev/log")))
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
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)
212
103
class AvahiError(Exception):
213
104
def __init__(self, value, *args, **kwargs):
268
158
" after %i retries, exiting.",
269
159
self.rename_count)
270
160
raise AvahiServiceError("Too many renames")
271
self.name = unicode(self.server
272
.GetAlternativeServiceName(self.name))
161
self.name = unicode(self.server.GetAlternativeServiceName(self.name))
273
162
logger.info("Changing Zeroconf service name to %r ...",
164
syslogger.setFormatter(logging.Formatter
165
('Mandos (%s) [%%(process)d]:'
166
' %%(levelname)s: %%(message)s'
278
except dbus.exceptions.DBusException as error:
171
except dbus.exceptions.DBusException, error:
279
172
logger.critical("DBusException: %s", error)
282
175
self.rename_count += 1
283
176
def remove(self):
284
177
"""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
288
178
if self.group is not None:
289
179
self.group.Reset()
291
181
"""Derived from the Avahi example code"""
293
182
if self.group is None:
294
183
self.group = dbus.Interface(
295
184
self.bus.get_object(avahi.DBUS_NAME,
296
185
self.server.EntryGroupNew()),
297
186
avahi.DBUS_INTERFACE_ENTRY_GROUP)
298
self.entry_group_state_changed_match = (
299
self.group.connect_to_signal(
300
'StateChanged', self.entry_group_state_changed))
187
self.group.connect_to_signal('StateChanged',
189
.entry_group_state_changed)
301
190
logger.debug("Adding Zeroconf service '%s' of type '%s' ...",
302
191
self.name, self.type)
303
192
self.group.AddService(
326
215
def cleanup(self):
327
216
"""Derived from the Avahi example code"""
328
217
if self.group is not None:
331
except (dbus.exceptions.UnknownMethodException,
332
dbus.exceptions.DBusException):
334
219
self.group = None
336
def server_state_changed(self, state, error=None):
220
def server_state_changed(self, state):
337
221
"""Derived from the Avahi example code"""
338
222
logger.debug("Avahi server state change: %i", state)
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)
223
if state == avahi.SERVER_COLLISION:
224
logger.error("Zeroconf server name collision")
353
226
elif state == avahi.SERVER_RUNNING:
357
logger.debug("Unknown state: %r", state)
359
logger.debug("Unknown state: %r: %r", state, error)
360
228
def activate(self):
361
229
"""Derived from the Avahi example code"""
362
230
if self.server is None:
363
231
self.server = dbus.Interface(
364
232
self.bus.get_object(avahi.DBUS_NAME,
365
avahi.DBUS_PATH_SERVER,
366
follow_name_owner_changes=True),
233
avahi.DBUS_PATH_SERVER),
367
234
avahi.DBUS_INTERFACE_SERVER)
368
235
self.server.connect_to_signal("StateChanged",
369
236
self.server_state_changed)
370
237
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))
388
240
class Client(object):
389
241
"""A representation of a client host served by this server.
392
approved: bool(); 'None' if not yet approved/disapproved
244
_approved: bool(); 'None' if not yet approved/disapproved
393
245
approval_delay: datetime.timedelta(); Time to wait for approval
394
246
approval_duration: datetime.timedelta(); Duration of one approval
395
247
checker: subprocess.Popen(); a running checker process used
413
264
interval: datetime.timedelta(); How often to start a new checker
414
265
last_approval_request: datetime.datetime(); (UTC) or None
415
266
last_checked_ok: datetime.datetime(); (UTC) or None
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
267
last_enabled: datetime.datetime(); (UTC)
420
268
name: string; from the config file, used in log messages and
421
269
D-Bus identifiers
422
270
secret: bytestring; sent verbatim (over TLS) to client
423
271
timeout: datetime.timedelta(); How long from last_checked_ok
424
272
until this client is disabled
425
extended_timeout: extra long timeout when password has been sent
426
273
runtime_expansions: Allowed attributes for runtime expansion.
427
expires: datetime.datetime(); time (UTC) when a client will be
431
276
runtime_expansions = ("approval_delay", "approval_duration",
432
277
"created", "enabled", "fingerprint",
433
278
"host", "interval", "last_checked_ok",
434
279
"last_enabled", "name", "timeout")
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",
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))
446
288
def timeout_milliseconds(self):
447
289
"Return the 'timeout' attribute in milliseconds"
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)
290
return self._timedelta_to_milliseconds(self.timeout)
454
292
def interval_milliseconds(self):
455
293
"Return the 'interval' attribute in milliseconds"
456
return timedelta_to_milliseconds(self.interval)
294
return self._timedelta_to_milliseconds(self.interval)
458
296
def approval_delay_milliseconds(self):
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):
297
return self._timedelta_to_milliseconds(self.approval_delay)
299
def __init__(self, name = None, disable_hook=None, config=None):
510
300
"""Note: the 'checker' key in 'config' sets the
511
301
'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
528
306
logger.debug("Creating client %r", self.name)
529
307
# Uppercase and remove spaces from fingerprint for later
530
308
# comparison purposes with return value from the fingerprint()
310
self.fingerprint = (config["fingerprint"].upper()
532
312
logger.debug(" Fingerprint: %s", self.fingerprint)
533
self.created = settings.get("created",
534
datetime.datetime.utcnow())
536
# attributes specific for this server instance
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
537
332
self.checker = None
538
333
self.checker_initiator_tag = None
539
334
self.disable_initiator_tag = None
540
335
self.checker_callback_tag = None
336
self.checker_command = config["checker"]
541
337
self.current_checker_command = None
338
self.last_connect = None
339
self._approved = None
340
self.approved_by_default = config.get("approved_by_default",
543
342
self.approvals_pending = 0
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)
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())
559
# Send notice to process children that client state has changed
560
349
def send_changedstate(self):
561
with self.changedstate:
562
self.changedstate.notify_all()
350
self.changedstate.acquire()
351
self.changedstate.notify_all()
352
self.changedstate.release()
564
354
def enable(self):
565
355
"""Start this client's checker and timeout hooks"""
566
356
if getattr(self, "enabled", False):
567
357
# Already enabled
569
359
self.send_changedstate()
570
self.expires = datetime.datetime.utcnow() + self.timeout
572
360
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*.
575
374
def disable(self, quiet=True):
576
375
"""Disable this client."""
921
704
xmlstring = document.toxml("utf-8")
922
705
document.unlink()
923
706
except (AttributeError, xml.dom.DOMException,
924
xml.parsers.expat.ExpatError) as error:
707
xml.parsers.expat.ExpatError), error:
925
708
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)
1036
713
class ClientDBus(Client, DBusObjectWithProperties):
1037
714
"""A Client class using D-Bus
1062
737
DBusObjectWithProperties.__init__(self, self.bus,
1063
738
self.dbus_object_path)
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
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))
1132
784
def __del__(self, *args, **kwargs):
1367
1060
if value is None: # get
1368
1061
return dbus.UInt64(self.timeout_milliseconds())
1369
1062
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:
1370
1068
# Reschedule timeout
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)
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))
1398
1084
# Interval - property
1399
1085
@dbus_service_property(_interface, signature="t",
1402
1088
if value is None: # get
1403
1089
return dbus.UInt64(self.interval_milliseconds())
1404
1090
self.interval = datetime.timedelta(0, 0, 0, value)
1092
self.PropertyChanged(dbus.String("Interval"),
1093
dbus.UInt64(value, variant_level=1))
1405
1094
if getattr(self, "checker_initiator_tag", None) is None:
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
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
1414
1102
# Checker - property
1415
1103
@dbus_service_property(_interface, signature="s",
1416
1104
access="readwrite")
1417
1105
def Checker_dbus_property(self, value=None):
1418
1106
if value is None: # get
1419
1107
return dbus.String(self.checker_command)
1420
self.checker_command = unicode(value)
1108
self.checker_command = value
1110
self.PropertyChanged(dbus.String("Checker"),
1111
dbus.String(self.checker_command,
1422
1114
# CheckerRunning - property
1423
1115
@dbus_service_property(_interface, signature="b",
1866
1537
fpr = request[1]
1867
1538
address = request[2]
1869
for c in self.clients.itervalues():
1540
for c in self.clients:
1870
1541
if c.fingerprint == fpr:
1874
logger.info("Client not found for fingerprint: %s, ad"
1875
"dress: %s", fpr, address)
1545
logger.warning("Client not found for fingerprint: %s, ad"
1546
"dress: %s", fpr, address)
1876
1547
if self.use_dbus:
1877
1548
# Emit D-Bus signal
1878
mandos_dbus_service.ClientNotFound(fpr,
1549
mandos_dbus_service.ClientNotFound(fpr, address[0])
1880
1550
parent_pipe.send(False)
1883
1553
gobject.io_add_watch(parent_pipe.fileno(),
1884
1554
gobject.IO_IN | gobject.IO_HUP,
1885
1555
functools.partial(self.handle_ipc,
1556
parent_pipe = parent_pipe,
1557
client_object = client))
1891
1558
parent_pipe.send(True)
1892
# remove the old hook in favor of the new above hook on
1559
# remove the old hook in favor of the new above hook on same fileno
1895
1561
if command == 'funcall':
1896
1562
funcname = request[1]
1897
1563
args = request[2]
1898
1564
kwargs = request[3]
1900
parent_pipe.send(('data', getattr(client_object,
1566
parent_pipe.send(('data', getattr(client_object, funcname)(*args, **kwargs)))
1904
1568
if command == 'getattr':
1905
1569
attrname = request[1]
1906
1570
if callable(client_object.__getattribute__(attrname)):
1907
1571
parent_pipe.send(('function',))
1909
parent_pipe.send(('data', client_object
1910
.__getattribute__(attrname)))
1573
parent_pipe.send(('data', client_object.__getattribute__(attrname)))
1912
1575
if command == 'setattr':
1913
1576
attrname = request[1]
1914
1577
value = request[2]
1915
1578
setattr(client_object, attrname, value)
1986
1673
##################################################################
1987
1674
# Parsing of options, both command line and config file
1989
parser = argparse.ArgumentParser()
1990
parser.add_argument("-v", "--version", action="version",
1991
version = "%%(prog)s %s" % version,
1992
help="show version number and exit")
1993
parser.add_argument("-i", "--interface", metavar="IF",
1994
help="Bind to interface IF")
1995
parser.add_argument("-a", "--address",
1996
help="Address to listen for requests on")
1997
parser.add_argument("-p", "--port", type=int,
1998
help="Port number to receive requests on")
1999
parser.add_argument("--check", action="store_true",
2000
help="Run self-test")
2001
parser.add_argument("--debug", action="store_true",
2002
help="Debug mode; run in foreground and log"
2004
parser.add_argument("--debuglevel", metavar="LEVEL",
2005
help="Debug level for stdout output")
2006
parser.add_argument("--priority", help="GnuTLS"
2007
" priority string (see GnuTLS documentation)")
2008
parser.add_argument("--servicename",
2009
metavar="NAME", help="Zeroconf service name")
2010
parser.add_argument("--configdir",
2011
default="/etc/mandos", metavar="DIR",
2012
help="Directory to search for configuration"
2014
parser.add_argument("--no-dbus", action="store_false",
2015
dest="use_dbus", help="Do not provide D-Bus"
2016
" system bus interface")
2017
parser.add_argument("--no-ipv6", action="store_false",
2018
dest="use_ipv6", help="Do not use IPv6")
2019
parser.add_argument("--no-restore", action="store_false",
2020
dest="restore", help="Do not restore stored"
2022
parser.add_argument("--statedir", metavar="DIR",
2023
help="Directory to save/restore state in")
2025
options = parser.parse_args()
1676
parser = optparse.OptionParser(version = "%%prog %s" % version)
1677
parser.add_option("-i", "--interface", type="string",
1678
metavar="IF", help="Bind to interface IF")
1679
parser.add_option("-a", "--address", type="string",
1680
help="Address to listen for requests on")
1681
parser.add_option("-p", "--port", type="int",
1682
help="Port number to receive requests on")
1683
parser.add_option("--check", action="store_true",
1684
help="Run self-test")
1685
parser.add_option("--debug", action="store_true",
1686
help="Debug mode; run in foreground and log to"
1688
parser.add_option("--debuglevel", type="string", metavar="LEVEL",
1689
help="Debug level for stdout output")
1690
parser.add_option("--priority", type="string", help="GnuTLS"
1691
" priority string (see GnuTLS documentation)")
1692
parser.add_option("--servicename", type="string",
1693
metavar="NAME", help="Zeroconf service name")
1694
parser.add_option("--configdir", type="string",
1695
default="/etc/mandos", metavar="DIR",
1696
help="Directory to search for configuration"
1698
parser.add_option("--no-dbus", action="store_false",
1699
dest="use_dbus", help="Do not provide D-Bus"
1700
" system bus interface")
1701
parser.add_option("--no-ipv6", action="store_false",
1702
dest="use_ipv6", help="Do not use IPv6")
1703
options = parser.parse_args()[0]
2027
1705
if options.check:
2207
1882
client_class = Client
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"]))
1884
client_class = functools.partial(ClientDBus, bus = bus)
1885
def client_config_items(config, section):
1886
special_settings = {
1887
"approved_by_default":
1888
lambda: config.getboolean(section,
1889
"approved_by_default"),
1891
for name, value in config.items(section):
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)
1893
yield (name, special_settings[name]())
1897
tcp_server.clients.update(set(
1898
client_class(name = section,
1899
config= dict(client_config_items(
1900
client_config, section)))
1901
for section in client_config.sections()))
2303
1902
if not tcp_server.clients:
2304
1903
logger.warning("No clients defined")
2378
class MandosDBusServiceTransitional(MandosDBusService):
2379
__metaclass__ = AlternateDBusNamesMetaclass
2380
mandos_dbus_service = MandosDBusServiceTransitional()
1977
mandos_dbus_service = MandosDBusService()
2383
1980
"Cleanup function; run on exit"
2384
1981
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
2439
1983
while tcp_server.clients:
2440
name, client = tcp_server.clients.popitem()
1984
client = tcp_server.clients.pop()
2442
1986
client.remove_from_connection()
1987
client.disable_hook = None
2443
1988
# Don't signal anything except ClientRemoved
2444
1989
client.disable(quiet=True)
2446
1991
# Emit D-Bus signal
2447
mandos_dbus_service.ClientRemoved(client
1992
mandos_dbus_service.ClientRemoved(client.dbus_object_path,
2450
client_settings.clear()
2452
1995
atexit.register(cleanup)
2454
for client in tcp_server.clients.itervalues():
1997
for client in tcp_server.clients:
2456
1999
# Emit D-Bus signal
2457
2000
mandos_dbus_service.ClientAdded(client.dbus_object_path)
2458
# Need to initiate checking of clients
2460
client.init_checker()
2462
2003
tcp_server.enable()
2463
2004
tcp_server.server_activate()