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()
1072
935
approval_delay = notifychangeproperty(dbus.UInt16,
1073
936
"ApprovalDelay",
1075
timedelta_to_milliseconds)
938
_timedelta_to_milliseconds)
1076
939
approval_duration = notifychangeproperty(
1077
940
dbus.UInt16, "ApprovalDuration",
1078
type_func = timedelta_to_milliseconds)
941
type_func = _timedelta_to_milliseconds)
1079
942
host = notifychangeproperty(dbus.String, "Host")
1080
943
timeout = notifychangeproperty(dbus.UInt16, "Timeout",
1082
timedelta_to_milliseconds)
945
_timedelta_to_milliseconds)
1083
946
extended_timeout = notifychangeproperty(
1084
947
dbus.UInt16, "ExtendedTimeout",
1085
type_func = timedelta_to_milliseconds)
948
type_func = _timedelta_to_milliseconds)
1086
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.
2164
2024
server_settings["use_dbus"] = False
2165
2025
tcp_server.use_dbus = False
2166
2026
protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
2167
service = AvahiServiceToSyslog(name =
2168
server_settings["servicename"],
2169
servicetype = "_mandos._tcp",
2170
protocol = protocol, bus = bus)
2027
service = AvahiService(name = server_settings["servicename"],
2028
servicetype = "_mandos._tcp",
2029
protocol = protocol, bus = bus)
2171
2030
if server_settings["interface"]:
2172
2031
service.interface = (if_nametoindex
2173
2032
(str(server_settings["interface"])))
2180
2039
client_class = functools.partial(ClientDBusTransitional,
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],
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):
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
tcp_server.clients[client_name].secret = (
2295
client_settings[client_name]["secret"])
2297
# Create/remove clients based on new changes made to config
2298
for clientname in set(old_client_settings) - set(client_settings):
2299
del tcp_server.clients[clientname]
2300
for clientname in set(client_settings) - set(old_client_settings):
2301
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()))
2307
2058
if not tcp_server.clients:
2308
2059
logger.warning("No clients defined")
2389
2139
service.cleanup()
2391
2141
multiprocessing.active_children()
2392
if not (tcp_server.clients or client_settings):
2395
# Store client before exiting. Secrets are encrypted with key
2396
# based on what config file has. If config file is
2397
# removed/edited, old secret will thus be unrecovable.
2399
with PGPEngine() as pgp:
2400
for client in tcp_server.clients.itervalues():
2401
key = client_settings[client.name]["secret"]
2402
client.encrypted_secret = pgp.encrypt(client.secret,
2406
# A list of attributes that will not be stored when
2408
exclude = set(("bus", "changedstate", "secret"))
2409
for name, typ in (inspect.getmembers
2410
(dbus.service.Object)):
2413
client_dict["encrypted_secret"] = (client
2415
for attr in client.client_structure:
2416
if attr not in exclude:
2417
client_dict[attr] = getattr(client, attr)
2419
clients.append(client_dict)
2420
del client_settings[client.name]["secret"]
2423
with os.fdopen(os.open(stored_state_path,
2424
os.O_CREAT|os.O_WRONLY|os.O_TRUNC,
2425
0600), "wb") as stored_state:
2426
pickle.dump((clients, client_settings), stored_state)
2427
except (IOError, OSError) as e:
2428
logger.warning("Could not save persistent state: {0}"
2430
if e.errno not in (errno.ENOENT, errno.EACCES):
2433
# Delete all clients, and settings from config
2434
2142
while tcp_server.clients:
2435
name, client = tcp_server.clients.popitem()
2143
client = tcp_server.clients.pop()
2437
2145
client.remove_from_connection()
2146
client.disable_hook = None
2438
2147
# Don't signal anything except ClientRemoved
2439
2148
client.disable(quiet=True)