86
84
except ImportError:
87
85
SO_BINDTODEVICE = None
90
stored_state_file = "clients.pickle"
92
90
logger = logging.getLogger()
91
stored_state_path = "/var/lib/mandos/clients.pickle"
93
93
syslogger = (logging.handlers.SysLogHandler
94
94
(facility = logging.handlers.SysLogHandler.LOG_DAEMON,
95
95
address = str("/dev/log")))
98
if_nametoindex = (ctypes.cdll.LoadLibrary
99
(ctypes.util.find_library("c"))
101
except (OSError, AttributeError):
102
def if_nametoindex(interface):
103
"Get an interface index the hard way, i.e. using fcntl()"
104
SIOCGIFINDEX = 0x8933 # From /usr/include/linux/sockios.h
105
with contextlib.closing(socket.socket()) as s:
106
ifreq = fcntl.ioctl(s, SIOCGIFINDEX,
107
struct.pack(str("16s16x"),
109
interface_index = struct.unpack(str("I"),
111
return interface_index
114
def initlogger(debug, level=logging.WARNING):
115
"""init logger and add loglevel"""
117
syslogger.setFormatter(logging.Formatter
118
('Mandos [%(process)d]: %(levelname)s:'
120
logger.addHandler(syslogger)
123
console = logging.StreamHandler()
124
console.setFormatter(logging.Formatter('%(asctime)s %(name)s'
128
logger.addHandler(console)
129
logger.setLevel(level)
132
class PGPError(Exception):
133
"""Exception if encryption/decryption fails"""
137
class PGPEngine(object):
138
"""A simple class for OpenPGP symmetric encryption & decryption"""
140
self.gnupg = GnuPGInterface.GnuPG()
141
self.tempdir = tempfile.mkdtemp(prefix="mandos-")
142
self.gnupg = GnuPGInterface.GnuPG()
143
self.gnupg.options.meta_interactive = False
144
self.gnupg.options.homedir = self.tempdir
145
self.gnupg.options.extra_args.extend(['--force-mdc',
152
def __exit__ (self, exc_type, exc_value, traceback):
160
if self.tempdir is not None:
161
# Delete contents of tempdir
162
for root, dirs, files in os.walk(self.tempdir,
164
for filename in files:
165
os.remove(os.path.join(root, filename))
167
os.rmdir(os.path.join(root, dirname))
169
os.rmdir(self.tempdir)
172
def password_encode(self, password):
173
# Passphrase can not be empty and can not contain newlines or
174
# NUL bytes. So we prefix it and hex encode it.
175
return b"mandos" + binascii.hexlify(password)
177
def encrypt(self, data, password):
178
self.gnupg.passphrase = self.password_encode(password)
179
with open(os.devnull, "w") as devnull:
181
proc = self.gnupg.run(['--symmetric'],
182
create_fhs=['stdin', 'stdout'],
183
attach_fhs={'stderr': devnull})
184
with contextlib.closing(proc.handles['stdin']) as f:
186
with contextlib.closing(proc.handles['stdout']) as f:
187
ciphertext = f.read()
191
self.gnupg.passphrase = None
194
def decrypt(self, data, password):
195
self.gnupg.passphrase = self.password_encode(password)
196
with open(os.devnull, "w") as devnull:
198
proc = self.gnupg.run(['--decrypt'],
199
create_fhs=['stdin', 'stdout'],
200
attach_fhs={'stderr': devnull})
201
with contextlib.closing(proc.handles['stdin']) as f:
203
with contextlib.closing(proc.handles['stdout']) as f:
204
decrypted_plaintext = f.read()
208
self.gnupg.passphrase = None
209
return decrypted_plaintext
96
syslogger.setFormatter(logging.Formatter
97
('Mandos [%(process)d]: %(levelname)s:'
99
logger.addHandler(syslogger)
101
console = logging.StreamHandler()
102
console.setFormatter(logging.Formatter('%(asctime)s %(name)s'
106
logger.addHandler(console)
213
109
class AvahiError(Exception):
433
329
"created", "enabled", "fingerprint",
434
330
"host", "interval", "last_checked_ok",
435
331
"last_enabled", "name", "timeout")
436
client_defaults = { "timeout": "5m",
437
"extended_timeout": "15m",
439
"checker": "fping -q -- %%(host)s",
441
"approval_delay": "0s",
442
"approval_duration": "1s",
443
"approved_by_default": "True",
447
333
def timeout_milliseconds(self):
448
334
"Return the 'timeout' attribute in milliseconds"
449
return timedelta_to_milliseconds(self.timeout)
335
return _timedelta_to_milliseconds(self.timeout)
451
337
def extended_timeout_milliseconds(self):
452
338
"Return the 'extended_timeout' attribute in milliseconds"
453
return timedelta_to_milliseconds(self.extended_timeout)
339
return _timedelta_to_milliseconds(self.extended_timeout)
455
341
def interval_milliseconds(self):
456
342
"Return the 'interval' attribute in milliseconds"
457
return timedelta_to_milliseconds(self.interval)
343
return _timedelta_to_milliseconds(self.interval)
459
345
def approval_delay_milliseconds(self):
460
return timedelta_to_milliseconds(self.approval_delay)
463
def config_parser(config):
464
"""Construct a new dict of client settings of this form:
465
{ client_name: {setting_name: value, ...}, ...}
466
with exceptions for any special settings as defined above.
467
NOTE: Must be a pure function. Must return the same result
468
value given the same arguments.
471
for client_name in config.sections():
472
section = dict(config.items(client_name))
473
client = settings[client_name] = {}
475
client["host"] = section["host"]
476
# Reformat values from string types to Python types
477
client["approved_by_default"] = config.getboolean(
478
client_name, "approved_by_default")
479
client["enabled"] = config.getboolean(client_name,
482
client["fingerprint"] = (section["fingerprint"].upper()
484
if "secret" in section:
485
client["secret"] = section["secret"].decode("base64")
486
elif "secfile" in section:
487
with open(os.path.expanduser(os.path.expandvars
488
(section["secfile"])),
490
client["secret"] = secfile.read()
492
raise TypeError("No secret or secfile for section %s"
494
client["timeout"] = string_to_delta(section["timeout"])
495
client["extended_timeout"] = string_to_delta(
496
section["extended_timeout"])
497
client["interval"] = string_to_delta(section["interval"])
498
client["approval_delay"] = string_to_delta(
499
section["approval_delay"])
500
client["approval_duration"] = string_to_delta(
501
section["approval_duration"])
502
client["checker_command"] = section["checker"]
503
client["last_approval_request"] = None
504
client["last_checked_ok"] = None
505
client["last_checker_status"] = -2
510
def __init__(self, settings, name = None):
346
return _timedelta_to_milliseconds(self.approval_delay)
348
def __init__(self, name = None, config=None):
511
349
"""Note: the 'checker' key in 'config' sets the
512
350
'checker_command' attribute and *not* the 'checker'
515
# adding all client settings
516
for setting, value in settings.iteritems():
517
setattr(self, setting, value)
520
if not hasattr(self, "last_enabled"):
521
self.last_enabled = datetime.datetime.utcnow()
522
if not hasattr(self, "expires"):
523
self.expires = (datetime.datetime.utcnow()
526
self.last_enabled = None
529
355
logger.debug("Creating client %r", self.name)
530
356
# Uppercase and remove spaces from fingerprint for later
531
357
# comparison purposes with return value from the fingerprint()
359
self.fingerprint = (config["fingerprint"].upper()
533
361
logger.debug(" Fingerprint: %s", self.fingerprint)
534
self.created = settings.get("created",
535
datetime.datetime.utcnow())
537
# attributes specific for this server instance
362
if "secret" in config:
363
self.secret = config["secret"].decode("base64")
364
elif "secfile" in config:
365
with open(os.path.expanduser(os.path.expandvars
366
(config["secfile"])),
368
self.secret = secfile.read()
370
raise TypeError("No secret or secfile for client %s"
372
self.host = config.get("host", "")
373
self.created = datetime.datetime.utcnow()
375
self.last_approval_request = None
376
self.last_enabled = datetime.datetime.utcnow()
377
self.last_checked_ok = None
378
self.last_checker_status = None
379
self.timeout = string_to_delta(config["timeout"])
380
self.extended_timeout = string_to_delta(config
381
["extended_timeout"])
382
self.interval = string_to_delta(config["interval"])
538
383
self.checker = None
539
384
self.checker_initiator_tag = None
540
385
self.disable_initiator_tag = None
386
self.expires = datetime.datetime.utcnow() + self.timeout
541
387
self.checker_callback_tag = None
388
self.checker_command = config["checker"]
542
389
self.current_checker_command = None
390
self._approved = None
391
self.approved_by_default = config.get("approved_by_default",
544
393
self.approvals_pending = 0
394
self.approval_delay = string_to_delta(
395
config["approval_delay"])
396
self.approval_duration = string_to_delta(
397
config["approval_duration"])
545
398
self.changedstate = (multiprocessing_manager
546
399
.Condition(multiprocessing_manager
548
self.client_structure = [attr for attr in
549
self.__dict__.iterkeys()
550
if not attr.startswith("_")]
401
self.client_structure = [attr for attr in self.__dict__.iterkeys() if not attr.startswith("_")]
551
402
self.client_structure.append("client_structure")
553
405
for name, t in inspect.getmembers(type(self),
406
lambda obj: isinstance(obj, property)):
557
407
if not name.startswith("_"):
558
408
self.client_structure.append(name)
733
583
logger.debug("Stopping checker for %(name)s", vars(self))
735
self.checker.terminate()
585
os.kill(self.checker.pid, signal.SIGTERM)
737
587
#if self.checker.poll() is None:
738
# self.checker.kill()
588
# os.kill(self.checker.pid, signal.SIGKILL)
739
589
except OSError as error:
740
590
if error.errno != errno.ESRCH: # No such process
742
592
self.checker = None
594
# Encrypts a client secret and stores it in a varible encrypted_secret
595
def encrypt_secret(self, key):
596
# Encryption-key need to be of a specific size, so we hash inputed key
597
hasheng = hashlib.sha256()
599
encryptionkey = hasheng.digest()
601
# Create validation hash so we know at decryption if it was sucessful
602
hasheng = hashlib.sha256()
603
hasheng.update(self.secret)
604
validationhash = hasheng.digest()
607
iv = os.urandom(Crypto.Cipher.AES.block_size)
608
ciphereng = Crypto.Cipher.AES.new(encryptionkey,
609
Crypto.Cipher.AES.MODE_CFB, iv)
610
ciphertext = ciphereng.encrypt(validationhash+self.secret)
611
self.encrypted_secret = (ciphertext, iv)
613
# Decrypt a encrypted client secret
614
def decrypt_secret(self, key):
615
# Decryption-key need to be of a specific size, so we hash inputed key
616
hasheng = hashlib.sha256()
618
encryptionkey = hasheng.digest()
620
# Decrypt encrypted secret
621
ciphertext, iv = self.encrypted_secret
622
ciphereng = Crypto.Cipher.AES.new(encryptionkey,
623
Crypto.Cipher.AES.MODE_CFB, iv)
624
plain = ciphereng.decrypt(ciphertext)
626
# Validate decrypted secret to know if it was succesful
627
hasheng = hashlib.sha256()
628
validationhash = plain[:hasheng.digest_size]
629
secret = plain[hasheng.digest_size:]
630
hasheng.update(secret)
632
# if validation fails, we use key as new secret. Otherwhise, we use
633
# the decrypted secret
634
if hasheng.digest() == validationhash:
638
del self.encrypted_secret
745
641
def dbus_service_property(dbus_interface, signature="v",
746
642
access="readwrite", byte_arrays=False):
775
def dbus_interface_annotations(dbus_interface):
776
"""Decorator for marking functions returning interface annotations.
780
@dbus_interface_annotations("org.example.Interface")
781
def _foo(self): # Function name does not matter
782
return {"org.freedesktop.DBus.Deprecated": "true",
783
"org.freedesktop.DBus.Property.EmitsChangedSignal":
787
func._dbus_is_interface = True
788
func._dbus_interface = dbus_interface
789
func._dbus_name = dbus_interface
794
def dbus_annotations(annotations):
795
"""Decorator to annotate D-Bus methods, signals or properties
798
@dbus_service_property("org.example.Interface", signature="b",
800
@dbus_annotations({{"org.freedesktop.DBus.Deprecated": "true",
801
"org.freedesktop.DBus.Property."
802
"EmitsChangedSignal": "false"})
803
def Property_dbus_property(self):
804
return dbus.Boolean(False)
807
func._dbus_annotations = annotations
812
671
class DBusPropertyException(dbus.exceptions.DBusException):
813
672
"""A base class for D-Bus property-related exceptions
840
def _is_dbus_thing(thing):
841
"""Returns a function testing if an attribute is a D-Bus thing
843
If called like _is_dbus_thing("method") it returns a function
844
suitable for use as predicate to inspect.getmembers().
846
return lambda obj: getattr(obj, "_dbus_is_{0}".format(thing),
699
def _is_dbus_property(obj):
700
return getattr(obj, "_dbus_is_property", False)
849
def _get_all_dbus_things(self, thing):
702
def _get_all_dbus_properties(self):
850
703
"""Returns a generator of (name, attribute) pairs
852
return ((getattr(athing.__get__(self), "_dbus_name",
854
athing.__get__(self))
705
return ((prop.__get__(self)._dbus_name, prop.__get__(self))
855
706
for cls in self.__class__.__mro__
857
inspect.getmembers(cls,
858
self._is_dbus_thing(thing)))
708
inspect.getmembers(cls, self._is_dbus_property))
860
710
def _get_dbus_property(self, interface_name, property_name):
861
711
"""Returns a bound method if one exists which is a D-Bus
948
795
e.setAttribute("access", prop._dbus_access)
950
797
for if_tag in document.getElementsByTagName("interface"):
952
798
for tag in (make_tag(document, name, prop)
954
in self._get_all_dbus_things("property")
800
in self._get_all_dbus_properties()
955
801
if prop._dbus_interface
956
802
== if_tag.getAttribute("name")):
957
803
if_tag.appendChild(tag)
958
# Add annotation tags
959
for typ in ("method", "signal", "property"):
960
for tag in if_tag.getElementsByTagName(typ):
962
for name, prop in (self.
963
_get_all_dbus_things(typ)):
964
if (name == tag.getAttribute("name")
965
and prop._dbus_interface
966
== if_tag.getAttribute("name")):
967
annots.update(getattr
971
for name, value in annots.iteritems():
972
ann_tag = document.createElement(
974
ann_tag.setAttribute("name", name)
975
ann_tag.setAttribute("value", value)
976
tag.appendChild(ann_tag)
977
# Add interface annotation tags
978
for annotation, value in dict(
980
*(annotations().iteritems()
981
for name, annotations in
982
self._get_all_dbus_things("interface")
983
if name == if_tag.getAttribute("name")
985
ann_tag = document.createElement("annotation")
986
ann_tag.setAttribute("name", annotation)
987
ann_tag.setAttribute("value", value)
988
if_tag.appendChild(ann_tag)
989
804
# Add the names to the return values for the
990
805
# "org.freedesktop.DBus.Properties" methods
991
806
if (if_tag.getAttribute("name")
1128
927
attribute.func_name,
1129
928
attribute.func_defaults,
1130
929
attribute.func_closure)))
1131
# Copy annotations, if any
1133
attr[attrname]._dbus_annotations = (
1134
dict(attribute._dbus_annotations))
1135
except AttributeError:
1137
# Is this a D-Bus interface?
1138
elif getattr(attribute, "_dbus_is_interface", False):
1139
# Create a new, but exactly alike, function
1140
# object. Decorate it to be a new D-Bus interface
1141
# with the alternate D-Bus interface name. Add it
1143
attr[attrname] = (dbus_interface_annotations
1146
(attribute.func_code,
1147
attribute.func_globals,
1148
attribute.func_name,
1149
attribute.func_defaults,
1150
attribute.func_closure)))
1151
# Deprecate all old interfaces
1152
basename="_AlternateDBusNamesMetaclass_interface_annotation{0}"
1153
for old_interface_name in old_interface_names:
1154
@dbus_interface_annotations(old_interface_name)
1156
return { "org.freedesktop.DBus.Deprecated": "true" }
1157
# Find an unused name
1158
for aname in (basename.format(i) for i in
1160
if aname not in attr:
1163
930
return type.__new__(mcs, name, bases, attr)
1166
932
class ClientDBus(Client, DBusObjectWithProperties):
1167
933
"""A Client class using D-Bus
1230
998
checker is not None)
1231
999
last_checked_ok = notifychangeproperty(datetime_to_dbus,
1232
1000
"LastCheckedOK")
1233
last_checker_status = notifychangeproperty(dbus.Int16,
1234
"LastCheckerStatus")
1235
1001
last_approval_request = notifychangeproperty(
1236
1002
datetime_to_dbus, "LastApprovalRequest")
1237
1003
approved_by_default = notifychangeproperty(dbus.Boolean,
1238
1004
"ApprovedByDefault")
1239
approval_delay = notifychangeproperty(dbus.UInt64,
1005
approval_delay = notifychangeproperty(dbus.UInt16,
1240
1006
"ApprovalDelay",
1242
timedelta_to_milliseconds)
1008
_timedelta_to_milliseconds)
1243
1009
approval_duration = notifychangeproperty(
1244
dbus.UInt64, "ApprovalDuration",
1245
type_func = timedelta_to_milliseconds)
1010
dbus.UInt16, "ApprovalDuration",
1011
type_func = _timedelta_to_milliseconds)
1246
1012
host = notifychangeproperty(dbus.String, "Host")
1247
timeout = notifychangeproperty(dbus.UInt64, "Timeout",
1013
timeout = notifychangeproperty(dbus.UInt16, "Timeout",
1249
timedelta_to_milliseconds)
1015
_timedelta_to_milliseconds)
1250
1016
extended_timeout = notifychangeproperty(
1251
dbus.UInt64, "ExtendedTimeout",
1252
type_func = timedelta_to_milliseconds)
1253
interval = notifychangeproperty(dbus.UInt64,
1017
dbus.UInt16, "ExtendedTimeout",
1018
type_func = _timedelta_to_milliseconds)
1019
interval = notifychangeproperty(dbus.UInt16,
1256
timedelta_to_milliseconds)
1022
_timedelta_to_milliseconds)
1257
1023
checker_command = notifychangeproperty(dbus.String, "Checker")
1259
1025
del notifychangeproperty
1501
1254
if value is None: # get
1502
1255
return dbus.UInt64(self.timeout_milliseconds())
1503
1256
self.timeout = datetime.timedelta(0, 0, 0, value)
1257
if getattr(self, "disable_initiator_tag", None) is None:
1504
1259
# Reschedule timeout
1506
now = datetime.datetime.utcnow()
1507
time_to_die = timedelta_to_milliseconds(
1508
(self.last_checked_ok + self.timeout) - now)
1509
if time_to_die <= 0:
1510
# The timeout has passed
1513
self.expires = (now +
1514
datetime.timedelta(milliseconds =
1516
if (getattr(self, "disable_initiator_tag", None)
1519
gobject.source_remove(self.disable_initiator_tag)
1520
self.disable_initiator_tag = (gobject.timeout_add
1260
gobject.source_remove(self.disable_initiator_tag)
1261
self.disable_initiator_tag = None
1263
time_to_die = _timedelta_to_milliseconds((self
1268
if time_to_die <= 0:
1269
# The timeout has passed
1272
self.expires = (datetime.datetime.utcnow()
1273
+ datetime.timedelta(milliseconds =
1275
self.disable_initiator_tag = (gobject.timeout_add
1276
(time_to_die, self.disable))
1524
1278
# ExtendedTimeout - property
1525
1279
@dbus_service_property(_interface, signature="t",
2335
2113
client_class = functools.partial(ClientDBusTransitional,
2338
client_settings = Client.config_parser(client_config)
2116
special_settings = {
2117
# Some settings need to be accessd by special methods;
2118
# booleans need .getboolean(), etc. Here is a list of them:
2119
"approved_by_default":
2121
client_config.getboolean(section, "approved_by_default"),
2123
# Construct a new dict of client settings of this form:
2124
# { client_name: {setting_name: value, ...}, ...}
2125
# with exceptions for any special settings as defined above
2126
client_settings = dict((clientname,
2128
(value if setting not in special_settings
2129
else special_settings[setting](clientname)))
2130
for setting, value in client_config.items(clientname)))
2131
for clientname in client_config.sections())
2339
2133
old_client_settings = {}
2342
# Get client data and settings from last running state.
2136
# Get client data and settings from last running state.
2343
2137
if server_settings["restore"]:
2345
2139
with open(stored_state_path, "rb") as stored_state:
2346
clients_data, old_client_settings = (pickle.load
2140
clients_data, old_client_settings = pickle.load(stored_state)
2348
2141
os.remove(stored_state_path)
2349
2142
except IOError as e:
2350
logger.warning("Could not load persistent state: {0}"
2143
logger.warning("Could not load persistant state: {0}".format(e))
2352
2144
if e.errno != errno.ENOENT:
2354
except EOFError as e:
2355
logger.warning("Could not load persistent state: "
2356
"EOFError: {0}".format(e))
2358
with PGPEngine() as pgp:
2359
for client_name, client in clients_data.iteritems():
2360
# Decide which value to use after restoring saved state.
2361
# We have three different values: Old config file,
2362
# new config file, and saved state.
2363
# New config value takes precedence if it differs from old
2364
# config value, otherwise use saved state.
2365
for name, value in client_settings[client_name].items():
2367
# For each value in new config, check if it
2368
# differs from the old config value (Except for
2369
# the "secret" attribute)
2370
if (name != "secret" and
2371
value != old_client_settings[client_name]
2373
client[name] = value
2377
# Clients who has passed its expire date can still be
2378
# enabled if its last checker was successful. Clients
2379
# whose checker succeeded before we stored its state is
2380
# assumed to have successfully run all checkers during
2382
if client["enabled"]:
2383
if datetime.datetime.utcnow() >= client["expires"]:
2384
if not client["last_checked_ok"]:
2386
"disabling client {0} - Client never "
2387
"performed a successful checker"
2388
.format(client_name))
2389
client["enabled"] = False
2390
elif client["last_checker_status"] != 0:
2392
"disabling client {0} - Client "
2393
"last checker failed with error code {1}"
2394
.format(client_name,
2395
client["last_checker_status"]))
2396
client["enabled"] = False
2398
client["expires"] = (datetime.datetime
2400
+ client["timeout"])
2401
logger.debug("Last checker succeeded,"
2402
" keeping {0} enabled"
2403
.format(client_name))
2147
for client in clients_data:
2148
client_name = client["name"]
2150
# Decide which value to use after restoring saved state.
2151
# We have three different values: Old config file,
2152
# new config file, and saved state.
2153
# New config value takes precedence if it differs from old
2154
# config value, otherwise use saved state.
2155
for name, value in client_settings[client_name].items():
2405
client["secret"] = (
2406
pgp.decrypt(client["encrypted_secret"],
2407
client_settings[client_name]
2410
# If decryption fails, we use secret from new settings
2411
logger.debug("Failed to decrypt {0} old secret"
2412
.format(client_name))
2413
client["secret"] = (
2414
client_settings[client_name]["secret"])
2417
# Add/remove clients based on new changes made to config
2418
for client_name in (set(old_client_settings)
2419
- set(client_settings)):
2420
del clients_data[client_name]
2421
for client_name in (set(client_settings)
2422
- set(old_client_settings)):
2423
clients_data[client_name] = client_settings[client_name]
2425
# Create all client objects
2426
for client_name, client in clients_data.iteritems():
2427
tcp_server.clients[client_name] = client_class(
2428
name = client_name, settings = client)
2157
# For each value in new config, check if it differs
2158
# from the old config value (Except for the "secret"
2160
if name != "secret" and value != old_client_settings[client_name][name]:
2161
setattr(client, name, value)
2165
# Clients who has passed its expire date, can still be enabled if its
2166
# last checker was sucessful. Clients who checkers failed before we
2167
# stored it state is asumed to had failed checker during downtime.
2168
if client["enabled"] and client["last_checked_ok"]:
2169
if ((datetime.datetime.utcnow() - client["last_checked_ok"])
2170
> client["interval"]):
2171
if client["last_checker_status"] != 0:
2172
client["enabled"] = False
2174
client["expires"] = datetime.datetime.utcnow() + client["timeout"]
2176
client["changedstate"] = (multiprocessing_manager
2177
.Condition(multiprocessing_manager
2180
new_client = ClientDBusTransitional.__new__(ClientDBusTransitional)
2181
tcp_server.clients[client_name] = new_client
2182
new_client.bus = bus
2183
for name, value in client.iteritems():
2184
setattr(new_client, name, value)
2185
client_object_name = unicode(client_name).translate(
2186
{ord("."): ord("_"),
2187
ord("-"): ord("_")})
2188
new_client.dbus_object_path = (dbus.ObjectPath
2189
("/clients/" + client_object_name))
2190
DBusObjectWithProperties.__init__(new_client,
2192
new_client.dbus_object_path)
2194
tcp_server.clients[client_name] = Client.__new__(Client)
2195
for name, value in client.iteritems():
2196
setattr(tcp_server.clients[client_name], name, value)
2198
tcp_server.clients[client_name].decrypt_secret(
2199
client_settings[client_name]["secret"])
2201
# Create/remove clients based on new changes made to config
2202
for clientname in set(old_client_settings) - set(client_settings):
2203
del tcp_server.clients[clientname]
2204
for clientname in set(client_settings) - set(old_client_settings):
2205
tcp_server.clients[clientname] = (client_class(name = clientname,
2430
2211
if not tcp_server.clients:
2431
2212
logger.warning("No clients defined")
2519
2295
multiprocessing.active_children()
2520
2296
if not (tcp_server.clients or client_settings):
2523
# Store client before exiting. Secrets are encrypted with key
2524
# based on what config file has. If config file is
2525
# removed/edited, old secret will thus be unrecovable.
2527
with PGPEngine() as pgp:
2528
for client in tcp_server.clients.itervalues():
2529
key = client_settings[client.name]["secret"]
2530
client.encrypted_secret = pgp.encrypt(client.secret,
2534
# A list of attributes that can not be pickled
2536
exclude = set(("bus", "changedstate", "secret",
2538
for name, typ in (inspect.getmembers
2539
(dbus.service.Object)):
2542
client_dict["encrypted_secret"] = (client
2544
for attr in client.client_structure:
2545
if attr not in exclude:
2546
client_dict[attr] = getattr(client, attr)
2548
clients[client.name] = client_dict
2549
del client_settings[client.name]["secret"]
2299
# Store client before exiting. Secrets are encrypted with key based
2300
# on what config file has. If config file is removed/edited, old
2301
# secret will thus be unrecovable.
2303
for client in tcp_server.clients.itervalues():
2304
client.encrypt_secret(client_settings[client.name]["secret"])
2308
# A list of attributes that will not be stored when shuting down.
2309
exclude = set(("bus", "changedstate", "secret"))
2310
for name, typ in inspect.getmembers(dbus.service.Object):
2313
client_dict["encrypted_secret"] = client.encrypted_secret
2314
for attr in client.client_structure:
2315
if attr not in exclude:
2316
client_dict[attr] = getattr(client, attr)
2318
clients.append(client_dict)
2319
del client_settings[client.name]["secret"]
2552
tempfd, tempname = tempfile.mkstemp(suffix=".pickle",
2555
(stored_state_path))
2556
with os.fdopen(tempfd, "wb") as stored_state:
2322
with os.fdopen(os.open(stored_state_path, os.O_CREAT|os.O_WRONLY|os.O_TRUNC, 0600), "wb") as stored_state:
2557
2323
pickle.dump((clients, client_settings), stored_state)
2558
os.rename(tempname, stored_state_path)
2559
except (IOError, OSError) as e:
2560
logger.warning("Could not save persistent state: {0}"
2567
if e.errno not in set((errno.ENOENT, errno.EACCES,
2324
except IOError as e:
2325
logger.warning("Could not save persistant state: {0}".format(e))
2326
if e.errno != errno.ENOENT:
2571
2329
# Delete all clients, and settings from config
2572
2330
while tcp_server.clients:
2573
2331
name, client = tcp_server.clients.popitem()