83
86
SO_BINDTODEVICE = None
90
stored_state_file = "clients.pickle"
88
#logger = logging.getLogger('mandos')
89
logger = logging.Logger('mandos')
92
logger = logging.getLogger()
90
93
syslogger = (logging.handlers.SysLogHandler
91
94
(facility = logging.handlers.SysLogHandler.LOG_DAEMON,
92
95
address = str("/dev/log")))
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)
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
104
211
class AvahiError(Exception):
105
212
def __init__(self, value, *args, **kwargs):
319
436
def timeout_milliseconds(self):
320
437
"Return the 'timeout' attribute in milliseconds"
321
return _timedelta_to_milliseconds(self.timeout)
438
return timedelta_to_milliseconds(self.timeout)
323
440
def extended_timeout_milliseconds(self):
324
441
"Return the 'extended_timeout' attribute in milliseconds"
325
return _timedelta_to_milliseconds(self.extended_timeout)
442
return timedelta_to_milliseconds(self.extended_timeout)
327
444
def interval_milliseconds(self):
328
445
"Return the 'interval' attribute in milliseconds"
329
return _timedelta_to_milliseconds(self.interval)
446
return timedelta_to_milliseconds(self.interval)
331
448
def approval_delay_milliseconds(self):
332
return _timedelta_to_milliseconds(self.approval_delay)
449
return timedelta_to_milliseconds(self.approval_delay)
334
def __init__(self, name = None, disable_hook=None, config=None):
451
def __init__(self, name = None, config=None):
335
452
"""Note: the 'checker' key in 'config' sets the
336
453
'checker_command' attribute and *not* the 'checker'
358
475
self.host = config.get("host", "")
359
476
self.created = datetime.datetime.utcnow()
477
self.enabled = config.get("enabled", True)
361
478
self.last_approval_request = None
362
self.last_enabled = None
480
self.last_enabled = datetime.datetime.utcnow()
482
self.last_enabled = None
363
483
self.last_checked_ok = None
484
self.last_checker_status = None
364
485
self.timeout = string_to_delta(config["timeout"])
365
486
self.extended_timeout = string_to_delta(config
366
487
["extended_timeout"])
367
488
self.interval = string_to_delta(config["interval"])
368
self.disable_hook = disable_hook
369
489
self.checker = None
370
490
self.checker_initiator_tag = None
371
491
self.disable_initiator_tag = None
493
self.expires = datetime.datetime.utcnow() + self.timeout
373
496
self.checker_callback_tag = None
374
497
self.checker_command = config["checker"]
375
498
self.current_checker_command = None
376
self.last_connect = None
377
self._approved = None
378
500
self.approved_by_default = config.get("approved_by_default",
380
502
self.approvals_pending = 0
385
507
self.changedstate = (multiprocessing_manager
386
508
.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
389
523
def send_changedstate(self):
390
self.changedstate.acquire()
391
self.changedstate.notify_all()
392
self.changedstate.release()
524
with self.changedstate:
525
self.changedstate.notify_all()
394
527
def enable(self):
395
528
"""Start this client's checker and timeout hooks"""
428
551
gobject.source_remove(self.checker_initiator_tag)
429
552
self.checker_initiator_tag = None
430
553
self.stop_checker()
431
if self.disable_hook:
432
self.disable_hook(self)
433
554
self.enabled = False
434
555
# Do not run this again if called by a gobject.timeout_add
437
558
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*.
441
574
def checker_callback(self, pid, condition, command):
442
575
"""The checker has completed, so take appropriate actions."""
443
576
self.checker_callback_tag = None
444
577
self.checker = None
445
578
if os.WIFEXITED(condition):
446
exitstatus = os.WEXITSTATUS(condition)
579
self.last_checker_status = os.WEXITSTATUS(condition)
580
if self.last_checker_status == 0:
448
581
logger.info("Checker for %(name)s succeeded",
450
583
self.checked_ok()
464
598
if timeout is None:
465
599
timeout = self.timeout
466
600
self.last_checked_ok = datetime.datetime.utcnow()
467
gobject.source_remove(self.disable_initiator_tag)
468
self.disable_initiator_tag = (gobject.timeout_add
469
(_timedelta_to_milliseconds
470
(timeout), self.disable))
471
self.expires = datetime.datetime.utcnow() + timeout
601
if self.disable_initiator_tag is not None:
602
gobject.source_remove(self.disable_initiator_tag)
603
if getattr(self, "enabled", False):
604
self.disable_initiator_tag = (gobject.timeout_add
605
(timedelta_to_milliseconds
606
(timeout), self.disable))
607
self.expires = datetime.datetime.utcnow() + timeout
473
609
def need_approval(self):
474
610
self.last_approval_request = datetime.datetime.utcnow()
933
1072
approval_delay = notifychangeproperty(dbus.UInt16,
934
1073
"ApprovalDelay",
936
_timedelta_to_milliseconds)
1075
timedelta_to_milliseconds)
937
1076
approval_duration = notifychangeproperty(
938
1077
dbus.UInt16, "ApprovalDuration",
939
type_func = _timedelta_to_milliseconds)
1078
type_func = timedelta_to_milliseconds)
940
1079
host = notifychangeproperty(dbus.String, "Host")
941
1080
timeout = notifychangeproperty(dbus.UInt16, "Timeout",
943
_timedelta_to_milliseconds)
1082
timedelta_to_milliseconds)
944
1083
extended_timeout = notifychangeproperty(
945
1084
dbus.UInt16, "ExtendedTimeout",
946
type_func = _timedelta_to_milliseconds)
1085
type_func = timedelta_to_milliseconds)
947
1086
interval = notifychangeproperty(dbus.UInt16,
950
_timedelta_to_milliseconds)
1089
timedelta_to_milliseconds)
951
1090
checker_command = notifychangeproperty(dbus.String, "Checker")
953
1092
del notifychangeproperty
1220
1367
self.interval = datetime.timedelta(0, 0, 0, value)
1221
1368
if getattr(self, "checker_initiator_tag", None) is None:
1223
# Reschedule checker run
1224
gobject.source_remove(self.checker_initiator_tag)
1225
self.checker_initiator_tag = (gobject.timeout_add
1226
(value, self.start_checker))
1227
self.start_checker() # Start one now, too
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
1229
1377
# Checker - property
1230
1378
@dbus_service_property(_interface, signature="s",
1765
1919
return timevalue
1768
def if_nametoindex(interface):
1769
"""Call the C function if_nametoindex(), or equivalent
1771
Note: This function cannot accept a unicode string."""
1772
global if_nametoindex
1774
if_nametoindex = (ctypes.cdll.LoadLibrary
1775
(ctypes.util.find_library("c"))
1777
except (OSError, AttributeError):
1778
logger.warning("Doing if_nametoindex the hard way")
1779
def if_nametoindex(interface):
1780
"Get an interface index the hard way, i.e. using fcntl()"
1781
SIOCGIFINDEX = 0x8933 # From /usr/include/linux/sockios.h
1782
with contextlib.closing(socket.socket()) as s:
1783
ifreq = fcntl.ioctl(s, SIOCGIFINDEX,
1784
struct.pack(str("16s16x"),
1786
interface_index = struct.unpack(str("I"),
1788
return interface_index
1789
return if_nametoindex(interface)
1792
1922
def daemon(nochdir = False, noclose = False):
1793
1923
"""See daemon(3). Standard BSD Unix function.
2022
2164
server_settings["use_dbus"] = False
2023
2165
tcp_server.use_dbus = False
2024
2166
protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
2025
service = AvahiService(name = server_settings["servicename"],
2026
servicetype = "_mandos._tcp",
2027
protocol = protocol, bus = bus)
2167
service = AvahiServiceToSyslog(name =
2168
server_settings["servicename"],
2169
servicetype = "_mandos._tcp",
2170
protocol = protocol, bus = bus)
2028
2171
if server_settings["interface"]:
2029
2172
service.interface = (if_nametoindex
2030
2173
(str(server_settings["interface"])))
2037
2180
client_class = functools.partial(ClientDBusTransitional,
2039
def client_config_items(config, section):
2040
special_settings = {
2041
"approved_by_default":
2042
lambda: config.getboolean(section,
2043
"approved_by_default"),
2045
for name, value in config.items(section):
2183
special_settings = {
2184
# Some settings need to be accessd by special methods;
2185
# booleans need .getboolean(), etc. Here is a list of them:
2186
"approved_by_default":
2188
client_config.getboolean(section, "approved_by_default"),
2191
client_config.getboolean(section, "enabled"),
2193
# Construct a new dict of client settings of this form:
2194
# { client_name: {setting_name: value, ...}, ...}
2195
# with exceptions for any special settings as defined above
2196
client_settings = dict((clientname,
2199
if setting not in special_settings
2200
else special_settings[setting]
2202
for setting, value in
2203
client_config.items(clientname)))
2204
for clientname in client_config.sections())
2206
old_client_settings = {}
2209
# Get client data and settings from last running state.
2210
if server_settings["restore"]:
2212
with open(stored_state_path, "rb") as stored_state:
2213
clients_data, old_client_settings = (pickle.load
2215
os.remove(stored_state_path)
2216
except IOError as e:
2217
logger.warning("Could not load persistent state: {0}"
2219
if e.errno != errno.ENOENT:
2222
with PGPEngine() as pgp:
2223
for client in clients_data:
2224
client_name = client["name"]
2226
# Decide which value to use after restoring saved state.
2227
# We have three different values: Old config file,
2228
# new config file, and saved state.
2229
# New config value takes precedence if it differs from old
2230
# config value, otherwise use saved state.
2231
for name, value in client_settings[client_name].items():
2233
# For each value in new config, check if it
2234
# differs from the old config value (Except for
2235
# the "secret" attribute)
2236
if (name != "secret" and
2237
value != old_client_settings[client_name]
2239
setattr(client, name, value)
2243
# Clients who has passed its expire date can still be
2244
# enabled if its last checker was sucessful. Clients
2245
# whose checker failed before we stored its state is
2246
# assumed to have failed all checkers during downtime.
2247
if client["enabled"] and client["last_checked_ok"]:
2248
if ((datetime.datetime.utcnow()
2249
- client["last_checked_ok"])
2250
> client["interval"]):
2251
if client["last_checker_status"] != 0:
2252
client["enabled"] = False
2254
client["expires"] = (datetime.datetime
2256
+ client["timeout"])
2258
client["changedstate"] = (multiprocessing_manager
2260
(multiprocessing_manager
2263
new_client = (ClientDBusTransitional.__new__
2264
(ClientDBusTransitional))
2265
tcp_server.clients[client_name] = new_client
2266
new_client.bus = bus
2267
for name, value in client.iteritems():
2268
setattr(new_client, name, value)
2269
client_object_name = unicode(client_name).translate(
2270
{ord("."): ord("_"),
2271
ord("-"): ord("_")})
2272
new_client.dbus_object_path = (dbus.ObjectPath
2274
+ client_object_name))
2275
DBusObjectWithProperties.__init__(new_client,
2280
tcp_server.clients[client_name] = (Client.__new__
2282
for name, value in client.iteritems():
2283
setattr(tcp_server.clients[client_name],
2047
yield (name, special_settings[name]())
2051
tcp_server.clients.update(set(
2052
client_class(name = section,
2053
config= dict(client_config_items(
2054
client_config, section)))
2055
for section in client_config.sections()))
2287
tcp_server.clients[client_name].secret = (
2288
pgp.decrypt(tcp_server.clients[client_name]
2290
client_settings[client_name]
2293
# If decryption fails, we use secret from new settings
2294
logger.debug("Failed to decrypt {0} old secret"
2295
.format(client_name))
2296
tcp_server.clients[client_name].secret = (
2297
client_settings[client_name]["secret"])
2299
# Create/remove clients based on new changes made to config
2300
for clientname in set(old_client_settings) - set(client_settings):
2301
del tcp_server.clients[clientname]
2302
for clientname in set(client_settings) - set(old_client_settings):
2303
tcp_server.clients[clientname] = (client_class(name
2056
2309
if not tcp_server.clients:
2057
2310
logger.warning("No clients defined")
2137
2391
service.cleanup()
2139
2393
multiprocessing.active_children()
2394
if not (tcp_server.clients or client_settings):
2397
# Store client before exiting. Secrets are encrypted with key
2398
# based on what config file has. If config file is
2399
# removed/edited, old secret will thus be unrecovable.
2401
with PGPEngine() as pgp:
2402
for client in tcp_server.clients.itervalues():
2403
key = client_settings[client.name]["secret"]
2404
client.encrypted_secret = pgp.encrypt(client.secret,
2408
# A list of attributes that will not be stored when
2410
exclude = set(("bus", "changedstate", "secret"))
2411
for name, typ in (inspect.getmembers
2412
(dbus.service.Object)):
2415
client_dict["encrypted_secret"] = (client
2417
for attr in client.client_structure:
2418
if attr not in exclude:
2419
client_dict[attr] = getattr(client, attr)
2421
clients.append(client_dict)
2422
del client_settings[client.name]["secret"]
2425
with os.fdopen(os.open(stored_state_path,
2426
os.O_CREAT|os.O_WRONLY|os.O_TRUNC,
2427
0600), "wb") as stored_state:
2428
pickle.dump((clients, client_settings), stored_state)
2429
except (IOError, OSError) as e:
2430
logger.warning("Could not save persistent state: {0}"
2432
if e.errno not in (errno.ENOENT, errno.EACCES):
2435
# Delete all clients, and settings from config
2140
2436
while tcp_server.clients:
2141
client = tcp_server.clients.pop()
2437
name, client = tcp_server.clients.popitem()
2143
2439
client.remove_from_connection()
2144
client.disable_hook = None
2145
2440
# Don't signal anything except ClientRemoved
2146
2441
client.disable(quiet=True)