107
107
SIOCGIFINDEX = 0x8933 # From /usr/include/linux/sockios.h
108
108
with contextlib.closing(socket.socket()) as s:
109
109
ifreq = fcntl.ioctl(s, SIOCGIFINDEX,
110
struct.pack(str("16s16x"),
112
interface_index = struct.unpack(str("I"),
110
struct.pack(b"16s16x", interface))
111
interface_index = struct.unpack("I", ifreq[16:20])[0]
114
112
return interface_index
117
115
def initlogger(debug, level=logging.WARNING):
118
116
"""init logger and add loglevel"""
119
syslogger = (logging.handlers.SysLogHandler
121
logging.handlers.SysLogHandler.LOG_DAEMON,
122
address = "/dev/log"))
120
123
syslogger.setFormatter(logging.Formatter
121
124
('Mandos [%(process)d]: %(levelname)s:'
175
176
def password_encode(self, password):
176
177
# Passphrase can not be empty and can not contain newlines or
177
178
# NUL bytes. So we prefix it and hex encode it.
178
return b"mandos" + binascii.hexlify(password)
179
encoded = b"mandos" + binascii.hexlify(password)
180
if len(encoded) > 2048:
181
# GnuPG can't handle long passwords, so encode differently
182
encoded = (b"mandos" + password.replace(b"\\", b"\\\\")
183
.replace(b"\n", b"\\n")
184
.replace(b"\0", b"\\x00"))
180
187
def encrypt(self, data, password):
181
self.gnupg.passphrase = self.password_encode(password)
182
with open(os.devnull, "w") as devnull:
184
proc = self.gnupg.run(['--symmetric'],
185
create_fhs=['stdin', 'stdout'],
186
attach_fhs={'stderr': devnull})
187
with contextlib.closing(proc.handles['stdin']) as f:
189
with contextlib.closing(proc.handles['stdout']) as f:
190
ciphertext = f.read()
194
self.gnupg.passphrase = None
188
passphrase = self.password_encode(password)
189
with tempfile.NamedTemporaryFile(dir=self.tempdir
191
passfile.write(passphrase)
193
proc = subprocess.Popen(['gpg', '--symmetric',
197
stdin = subprocess.PIPE,
198
stdout = subprocess.PIPE,
199
stderr = subprocess.PIPE)
200
ciphertext, err = proc.communicate(input = data)
201
if proc.returncode != 0:
195
203
return ciphertext
197
205
def decrypt(self, data, password):
198
self.gnupg.passphrase = self.password_encode(password)
199
with open(os.devnull, "w") as devnull:
201
proc = self.gnupg.run(['--decrypt'],
202
create_fhs=['stdin', 'stdout'],
203
attach_fhs={'stderr': devnull})
204
with contextlib.closing(proc.handles['stdin']) as f:
206
with contextlib.closing(proc.handles['stdout']) as f:
207
decrypted_plaintext = f.read()
211
self.gnupg.passphrase = None
206
passphrase = self.password_encode(password)
207
with tempfile.NamedTemporaryFile(dir = self.tempdir
209
passfile.write(passphrase)
211
proc = subprocess.Popen(['gpg', '--decrypt',
215
stdin = subprocess.PIPE,
216
stdout = subprocess.PIPE,
217
stderr = subprocess.PIPE)
218
decrypted_plaintext, err = proc.communicate(input
220
if proc.returncode != 0:
212
222
return decrypted_plaintext
215
225
class AvahiError(Exception):
216
226
def __init__(self, value, *args, **kwargs):
217
227
self.value = value
218
super(AvahiError, self).__init__(value, *args, **kwargs)
219
def __unicode__(self):
220
return unicode(repr(self.value))
228
return super(AvahiError, self).__init__(value, *args,
222
231
class AvahiServiceError(AvahiError):
386
395
"""Add the new name to the syslog messages"""
387
396
ret = AvahiService.rename(self)
388
397
syslogger.setFormatter(logging.Formatter
389
('Mandos ({0}) [%(process)d]:'
398
('Mandos ({}) [%(process)d]:'
390
399
' %(levelname)s: %(message)s'
391
400
.format(self.name)))
395
def timedelta_to_milliseconds(td):
396
"Convert a datetime.timedelta() to milliseconds"
397
return ((td.days * 24 * 60 * 60 * 1000)
398
+ (td.seconds * 1000)
399
+ (td.microseconds // 1000))
402
404
class Client(object):
403
405
"""A representation of a client host served by this server.
458
461
"enabled": "True",
461
def timeout_milliseconds(self):
462
"Return the 'timeout' attribute in milliseconds"
463
return timedelta_to_milliseconds(self.timeout)
465
def extended_timeout_milliseconds(self):
466
"Return the 'extended_timeout' attribute in milliseconds"
467
return timedelta_to_milliseconds(self.extended_timeout)
469
def interval_milliseconds(self):
470
"Return the 'interval' attribute in milliseconds"
471
return timedelta_to_milliseconds(self.interval)
473
def approval_delay_milliseconds(self):
474
return timedelta_to_milliseconds(self.approval_delay)
477
465
def config_parser(config):
478
466
"""Construct a new dict of client settings of this form:
523
def __init__(self, settings, name = None):
511
def __init__(self, settings, name = None, server_settings=None):
513
if server_settings is None:
515
self.server_settings = server_settings
525
516
# adding all client settings
526
for setting, value in settings.iteritems():
517
for setting, value in settings.items():
527
518
setattr(self, setting, value)
612
603
if self.checker_initiator_tag is not None:
613
604
gobject.source_remove(self.checker_initiator_tag)
614
605
self.checker_initiator_tag = (gobject.timeout_add
615
(self.interval_milliseconds(),
607
.total_seconds() * 1000),
616
608
self.start_checker))
617
609
# Schedule a disable() when 'timeout' has passed
618
610
if self.disable_initiator_tag is not None:
619
611
gobject.source_remove(self.disable_initiator_tag)
620
612
self.disable_initiator_tag = (gobject.timeout_add
621
(self.timeout_milliseconds(),
614
.total_seconds() * 1000),
623
616
# Also start a new checker *right now*.
624
617
self.start_checker()
680
673
# If a checker exists, make sure it is not a zombie
682
675
pid, status = os.waitpid(self.checker.pid, os.WNOHANG)
683
except (AttributeError, OSError) as error:
684
if (isinstance(error, OSError)
685
and error.errno != errno.ECHILD):
676
except AttributeError:
678
except OSError as error:
679
if error.errno != errno.ECHILD:
689
683
logger.warning("Checker was a zombie")
711
704
# in normal mode, that is already done by daemon(),
712
705
# and in debug mode we don't want to. (Stdin is
713
706
# always replaced by /dev/null.)
707
# The exception is when not debugging but nevertheless
708
# running in the foreground; use the previously
711
if (not self.server_settings["debug"]
712
and self.server_settings["foreground"]):
713
popen_args.update({"stdout": wnull,
714
715
self.checker = subprocess.Popen(command,
717
719
except OSError as error:
718
720
logger.error("Failed to start subprocess",
720
723
self.checker_callback_tag = (gobject.child_watch_add
721
724
(self.checker.pid,
722
725
self.checker_callback,
724
727
# The checker may have completed before the gobject
725
728
# watch was added. Check for this.
726
pid, status = os.waitpid(self.checker.pid, os.WNOHANG)
730
pid, status = os.waitpid(self.checker.pid, os.WNOHANG)
731
except OSError as error:
732
if error.errno == errno.ECHILD:
733
# This should never happen
734
logger.error("Child process vanished",
728
739
gobject.source_remove(self.checker_callback_tag)
729
740
self.checker_callback(pid, status, command)
984
995
# Add interface annotation tags
985
996
for annotation, value in dict(
986
997
itertools.chain.from_iterable(
987
annotations().iteritems()
998
annotations().items()
988
999
for name, annotations in
989
1000
self._get_all_dbus_things("interface")
990
1001
if name == if_tag.getAttribute("name")
992
1003
ann_tag = document.createElement("annotation")
993
1004
ann_tag.setAttribute("name", annotation)
994
1005
ann_tag.setAttribute("value", value)
1069
1080
interface_names.add(alt_interface)
1070
1081
# Is this a D-Bus signal?
1071
1082
if getattr(attribute, "_dbus_is_signal", False):
1072
# Extract the original non-method function by
1083
# Extract the original non-method undecorated
1084
# function by black magic
1074
1085
nonmethod_func = (dict(
1075
1086
zip(attribute.func_code.co_freevars,
1076
1087
attribute.__closure__))["func"]
1271
1282
approval_delay = notifychangeproperty(dbus.UInt64,
1272
1283
"ApprovalDelay",
1274
timedelta_to_milliseconds)
1285
lambda td: td.total_seconds()
1275
1287
approval_duration = notifychangeproperty(
1276
1288
dbus.UInt64, "ApprovalDuration",
1277
type_func = timedelta_to_milliseconds)
1289
type_func = lambda td: td.total_seconds() * 1000)
1278
1290
host = notifychangeproperty(dbus.String, "Host")
1279
1291
timeout = notifychangeproperty(dbus.UInt64, "Timeout",
1281
timedelta_to_milliseconds)
1292
type_func = lambda td:
1293
td.total_seconds() * 1000)
1282
1294
extended_timeout = notifychangeproperty(
1283
1295
dbus.UInt64, "ExtendedTimeout",
1284
type_func = timedelta_to_milliseconds)
1296
type_func = lambda td: td.total_seconds() * 1000)
1285
1297
interval = notifychangeproperty(dbus.UInt64,
1288
timedelta_to_milliseconds)
1300
lambda td: td.total_seconds()
1289
1302
checker_command = notifychangeproperty(dbus.String, "Checker")
1291
1304
del notifychangeproperty
1319
1332
*args, **kwargs)
1321
1334
def start_checker(self, *args, **kwargs):
1322
old_checker = self.checker
1323
if self.checker is not None:
1324
old_checker_pid = self.checker.pid
1326
old_checker_pid = None
1335
old_checker_pid = getattr(self.checker, "pid", None)
1327
1336
r = Client.start_checker(self, *args, **kwargs)
1328
1337
# Only if new checker process was started
1329
1338
if (self.checker is not None
1547
1556
gobject.source_remove(self.disable_initiator_tag)
1548
1557
self.disable_initiator_tag = (
1549
1558
gobject.timeout_add(
1550
timedelta_to_milliseconds(self.expires - now),
1559
int((self.expires - now).total_seconds()
1560
* 1000), self.disable))
1553
1562
# ExtendedTimeout - property
1554
1563
@dbus_service_property(_interface, signature="t",
1555
1564
access="readwrite")
1556
1565
def ExtendedTimeout_dbus_property(self, value=None):
1557
1566
if value is None: # get
1558
return dbus.UInt64(self.extended_timeout_milliseconds())
1567
return dbus.UInt64(self.extended_timeout.total_seconds()
1559
1569
self.extended_timeout = datetime.timedelta(0, 0, 0, value)
1561
1571
# Interval - property
2158
2167
token_duration = Token(re.compile(r"P"), None,
2159
2168
frozenset((token_year, token_month,
2160
2169
token_day, token_time,
2162
2171
# Define starting values
2163
2172
value = datetime.timedelta() # Value so far
2164
2173
found_token = None
2165
followers = frozenset(token_duration,) # Following valid tokens
2174
followers = frozenset((token_duration,)) # Following valid tokens
2166
2175
s = duration # String left to parse
2167
2176
# Loop until end token is found
2168
2177
while found_token is not token_end:
2251
2260
# Close all standard open file descriptors
2252
2261
null = os.open(os.devnull, os.O_NOCTTY | os.O_RDWR)
2253
2262
if not stat.S_ISCHR(os.fstat(null).st_mode):
2254
raise OSError(errno.ENODEV,
2255
"{0} not a character device"
2263
raise OSError(errno.ENODEV, "{} not a character device"
2256
2264
.format(os.devnull))
2257
2265
os.dup2(null, sys.stdin.fileno())
2258
2266
os.dup2(null, sys.stdout.fileno())
2269
2277
parser = argparse.ArgumentParser()
2270
2278
parser.add_argument("-v", "--version", action="version",
2271
version = "%(prog)s {0}".format(version),
2279
version = "%(prog)s {}".format(version),
2272
2280
help="show version number and exit")
2273
2281
parser.add_argument("-i", "--interface", metavar="IF",
2274
2282
help="Bind to interface IF")
2294
2302
parser.add_argument("--no-dbus", action="store_false",
2295
2303
dest="use_dbus", help="Do not provide D-Bus"
2296
" system bus interface")
2304
" system bus interface", default=None)
2297
2305
parser.add_argument("--no-ipv6", action="store_false",
2298
dest="use_ipv6", help="Do not use IPv6")
2306
dest="use_ipv6", help="Do not use IPv6",
2299
2308
parser.add_argument("--no-restore", action="store_false",
2300
2309
dest="restore", help="Do not restore stored"
2310
" state", default=None)
2302
2311
parser.add_argument("--socket", type=int,
2303
2312
help="Specify a file descriptor to a network"
2304
2313
" socket to use instead of creating one")
2305
2314
parser.add_argument("--statedir", metavar="DIR",
2306
2315
help="Directory to save/restore state in")
2307
2316
parser.add_argument("--foreground", action="store_true",
2308
help="Run in foreground")
2317
help="Run in foreground", default=None)
2318
parser.add_argument("--no-zeroconf", action="store_false",
2319
dest="zeroconf", help="Do not use Zeroconf",
2310
2322
options = parser.parse_args()
2312
2324
if options.check:
2326
fail_count, test_count = doctest.testmod()
2327
sys.exit(os.EX_OK if fail_count == 0 else 1)
2317
2329
# Default values for config file for server-global settings
2318
2330
server_defaults = { "interface": "",
2361
2374
for option in ("interface", "address", "port", "debug",
2362
2375
"priority", "servicename", "configdir",
2363
2376
"use_dbus", "use_ipv6", "debuglevel", "restore",
2364
"statedir", "socket", "foreground"):
2377
"statedir", "socket", "foreground", "zeroconf"):
2365
2378
value = getattr(options, option)
2366
2379
if value is not None:
2367
2380
server_settings[option] = value
2369
2382
# Force all strings to be unicode
2370
2383
for option in server_settings.keys():
2371
if type(server_settings[option]) is str:
2372
server_settings[option] = unicode(server_settings[option])
2384
if isinstance(server_settings[option], bytes):
2385
server_settings[option] = (server_settings[option]
2387
# Force all boolean options to be boolean
2388
for option in ("debug", "use_dbus", "use_ipv6", "restore",
2389
"foreground", "zeroconf"):
2390
server_settings[option] = bool(server_settings[option])
2373
2391
# Debug implies foreground
2374
2392
if server_settings["debug"]:
2375
2393
server_settings["foreground"] = True
2495
2524
use_dbus = False
2496
2525
server_settings["use_dbus"] = False
2497
2526
tcp_server.use_dbus = False
2498
protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
2499
service = AvahiServiceToSyslog(name =
2500
server_settings["servicename"],
2501
servicetype = "_mandos._tcp",
2502
protocol = protocol, bus = bus)
2503
if server_settings["interface"]:
2504
service.interface = (if_nametoindex
2505
(str(server_settings["interface"])))
2528
protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
2529
service = AvahiServiceToSyslog(name =
2530
server_settings["servicename"],
2531
servicetype = "_mandos._tcp",
2532
protocol = protocol, bus = bus)
2533
if server_settings["interface"]:
2534
service.interface = (if_nametoindex
2535
(server_settings["interface"]
2507
2538
global multiprocessing_manager
2508
2539
multiprocessing_manager = multiprocessing.Manager()
2562
2605
if datetime.datetime.utcnow() >= client["expires"]:
2563
2606
if not client["last_checked_ok"]:
2564
2607
logger.warning(
2565
"disabling client {0} - Client never "
2608
"disabling client {} - Client never "
2566
2609
"performed a successful checker"
2567
2610
.format(client_name))
2568
2611
client["enabled"] = False
2569
2612
elif client["last_checker_status"] != 0:
2570
2613
logger.warning(
2571
"disabling client {0} - Client "
2572
"last checker failed with error code {1}"
2614
"disabling client {} - Client last"
2615
" checker failed with error code {}"
2573
2616
.format(client_name,
2574
2617
client["last_checker_status"]))
2575
2618
client["enabled"] = False
2601
2644
clients_data[client_name] = client_settings[client_name]
2603
2646
# Create all client objects
2604
for client_name, client in clients_data.iteritems():
2647
for client_name, client in clients_data.items():
2605
2648
tcp_server.clients[client_name] = client_class(
2606
name = client_name, settings = client)
2649
name = client_name, settings = client,
2650
server_settings = server_settings)
2608
2652
if not tcp_server.clients:
2609
2653
logger.warning("No clients defined")
2785
2832
#service.interface = tcp_server.socket.getsockname()[3]
2788
# From the Avahi example code
2791
except dbus.exceptions.DBusException as error:
2792
logger.critical("D-Bus Exception", exc_info=error)
2795
# End of Avahi example code
2836
# From the Avahi example code
2839
except dbus.exceptions.DBusException as error:
2840
logger.critical("D-Bus Exception", exc_info=error)
2843
# End of Avahi example code
2797
2845
gobject.io_add_watch(tcp_server.fileno(), gobject.IO_IN,
2798
2846
lambda *args, **kwargs: