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):
267
276
self.entry_group_state_changed_match = None
278
def rename(self, remove=True):
270
279
"""Derived from the Avahi example code"""
271
280
if self.rename_count >= self.max_renames:
272
281
logger.critical("No suitable Zeroconf service name found"
273
282
" after %i retries, exiting.",
274
283
self.rename_count)
275
284
raise AvahiServiceError("Too many renames")
276
self.name = unicode(self.server
277
.GetAlternativeServiceName(self.name))
285
self.name = str(self.server
286
.GetAlternativeServiceName(self.name))
287
self.rename_count += 1
278
288
logger.info("Changing Zeroconf service name to %r ...",
283
294
except dbus.exceptions.DBusException as error:
284
logger.critical("D-Bus Exception", exc_info=error)
287
self.rename_count += 1
295
if (error.get_dbus_name()
296
== "org.freedesktop.Avahi.CollisionError"):
297
logger.info("Local Zeroconf service name collision.")
298
return self.rename(remove=False)
300
logger.critical("D-Bus Exception", exc_info=error)
289
304
def remove(self):
290
305
"""Derived from the Avahi example code"""
384
399
class AvahiServiceToSyslog(AvahiService):
400
def rename(self, *args, **kwargs):
386
401
"""Add the new name to the syslog messages"""
387
ret = AvahiService.rename(self)
402
ret = AvahiService.rename(self, *args, **kwargs)
388
403
syslogger.setFormatter(logging.Formatter
389
('Mandos ({0}) [%(process)d]:'
404
('Mandos ({}) [%(process)d]:'
390
405
' %(levelname)s: %(message)s'
391
406
.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
410
class Client(object):
403
411
"""A representation of a client host served by this server.
458
467
"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
471
def config_parser(config):
478
472
"""Construct a new dict of client settings of this form:
523
def __init__(self, settings, name = None):
520
def __init__(self, settings, name = None, server_settings=None):
522
if server_settings is None:
524
self.server_settings = server_settings
525
525
# adding all client settings
526
for setting, value in settings.iteritems():
526
for setting, value in settings.items():
527
527
setattr(self, setting, value)
612
609
if self.checker_initiator_tag is not None:
613
610
gobject.source_remove(self.checker_initiator_tag)
614
611
self.checker_initiator_tag = (gobject.timeout_add
615
(self.interval_milliseconds(),
613
.total_seconds() * 1000),
616
614
self.start_checker))
617
615
# Schedule a disable() when 'timeout' has passed
618
616
if self.disable_initiator_tag is not None:
619
617
gobject.source_remove(self.disable_initiator_tag)
620
618
self.disable_initiator_tag = (gobject.timeout_add
621
(self.timeout_milliseconds(),
620
.total_seconds() * 1000),
623
622
# Also start a new checker *right now*.
624
623
self.start_checker()
680
679
# If a checker exists, make sure it is not a zombie
682
681
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):
682
except AttributeError:
684
except OSError as error:
685
if error.errno != errno.ECHILD:
689
689
logger.warning("Checker was a zombie")
711
710
# in normal mode, that is already done by daemon(),
712
711
# and in debug mode we don't want to. (Stdin is
713
712
# always replaced by /dev/null.)
713
# The exception is when not debugging but nevertheless
714
# running in the foreground; use the previously
717
if (not self.server_settings["debug"]
718
and self.server_settings["foreground"]):
719
popen_args.update({"stdout": wnull,
714
721
self.checker = subprocess.Popen(command,
717
725
except OSError as error:
718
726
logger.error("Failed to start subprocess",
720
729
self.checker_callback_tag = (gobject.child_watch_add
721
730
(self.checker.pid,
722
731
self.checker_callback,
724
733
# The checker may have completed before the gobject
725
734
# watch was added. Check for this.
726
pid, status = os.waitpid(self.checker.pid, os.WNOHANG)
736
pid, status = os.waitpid(self.checker.pid, os.WNOHANG)
737
except OSError as error:
738
if error.errno == errno.ECHILD:
739
# This should never happen
740
logger.error("Child process vanished",
728
745
gobject.source_remove(self.checker_callback_tag)
729
746
self.checker_callback(pid, status, command)
802
819
"""Decorator to annotate D-Bus methods, signals or properties
822
@dbus_annotations({"org.freedesktop.DBus.Deprecated": "true",
823
"org.freedesktop.DBus.Property."
824
"EmitsChangedSignal": "false"})
805
825
@dbus_service_property("org.example.Interface", signature="b",
807
@dbus_annotations({{"org.freedesktop.DBus.Deprecated": "true",
808
"org.freedesktop.DBus.Property."
809
"EmitsChangedSignal": "false"})
810
827
def Property_dbus_property(self):
811
828
return dbus.Boolean(False)
935
952
value.variant_level+1)
936
953
return dbus.Dictionary(properties, signature="sv")
955
@dbus.service.signal(dbus.PROPERTIES_IFACE, signature="sa{sv}as")
956
def PropertiesChanged(self, interface_name, changed_properties,
957
invalidated_properties):
958
"""Standard D-Bus PropertiesChanged() signal, see D-Bus
938
963
@dbus.service.method(dbus.INTROSPECTABLE_IFACE,
939
964
out_signature="s",
940
965
path_keyword='object_path',
984
1009
# Add interface annotation tags
985
1010
for annotation, value in dict(
986
1011
itertools.chain.from_iterable(
987
annotations().iteritems()
1012
annotations().items()
988
1013
for name, annotations in
989
1014
self._get_all_dbus_things("interface")
990
1015
if name == if_tag.getAttribute("name")
992
1017
ann_tag = document.createElement("annotation")
993
1018
ann_tag.setAttribute("name", annotation)
994
1019
ann_tag.setAttribute("value", value)
1069
1094
interface_names.add(alt_interface)
1070
1095
# Is this a D-Bus signal?
1071
1096
if getattr(attribute, "_dbus_is_signal", False):
1072
# Extract the original non-method function by
1097
# Extract the original non-method undecorated
1098
# function by black magic
1074
1099
nonmethod_func = (dict(
1075
1100
zip(attribute.func_code.co_freevars,
1076
1101
attribute.__closure__))["func"]
1235
1263
to the D-Bus. Default: no transform
1236
1264
variant_level: D-Bus variant level. Default: 1
1238
attrname = "_{0}".format(dbus_name)
1266
attrname = "_{}".format(dbus_name)
1239
1267
def setter(self, value):
1240
1268
if hasattr(self, "dbus_object_path"):
1241
1269
if (not hasattr(self, attrname) or
1242
1270
type_func(getattr(self, attrname, None))
1243
1271
!= type_func(value)):
1244
dbus_value = transform_func(type_func(value),
1247
self.PropertyChanged(dbus.String(dbus_name),
1273
self.PropertiesChanged(_interface,
1278
dbus_value = transform_func(type_func(value),
1281
self.PropertyChanged(dbus.String(dbus_name),
1283
self.PropertiesChanged(_interface,
1285
dbus.String(dbus_name):
1286
dbus_value }), dbus.Array())
1249
1287
setattr(self, attrname, value)
1251
1289
return property(lambda self: getattr(self, attrname), setter)
1271
1309
approval_delay = notifychangeproperty(dbus.UInt64,
1272
1310
"ApprovalDelay",
1274
timedelta_to_milliseconds)
1312
lambda td: td.total_seconds()
1275
1314
approval_duration = notifychangeproperty(
1276
1315
dbus.UInt64, "ApprovalDuration",
1277
type_func = timedelta_to_milliseconds)
1316
type_func = lambda td: td.total_seconds() * 1000)
1278
1317
host = notifychangeproperty(dbus.String, "Host")
1279
1318
timeout = notifychangeproperty(dbus.UInt64, "Timeout",
1281
timedelta_to_milliseconds)
1319
type_func = lambda td:
1320
td.total_seconds() * 1000)
1282
1321
extended_timeout = notifychangeproperty(
1283
1322
dbus.UInt64, "ExtendedTimeout",
1284
type_func = timedelta_to_milliseconds)
1323
type_func = lambda td: td.total_seconds() * 1000)
1285
1324
interval = notifychangeproperty(dbus.UInt64,
1288
timedelta_to_milliseconds)
1327
lambda td: td.total_seconds()
1289
1329
checker_command = notifychangeproperty(dbus.String, "Checker")
1330
secret = notifychangeproperty(dbus.ByteArray, "Secret",
1331
invalidate_only=True)
1291
1333
del notifychangeproperty
1319
1361
*args, **kwargs)
1321
1363
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
1364
old_checker_pid = getattr(self.checker, "pid", None)
1327
1365
r = Client.start_checker(self, *args, **kwargs)
1328
1366
# Only if new checker process was started
1329
1367
if (self.checker is not None
1339
1377
def approve(self, value=True):
1340
1378
self.approved = value
1341
gobject.timeout_add(timedelta_to_milliseconds
1342
(self.approval_duration),
1343
self._reset_approved)
1379
gobject.timeout_add(int(self.approval_duration.total_seconds()
1380
* 1000), self._reset_approved)
1344
1381
self.send_changedstate()
1346
1383
## D-Bus methods, signals & properties
1347
_interface = "se.recompile.Mandos.Client"
1351
@dbus_interface_annotations(_interface)
1353
return { "org.freedesktop.DBus.Property.EmitsChangedSignal":
1358
1389
# CheckerCompleted - signal
1547
1580
gobject.source_remove(self.disable_initiator_tag)
1548
1581
self.disable_initiator_tag = (
1549
1582
gobject.timeout_add(
1550
timedelta_to_milliseconds(self.expires - now),
1583
int((self.expires - now).total_seconds()
1584
* 1000), self.disable))
1553
1586
# ExtendedTimeout - property
1554
1587
@dbus_service_property(_interface, signature="t",
1555
1588
access="readwrite")
1556
1589
def ExtendedTimeout_dbus_property(self, value=None):
1557
1590
if value is None: # get
1558
return dbus.UInt64(self.extended_timeout_milliseconds())
1591
return dbus.UInt64(self.extended_timeout.total_seconds()
1559
1593
self.extended_timeout = datetime.timedelta(0, 0, 0, value)
1561
1595
# Interval - property
2158
2191
token_duration = Token(re.compile(r"P"), None,
2159
2192
frozenset((token_year, token_month,
2160
2193
token_day, token_time,
2162
2195
# Define starting values
2163
2196
value = datetime.timedelta() # Value so far
2164
2197
found_token = None
2165
followers = frozenset(token_duration,) # Following valid tokens
2198
followers = frozenset((token_duration,)) # Following valid tokens
2166
2199
s = duration # String left to parse
2167
2200
# Loop until end token is found
2168
2201
while found_token is not token_end:
2251
2284
# Close all standard open file descriptors
2252
2285
null = os.open(os.devnull, os.O_NOCTTY | os.O_RDWR)
2253
2286
if not stat.S_ISCHR(os.fstat(null).st_mode):
2254
raise OSError(errno.ENODEV,
2255
"{0} not a character device"
2287
raise OSError(errno.ENODEV, "{} not a character device"
2256
2288
.format(os.devnull))
2257
2289
os.dup2(null, sys.stdin.fileno())
2258
2290
os.dup2(null, sys.stdout.fileno())
2269
2301
parser = argparse.ArgumentParser()
2270
2302
parser.add_argument("-v", "--version", action="version",
2271
version = "%(prog)s {0}".format(version),
2303
version = "%(prog)s {}".format(version),
2272
2304
help="show version number and exit")
2273
2305
parser.add_argument("-i", "--interface", metavar="IF",
2274
2306
help="Bind to interface IF")
2294
2326
parser.add_argument("--no-dbus", action="store_false",
2295
2327
dest="use_dbus", help="Do not provide D-Bus"
2296
" system bus interface")
2328
" system bus interface", default=None)
2297
2329
parser.add_argument("--no-ipv6", action="store_false",
2298
dest="use_ipv6", help="Do not use IPv6")
2330
dest="use_ipv6", help="Do not use IPv6",
2299
2332
parser.add_argument("--no-restore", action="store_false",
2300
2333
dest="restore", help="Do not restore stored"
2334
" state", default=None)
2302
2335
parser.add_argument("--socket", type=int,
2303
2336
help="Specify a file descriptor to a network"
2304
2337
" socket to use instead of creating one")
2305
2338
parser.add_argument("--statedir", metavar="DIR",
2306
2339
help="Directory to save/restore state in")
2307
2340
parser.add_argument("--foreground", action="store_true",
2308
help="Run in foreground")
2341
help="Run in foreground", default=None)
2342
parser.add_argument("--no-zeroconf", action="store_false",
2343
dest="zeroconf", help="Do not use Zeroconf",
2310
2346
options = parser.parse_args()
2312
2348
if options.check:
2350
fail_count, test_count = doctest.testmod()
2351
sys.exit(os.EX_OK if fail_count == 0 else 1)
2317
2353
# Default values for config file for server-global settings
2318
2354
server_defaults = { "interface": "",
2361
2399
for option in ("interface", "address", "port", "debug",
2362
2400
"priority", "servicename", "configdir",
2363
2401
"use_dbus", "use_ipv6", "debuglevel", "restore",
2364
"statedir", "socket", "foreground"):
2402
"statedir", "socket", "foreground", "zeroconf"):
2365
2403
value = getattr(options, option)
2366
2404
if value is not None:
2367
2405
server_settings[option] = value
2369
2407
# Force all strings to be unicode
2370
2408
for option in server_settings.keys():
2371
if type(server_settings[option]) is str:
2372
server_settings[option] = unicode(server_settings[option])
2409
if isinstance(server_settings[option], bytes):
2410
server_settings[option] = (server_settings[option]
2412
# Force all boolean options to be boolean
2413
for option in ("debug", "use_dbus", "use_ipv6", "restore",
2414
"foreground", "zeroconf"):
2415
server_settings[option] = bool(server_settings[option])
2373
2416
# Debug implies foreground
2374
2417
if server_settings["debug"]:
2375
2418
server_settings["foreground"] = True
2495
2549
use_dbus = False
2496
2550
server_settings["use_dbus"] = False
2497
2551
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"])))
2553
protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
2554
service = AvahiServiceToSyslog(name =
2555
server_settings["servicename"],
2556
servicetype = "_mandos._tcp",
2557
protocol = protocol, bus = bus)
2558
if server_settings["interface"]:
2559
service.interface = (if_nametoindex
2560
(server_settings["interface"]
2507
2563
global multiprocessing_manager
2508
2564
multiprocessing_manager = multiprocessing.Manager()
2562
2630
if datetime.datetime.utcnow() >= client["expires"]:
2563
2631
if not client["last_checked_ok"]:
2564
2632
logger.warning(
2565
"disabling client {0} - Client never "
2633
"disabling client {} - Client never "
2566
2634
"performed a successful checker"
2567
2635
.format(client_name))
2568
2636
client["enabled"] = False
2569
2637
elif client["last_checker_status"] != 0:
2570
2638
logger.warning(
2571
"disabling client {0} - Client "
2572
"last checker failed with error code {1}"
2639
"disabling client {} - Client last"
2640
" checker failed with error code {}"
2573
2641
.format(client_name,
2574
2642
client["last_checker_status"]))
2575
2643
client["enabled"] = False
2601
2669
clients_data[client_name] = client_settings[client_name]
2603
2671
# Create all client objects
2604
for client_name, client in clients_data.iteritems():
2672
for client_name, client in clients_data.items():
2605
2673
tcp_server.clients[client_name] = client_class(
2606
name = client_name, settings = client)
2674
name = client_name, settings = client,
2675
server_settings = server_settings)
2608
2677
if not tcp_server.clients:
2609
2678
logger.warning("No clients defined")
2785
2857
#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
2861
# From the Avahi example code
2864
except dbus.exceptions.DBusException as error:
2865
logger.critical("D-Bus Exception", exc_info=error)
2868
# End of Avahi example code
2797
2870
gobject.io_add_watch(tcp_server.fileno(), gobject.IO_IN,
2798
2871
lambda *args, **kwargs: