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