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(b"16s16x", interface))
111
interface_index = struct.unpack("I", ifreq[16:20])[0]
110
struct.pack(str("16s16x"),
112
interface_index = struct.unpack(str("I"),
112
114
return interface_index
115
117
def initlogger(debug, level=logging.WARNING):
116
118
"""init logger and add loglevel"""
119
syslogger = (logging.handlers.SysLogHandler
121
logging.handlers.SysLogHandler.LOG_DAEMON,
122
address = "/dev/log"))
123
120
syslogger.setFormatter(logging.Formatter
124
121
('Mandos [%(process)d]: %(levelname)s:'
176
175
def password_encode(self, password):
177
176
# Passphrase can not be empty and can not contain newlines or
178
177
# NUL bytes. So we prefix it and hex encode it.
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"))
178
return b"mandos" + binascii.hexlify(password)
187
180
def encrypt(self, data, password):
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:
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
203
195
return ciphertext
205
197
def decrypt(self, data, password):
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:
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
222
212
return decrypted_plaintext
225
215
class AvahiError(Exception):
226
216
def __init__(self, value, *args, **kwargs):
227
217
self.value = value
228
return super(AvahiError, self).__init__(value, *args,
218
super(AvahiError, self).__init__(value, *args, **kwargs)
219
def __unicode__(self):
220
return unicode(repr(self.value))
231
222
class AvahiServiceError(AvahiError):
276
267
self.entry_group_state_changed_match = None
278
def rename(self, remove=True):
279
270
"""Derived from the Avahi example code"""
280
271
if self.rename_count >= self.max_renames:
281
272
logger.critical("No suitable Zeroconf service name found"
282
273
" after %i retries, exiting.",
283
274
self.rename_count)
284
275
raise AvahiServiceError("Too many renames")
285
self.name = str(self.server
286
.GetAlternativeServiceName(self.name))
287
self.rename_count += 1
276
self.name = unicode(self.server
277
.GetAlternativeServiceName(self.name))
288
278
logger.info("Changing Zeroconf service name to %r ...",
294
283
except dbus.exceptions.DBusException as error:
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)
284
logger.critical("D-Bus Exception", exc_info=error)
287
self.rename_count += 1
304
289
def remove(self):
305
290
"""Derived from the Avahi example code"""
399
384
class AvahiServiceToSyslog(AvahiService):
400
def rename(self, *args, **kwargs):
401
386
"""Add the new name to the syslog messages"""
402
ret = AvahiService.rename(self, *args, **kwargs)
387
ret = AvahiService.rename(self)
403
388
syslogger.setFormatter(logging.Formatter
404
('Mandos ({}) [%(process)d]:'
389
('Mandos ({0}) [%(process)d]:'
405
390
' %(levelname)s: %(message)s'
406
391
.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))
410
402
class Client(object):
411
403
"""A representation of a client host served by this server.
467
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)
471
477
def config_parser(config):
472
478
"""Construct a new dict of client settings of this form:
517
def __init__(self, settings, name = None, server_settings=None):
523
def __init__(self, settings, name = None):
519
if server_settings is None:
521
self.server_settings = server_settings
522
525
# adding all client settings
523
for setting, value in settings.items():
526
for setting, value in settings.iteritems():
524
527
setattr(self, setting, value)
609
612
if self.checker_initiator_tag is not None:
610
613
gobject.source_remove(self.checker_initiator_tag)
611
614
self.checker_initiator_tag = (gobject.timeout_add
613
.total_seconds() * 1000),
615
(self.interval_milliseconds(),
614
616
self.start_checker))
615
617
# Schedule a disable() when 'timeout' has passed
616
618
if self.disable_initiator_tag is not None:
617
619
gobject.source_remove(self.disable_initiator_tag)
618
620
self.disable_initiator_tag = (gobject.timeout_add
620
.total_seconds() * 1000),
621
(self.timeout_milliseconds(),
622
623
# Also start a new checker *right now*.
623
624
self.start_checker()
679
680
# If a checker exists, make sure it is not a zombie
681
682
pid, status = os.waitpid(self.checker.pid, os.WNOHANG)
682
except AttributeError:
684
except OSError as error:
685
if error.errno != errno.ECHILD:
683
except (AttributeError, OSError) as error:
684
if (isinstance(error, OSError)
685
and error.errno != errno.ECHILD):
689
689
logger.warning("Checker was a zombie")
710
711
# in normal mode, that is already done by daemon(),
711
712
# and in debug mode we don't want to. (Stdin is
712
713
# 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,
721
714
self.checker = subprocess.Popen(command,
725
717
except OSError as error:
726
718
logger.error("Failed to start subprocess",
819
811
"""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"})
825
814
@dbus_service_property("org.example.Interface", signature="b",
816
@dbus_annotations({{"org.freedesktop.DBus.Deprecated": "true",
817
"org.freedesktop.DBus.Property."
818
"EmitsChangedSignal": "false"})
827
819
def Property_dbus_property(self):
828
820
return dbus.Boolean(False)
952
944
value.variant_level+1)
953
945
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
963
947
@dbus.service.method(dbus.INTROSPECTABLE_IFACE,
964
948
out_signature="s",
965
949
path_keyword='object_path',
1009
993
# Add interface annotation tags
1010
994
for annotation, value in dict(
1011
995
itertools.chain.from_iterable(
1012
annotations().items()
996
annotations().iteritems()
1013
997
for name, annotations in
1014
998
self._get_all_dbus_things("interface")
1015
999
if name == if_tag.getAttribute("name")
1017
1001
ann_tag = document.createElement("annotation")
1018
1002
ann_tag.setAttribute("name", annotation)
1019
1003
ann_tag.setAttribute("value", value)
1094
1078
interface_names.add(alt_interface)
1095
1079
# Is this a D-Bus signal?
1096
1080
if getattr(attribute, "_dbus_is_signal", False):
1097
# Extract the original non-method undecorated
1098
# function by black magic
1081
# Extract the original non-method function by
1099
1083
nonmethod_func = (dict(
1100
1084
zip(attribute.func_code.co_freevars,
1101
1085
attribute.__closure__))["func"]
1263
1244
to the D-Bus. Default: no transform
1264
1245
variant_level: D-Bus variant level. Default: 1
1266
attrname = "_{}".format(dbus_name)
1247
attrname = "_{0}".format(dbus_name)
1267
1248
def setter(self, value):
1268
1249
if hasattr(self, "dbus_object_path"):
1269
1250
if (not hasattr(self, attrname) or
1270
1251
type_func(getattr(self, attrname, None))
1271
1252
!= type_func(value)):
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())
1253
dbus_value = transform_func(type_func(value),
1256
self.PropertyChanged(dbus.String(dbus_name),
1287
1258
setattr(self, attrname, value)
1289
1260
return property(lambda self: getattr(self, attrname), setter)
1309
1280
approval_delay = notifychangeproperty(dbus.UInt64,
1310
1281
"ApprovalDelay",
1312
lambda td: td.total_seconds()
1283
timedelta_to_milliseconds)
1314
1284
approval_duration = notifychangeproperty(
1315
1285
dbus.UInt64, "ApprovalDuration",
1316
type_func = lambda td: td.total_seconds() * 1000)
1286
type_func = timedelta_to_milliseconds)
1317
1287
host = notifychangeproperty(dbus.String, "Host")
1318
1288
timeout = notifychangeproperty(dbus.UInt64, "Timeout",
1319
type_func = lambda td:
1320
td.total_seconds() * 1000)
1290
timedelta_to_milliseconds)
1321
1291
extended_timeout = notifychangeproperty(
1322
1292
dbus.UInt64, "ExtendedTimeout",
1323
type_func = lambda td: td.total_seconds() * 1000)
1293
type_func = timedelta_to_milliseconds)
1324
1294
interval = notifychangeproperty(dbus.UInt64,
1327
lambda td: td.total_seconds()
1297
timedelta_to_milliseconds)
1329
1298
checker_command = notifychangeproperty(dbus.String, "Checker")
1330
secret = notifychangeproperty(dbus.ByteArray, "Secret",
1331
invalidate_only=True)
1333
1300
del notifychangeproperty
1361
1328
*args, **kwargs)
1363
1330
def start_checker(self, *args, **kwargs):
1364
old_checker_pid = getattr(self.checker, "pid", None)
1331
old_checker = self.checker
1332
if self.checker is not None:
1333
old_checker_pid = self.checker.pid
1335
old_checker_pid = None
1365
1336
r = Client.start_checker(self, *args, **kwargs)
1366
1337
# Only if new checker process was started
1367
1338
if (self.checker is not None
1377
1348
def approve(self, value=True):
1378
1349
self.approved = value
1379
gobject.timeout_add(int(self.approval_duration.total_seconds()
1380
* 1000), self._reset_approved)
1350
gobject.timeout_add(timedelta_to_milliseconds
1351
(self.approval_duration),
1352
self._reset_approved)
1381
1353
self.send_changedstate()
1383
1355
## D-Bus methods, signals & properties
1356
_interface = "se.recompile.Mandos.Client"
1360
@dbus_interface_annotations(_interface)
1362
return { "org.freedesktop.DBus.Property.EmitsChangedSignal":
1389
1367
# CheckerCompleted - signal
1580
1556
gobject.source_remove(self.disable_initiator_tag)
1581
1557
self.disable_initiator_tag = (
1582
1558
gobject.timeout_add(
1583
int((self.expires - now).total_seconds()
1584
* 1000), self.disable))
1559
timedelta_to_milliseconds(self.expires - now),
1586
1562
# ExtendedTimeout - property
1587
1563
@dbus_service_property(_interface, signature="t",
1588
1564
access="readwrite")
1589
1565
def ExtendedTimeout_dbus_property(self, value=None):
1590
1566
if value is None: # get
1591
return dbus.UInt64(self.extended_timeout.total_seconds()
1567
return dbus.UInt64(self.extended_timeout_milliseconds())
1593
1568
self.extended_timeout = datetime.timedelta(0, 0, 0, value)
1595
1570
# Interval - property
2191
2167
token_duration = Token(re.compile(r"P"), None,
2192
2168
frozenset((token_year, token_month,
2193
2169
token_day, token_time,
2195
2171
# Define starting values
2196
2172
value = datetime.timedelta() # Value so far
2197
2173
found_token = None
2198
followers = frozenset((token_duration,)) # Following valid tokens
2174
followers = frozenset(token_duration,) # Following valid tokens
2199
2175
s = duration # String left to parse
2200
2176
# Loop until end token is found
2201
2177
while found_token is not token_end:
2284
2260
# Close all standard open file descriptors
2285
2261
null = os.open(os.devnull, os.O_NOCTTY | os.O_RDWR)
2286
2262
if not stat.S_ISCHR(os.fstat(null).st_mode):
2287
raise OSError(errno.ENODEV, "{} not a character device"
2263
raise OSError(errno.ENODEV,
2264
"{0} not a character device"
2288
2265
.format(os.devnull))
2289
2266
os.dup2(null, sys.stdin.fileno())
2290
2267
os.dup2(null, sys.stdout.fileno())
2301
2278
parser = argparse.ArgumentParser()
2302
2279
parser.add_argument("-v", "--version", action="version",
2303
version = "%(prog)s {}".format(version),
2280
version = "%(prog)s {0}".format(version),
2304
2281
help="show version number and exit")
2305
2282
parser.add_argument("-i", "--interface", metavar="IF",
2306
2283
help="Bind to interface IF")
2326
2303
parser.add_argument("--no-dbus", action="store_false",
2327
2304
dest="use_dbus", help="Do not provide D-Bus"
2328
" system bus interface", default=None)
2305
" system bus interface")
2329
2306
parser.add_argument("--no-ipv6", action="store_false",
2330
dest="use_ipv6", help="Do not use IPv6",
2307
dest="use_ipv6", help="Do not use IPv6")
2332
2308
parser.add_argument("--no-restore", action="store_false",
2333
2309
dest="restore", help="Do not restore stored"
2334
" state", default=None)
2335
2311
parser.add_argument("--socket", type=int,
2336
2312
help="Specify a file descriptor to a network"
2337
2313
" socket to use instead of creating one")
2338
2314
parser.add_argument("--statedir", metavar="DIR",
2339
2315
help="Directory to save/restore state in")
2340
2316
parser.add_argument("--foreground", action="store_true",
2341
help="Run in foreground", default=None)
2342
parser.add_argument("--no-zeroconf", action="store_false",
2343
dest="zeroconf", help="Do not use Zeroconf",
2317
help="Run in foreground")
2346
2319
options = parser.parse_args()
2348
2321
if options.check:
2350
fail_count, test_count = doctest.testmod()
2351
sys.exit(os.EX_OK if fail_count == 0 else 1)
2353
2326
# Default values for config file for server-global settings
2354
2327
server_defaults = { "interface": "",
2398
2370
for option in ("interface", "address", "port", "debug",
2399
2371
"priority", "servicename", "configdir",
2400
2372
"use_dbus", "use_ipv6", "debuglevel", "restore",
2401
"statedir", "socket", "foreground", "zeroconf"):
2373
"statedir", "socket", "foreground"):
2402
2374
value = getattr(options, option)
2403
2375
if value is not None:
2404
2376
server_settings[option] = value
2406
2378
# Force all strings to be unicode
2407
2379
for option in server_settings.keys():
2408
if isinstance(server_settings[option], bytes):
2409
server_settings[option] = (server_settings[option]
2411
# Force all boolean options to be boolean
2412
for option in ("debug", "use_dbus", "use_ipv6", "restore",
2413
"foreground", "zeroconf"):
2414
server_settings[option] = bool(server_settings[option])
2380
if type(server_settings[option]) is str:
2381
server_settings[option] = unicode(server_settings[option])
2415
2382
# Debug implies foreground
2416
2383
if server_settings["debug"]:
2417
2384
server_settings["foreground"] = True
2548
2504
use_dbus = False
2549
2505
server_settings["use_dbus"] = False
2550
2506
tcp_server.use_dbus = False
2552
protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
2553
service = AvahiServiceToSyslog(name =
2554
server_settings["servicename"],
2555
servicetype = "_mandos._tcp",
2556
protocol = protocol, bus = bus)
2557
if server_settings["interface"]:
2558
service.interface = (if_nametoindex
2559
(server_settings["interface"]
2507
protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
2508
service = AvahiServiceToSyslog(name =
2509
server_settings["servicename"],
2510
servicetype = "_mandos._tcp",
2511
protocol = protocol, bus = bus)
2512
if server_settings["interface"]:
2513
service.interface = (if_nametoindex
2514
(str(server_settings["interface"])))
2562
2516
global multiprocessing_manager
2563
2517
multiprocessing_manager = multiprocessing.Manager()
2629
2571
if datetime.datetime.utcnow() >= client["expires"]:
2630
2572
if not client["last_checked_ok"]:
2631
2573
logger.warning(
2632
"disabling client {} - Client never "
2574
"disabling client {0} - Client never "
2633
2575
"performed a successful checker"
2634
2576
.format(client_name))
2635
2577
client["enabled"] = False
2636
2578
elif client["last_checker_status"] != 0:
2637
2579
logger.warning(
2638
"disabling client {} - Client last"
2639
" checker failed with error code {}"
2580
"disabling client {0} - Client "
2581
"last checker failed with error code {1}"
2640
2582
.format(client_name,
2641
2583
client["last_checker_status"]))
2642
2584
client["enabled"] = False
2668
2610
clients_data[client_name] = client_settings[client_name]
2670
2612
# Create all client objects
2671
for client_name, client in clients_data.items():
2613
for client_name, client in clients_data.iteritems():
2672
2614
tcp_server.clients[client_name] = client_class(
2673
name = client_name, settings = client,
2674
server_settings = server_settings)
2615
name = client_name, settings = client)
2676
2617
if not tcp_server.clients:
2677
2618
logger.warning("No clients defined")
2856
2794
#service.interface = tcp_server.socket.getsockname()[3]
2860
# From the Avahi example code
2863
except dbus.exceptions.DBusException as error:
2864
logger.critical("D-Bus Exception", exc_info=error)
2867
# End of Avahi example code
2797
# From the Avahi example code
2800
except dbus.exceptions.DBusException as error:
2801
logger.critical("D-Bus Exception", exc_info=error)
2804
# End of Avahi example code
2869
2806
gobject.io_add_watch(tcp_server.fileno(), gobject.IO_IN,
2870
2807
lambda *args, **kwargs: