90
stored_state_file = "clients.pickle"
92
logger = logging.getLogger()
88
#logger = logging.getLogger('mandos')
89
logger = logging.Logger('mandos')
93
90
syslogger = (logging.handlers.SysLogHandler
94
91
(facility = logging.handlers.SysLogHandler.LOG_DAEMON,
95
92
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(level=logging.WARNING):
115
"""init logger and add loglevel"""
117
syslogger.setFormatter(logging.Formatter
118
('Mandos [%(process)d]: %(levelname)s:'
120
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',
150
def __exit__ (self, exc_type, exc_value, traceback):
158
if self.tempdir is not None:
159
# Delete contents of tempdir
160
for root, dirs, files in os.walk(self.tempdir,
162
for filename in files:
163
os.remove(os.path.join(root, filename))
165
os.rmdir(os.path.join(root, dirname))
167
os.rmdir(self.tempdir)
170
def password_encode(self, password):
171
# Passphrase can not be empty and can not contain newlines or
172
# NUL bytes. So we prefix it and hex encode it.
173
return b"mandos" + binascii.hexlify(password)
175
def encrypt(self, data, password):
176
self.gnupg.passphrase = self.password_encode(password)
177
with open(os.devnull) as devnull:
179
proc = self.gnupg.run(['--symmetric'],
180
create_fhs=['stdin', 'stdout'],
181
attach_fhs={'stderr': devnull})
182
with contextlib.closing(proc.handles['stdin']) as f:
184
with contextlib.closing(proc.handles['stdout']) as f:
185
ciphertext = f.read()
189
self.gnupg.passphrase = None
192
def decrypt(self, data, password):
193
self.gnupg.passphrase = self.password_encode(password)
194
with open(os.devnull) as devnull:
196
proc = self.gnupg.run(['--decrypt'],
197
create_fhs=['stdin', 'stdout'],
198
attach_fhs={'stderr': devnull})
199
with contextlib.closing(proc.handles['stdin'] ) as f:
201
with contextlib.closing(proc.handles['stdout']) as f:
202
decrypted_plaintext = f.read()
206
self.gnupg.passphrase = None
207
return decrypted_plaintext
93
syslogger.setFormatter(logging.Formatter
94
('Mandos [%(process)d]: %(levelname)s:'
96
logger.addHandler(syslogger)
98
console = logging.StreamHandler()
99
console.setFormatter(logging.Formatter('%(name)s [%(process)d]:'
102
logger.addHandler(console)
211
104
class AvahiError(Exception):
212
105
def __init__(self, value, *args, **kwargs):
436
319
def timeout_milliseconds(self):
437
320
"Return the 'timeout' attribute in milliseconds"
438
return timedelta_to_milliseconds(self.timeout)
321
return _timedelta_to_milliseconds(self.timeout)
440
323
def extended_timeout_milliseconds(self):
441
324
"Return the 'extended_timeout' attribute in milliseconds"
442
return timedelta_to_milliseconds(self.extended_timeout)
325
return _timedelta_to_milliseconds(self.extended_timeout)
444
327
def interval_milliseconds(self):
445
328
"Return the 'interval' attribute in milliseconds"
446
return timedelta_to_milliseconds(self.interval)
329
return _timedelta_to_milliseconds(self.interval)
448
331
def approval_delay_milliseconds(self):
449
return timedelta_to_milliseconds(self.approval_delay)
332
return _timedelta_to_milliseconds(self.approval_delay)
451
def __init__(self, name = None, config=None):
334
def __init__(self, name = None, disable_hook=None, config=None):
452
335
"""Note: the 'checker' key in 'config' sets the
453
336
'checker_command' attribute and *not* the 'checker'
475
358
self.host = config.get("host", "")
476
359
self.created = datetime.datetime.utcnow()
477
self.enabled = config.get("enabled", True)
478
361
self.last_approval_request = None
480
self.last_enabled = datetime.datetime.utcnow()
482
self.last_enabled = None
362
self.last_enabled = None
483
363
self.last_checked_ok = None
484
self.last_checker_status = None
485
364
self.timeout = string_to_delta(config["timeout"])
486
365
self.extended_timeout = string_to_delta(config
487
366
["extended_timeout"])
488
367
self.interval = string_to_delta(config["interval"])
368
self.disable_hook = disable_hook
489
369
self.checker = None
490
370
self.checker_initiator_tag = None
491
371
self.disable_initiator_tag = None
493
self.expires = datetime.datetime.utcnow() + self.timeout
496
373
self.checker_callback_tag = None
497
374
self.checker_command = config["checker"]
498
375
self.current_checker_command = None
376
self.last_connect = None
377
self._approved = None
500
378
self.approved_by_default = config.get("approved_by_default",
502
380
self.approvals_pending = 0
507
385
self.changedstate = (multiprocessing_manager
508
386
.Condition(multiprocessing_manager
510
self.client_structure = [attr for attr in
511
self.__dict__.iterkeys()
512
if not attr.startswith("_")]
513
self.client_structure.append("client_structure")
515
for name, t in inspect.getmembers(type(self),
519
if not name.startswith("_"):
520
self.client_structure.append(name)
522
# Send notice to process children that client state has changed
523
389
def send_changedstate(self):
524
with self.changedstate:
525
self.changedstate.notify_all()
390
self.changedstate.acquire()
391
self.changedstate.notify_all()
392
self.changedstate.release()
527
394
def enable(self):
528
395
"""Start this client's checker and timeout hooks"""
551
428
gobject.source_remove(self.checker_initiator_tag)
552
429
self.checker_initiator_tag = None
553
430
self.stop_checker()
431
if self.disable_hook:
432
self.disable_hook(self)
554
433
self.enabled = False
555
434
# Do not run this again if called by a gobject.timeout_add
558
437
def __del__(self):
438
self.disable_hook = None
561
def init_checker(self):
562
# Schedule a new checker to be started an 'interval' from now,
563
# and every interval from then on.
564
self.checker_initiator_tag = (gobject.timeout_add
565
(self.interval_milliseconds(),
567
# Schedule a disable() when 'timeout' has passed
568
self.disable_initiator_tag = (gobject.timeout_add
569
(self.timeout_milliseconds(),
571
# Also start a new checker *right now*.
574
441
def checker_callback(self, pid, condition, command):
575
442
"""The checker has completed, so take appropriate actions."""
576
443
self.checker_callback_tag = None
577
444
self.checker = None
578
445
if os.WIFEXITED(condition):
579
self.last_checker_status = os.WEXITSTATUS(condition)
580
if self.last_checker_status == 0:
446
exitstatus = os.WEXITSTATUS(condition)
581
448
logger.info("Checker for %(name)s succeeded",
583
450
self.checked_ok()
1069
932
datetime_to_dbus, "LastApprovalRequest")
1070
933
approved_by_default = notifychangeproperty(dbus.Boolean,
1071
934
"ApprovedByDefault")
1072
approval_delay = notifychangeproperty(dbus.UInt64,
935
approval_delay = notifychangeproperty(dbus.UInt16,
1073
936
"ApprovalDelay",
1075
timedelta_to_milliseconds)
938
_timedelta_to_milliseconds)
1076
939
approval_duration = notifychangeproperty(
1077
dbus.UInt64, "ApprovalDuration",
1078
type_func = timedelta_to_milliseconds)
940
dbus.UInt16, "ApprovalDuration",
941
type_func = _timedelta_to_milliseconds)
1079
942
host = notifychangeproperty(dbus.String, "Host")
1080
timeout = notifychangeproperty(dbus.UInt64, "Timeout",
943
timeout = notifychangeproperty(dbus.UInt16, "Timeout",
1082
timedelta_to_milliseconds)
945
_timedelta_to_milliseconds)
1083
946
extended_timeout = notifychangeproperty(
1084
dbus.UInt64, "ExtendedTimeout",
1085
type_func = timedelta_to_milliseconds)
1086
interval = notifychangeproperty(dbus.UInt64,
947
dbus.UInt16, "ExtendedTimeout",
948
type_func = _timedelta_to_milliseconds)
949
interval = notifychangeproperty(dbus.UInt16,
1089
timedelta_to_milliseconds)
952
_timedelta_to_milliseconds)
1090
953
checker_command = notifychangeproperty(dbus.String, "Checker")
1092
955
del notifychangeproperty
1367
1222
self.interval = datetime.timedelta(0, 0, 0, value)
1368
1223
if getattr(self, "checker_initiator_tag", None) is None:
1371
# Reschedule checker run
1372
gobject.source_remove(self.checker_initiator_tag)
1373
self.checker_initiator_tag = (gobject.timeout_add
1374
(value, self.start_checker))
1375
self.start_checker() # Start one now, too
1225
# Reschedule checker run
1226
gobject.source_remove(self.checker_initiator_tag)
1227
self.checker_initiator_tag = (gobject.timeout_add
1228
(value, self.start_checker))
1229
self.start_checker() # Start one now, too
1377
1231
# Checker - property
1378
1232
@dbus_service_property(_interface, signature="s",
1919
1767
return timevalue
1770
def if_nametoindex(interface):
1771
"""Call the C function if_nametoindex(), or equivalent
1773
Note: This function cannot accept a unicode string."""
1774
global if_nametoindex
1776
if_nametoindex = (ctypes.cdll.LoadLibrary
1777
(ctypes.util.find_library("c"))
1779
except (OSError, AttributeError):
1780
logger.warning("Doing if_nametoindex the hard way")
1781
def if_nametoindex(interface):
1782
"Get an interface index the hard way, i.e. using fcntl()"
1783
SIOCGIFINDEX = 0x8933 # From /usr/include/linux/sockios.h
1784
with contextlib.closing(socket.socket()) as s:
1785
ifreq = fcntl.ioctl(s, SIOCGIFINDEX,
1786
struct.pack(str("16s16x"),
1788
interface_index = struct.unpack(str("I"),
1790
return interface_index
1791
return if_nametoindex(interface)
1922
1794
def daemon(nochdir = False, noclose = False):
1923
1795
"""See daemon(3). Standard BSD Unix function.
2166
2024
server_settings["use_dbus"] = False
2167
2025
tcp_server.use_dbus = False
2168
2026
protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
2169
service = AvahiServiceToSyslog(name =
2170
server_settings["servicename"],
2171
servicetype = "_mandos._tcp",
2172
protocol = protocol, bus = bus)
2027
service = AvahiService(name = server_settings["servicename"],
2028
servicetype = "_mandos._tcp",
2029
protocol = protocol, bus = bus)
2173
2030
if server_settings["interface"]:
2174
2031
service.interface = (if_nametoindex
2175
2032
(str(server_settings["interface"])))
2182
2039
client_class = functools.partial(ClientDBusTransitional,
2185
special_settings = {
2186
# Some settings need to be accessd by special methods;
2187
# booleans need .getboolean(), etc. Here is a list of them:
2188
"approved_by_default":
2190
client_config.getboolean(section, "approved_by_default"),
2193
client_config.getboolean(section, "enabled"),
2195
# Construct a new dict of client settings of this form:
2196
# { client_name: {setting_name: value, ...}, ...}
2197
# with exceptions for any special settings as defined above
2198
client_settings = dict((clientname,
2201
if setting not in special_settings
2202
else special_settings[setting]
2204
for setting, value in
2205
client_config.items(clientname)))
2206
for clientname in client_config.sections())
2208
old_client_settings = {}
2211
# Get client data and settings from last running state.
2212
if server_settings["restore"]:
2214
with open(stored_state_path, "rb") as stored_state:
2215
clients_data, old_client_settings = (pickle.load
2217
os.remove(stored_state_path)
2218
except IOError as e:
2219
logger.warning("Could not load persistent state: {0}"
2221
if e.errno != errno.ENOENT:
2224
with PGPEngine() as pgp:
2225
for client in clients_data:
2226
client_name = client["name"]
2228
# Decide which value to use after restoring saved state.
2229
# We have three different values: Old config file,
2230
# new config file, and saved state.
2231
# New config value takes precedence if it differs from old
2232
# config value, otherwise use saved state.
2233
for name, value in client_settings[client_name].items():
2235
# For each value in new config, check if it
2236
# differs from the old config value (Except for
2237
# the "secret" attribute)
2238
if (name != "secret" and
2239
value != old_client_settings[client_name]
2241
client[name] = value
2245
# Clients who has passed its expire date can still be
2246
# enabled if its last checker was sucessful. Clients
2247
# whose checker failed before we stored its state is
2248
# assumed to have failed all checkers during downtime.
2249
if client["enabled"]:
2250
if client["expires"] <= (datetime.datetime
2252
# Client has expired
2253
if client["last_checker_status"] != 0:
2254
client["enabled"] = False
2256
client["expires"] = (datetime.datetime
2258
+ client["timeout"])
2260
client["changedstate"] = (multiprocessing_manager
2262
(multiprocessing_manager
2265
new_client = (ClientDBusTransitional.__new__
2266
(ClientDBusTransitional))
2267
tcp_server.clients[client_name] = new_client
2268
new_client.bus = bus
2269
for name, value in client.iteritems():
2270
setattr(new_client, name, value)
2271
client_object_name = unicode(client_name).translate(
2272
{ord("."): ord("_"),
2273
ord("-"): ord("_")})
2274
new_client.dbus_object_path = (dbus.ObjectPath
2276
+ client_object_name))
2277
DBusObjectWithProperties.__init__(new_client,
2282
tcp_server.clients[client_name] = (Client.__new__
2284
for name, value in client.iteritems():
2285
setattr(tcp_server.clients[client_name],
2041
def client_config_items(config, section):
2042
special_settings = {
2043
"approved_by_default":
2044
lambda: config.getboolean(section,
2045
"approved_by_default"),
2047
for name, value in config.items(section):
2289
tcp_server.clients[client_name].secret = (
2290
pgp.decrypt(tcp_server.clients[client_name]
2292
client_settings[client_name]
2295
# If decryption fails, we use secret from new settings
2296
logger.debug("Failed to decrypt {0} old secret"
2297
.format(client_name))
2298
tcp_server.clients[client_name].secret = (
2299
client_settings[client_name]["secret"])
2301
# Create/remove clients based on new changes made to config
2302
for clientname in set(old_client_settings) - set(client_settings):
2303
del tcp_server.clients[clientname]
2304
for clientname in set(client_settings) - set(old_client_settings):
2305
tcp_server.clients[clientname] = (client_class(name
2049
yield (name, special_settings[name]())
2053
tcp_server.clients.update(set(
2054
client_class(name = section,
2055
config= dict(client_config_items(
2056
client_config, section)))
2057
for section in client_config.sections()))
2311
2058
if not tcp_server.clients:
2312
2059
logger.warning("No clients defined")
2393
2139
service.cleanup()
2395
2141
multiprocessing.active_children()
2396
if not (tcp_server.clients or client_settings):
2399
# Store client before exiting. Secrets are encrypted with key
2400
# based on what config file has. If config file is
2401
# removed/edited, old secret will thus be unrecovable.
2403
with PGPEngine() as pgp:
2404
for client in tcp_server.clients.itervalues():
2405
key = client_settings[client.name]["secret"]
2406
client.encrypted_secret = pgp.encrypt(client.secret,
2410
# A list of attributes that will not be stored when
2412
exclude = set(("bus", "changedstate", "secret"))
2413
for name, typ in (inspect.getmembers
2414
(dbus.service.Object)):
2417
client_dict["encrypted_secret"] = (client
2419
for attr in client.client_structure:
2420
if attr not in exclude:
2421
client_dict[attr] = getattr(client, attr)
2423
clients.append(client_dict)
2424
del client_settings[client.name]["secret"]
2427
with os.fdopen(os.open(stored_state_path,
2428
os.O_CREAT|os.O_WRONLY|os.O_TRUNC,
2429
0600), "wb") as stored_state:
2430
pickle.dump((clients, client_settings), stored_state)
2431
except (IOError, OSError) as e:
2432
logger.warning("Could not save persistent state: {0}"
2434
if e.errno not in (errno.ENOENT, errno.EACCES):
2437
# Delete all clients, and settings from config
2438
2142
while tcp_server.clients:
2439
name, client = tcp_server.clients.popitem()
2143
client = tcp_server.clients.pop()
2441
2145
client.remove_from_connection()
2146
client.disable_hook = None
2442
2147
# Don't signal anything except ClientRemoved
2443
2148
client.disable(quiet=True)