106
107
SIOCGIFINDEX = 0x8933 # From /usr/include/linux/sockios.h
107
108
with contextlib.closing(socket.socket()) as s:
108
109
ifreq = fcntl.ioctl(s, SIOCGIFINDEX,
109
struct.pack(str("16s16x"),
111
interface_index = struct.unpack(str("I"),
110
struct.pack(b"16s16x", interface))
111
interface_index = struct.unpack("I", ifreq[16:20])[0]
113
112
return interface_index
116
115
def initlogger(debug, level=logging.WARNING):
117
116
"""init logger and add loglevel"""
119
syslogger = (logging.handlers.SysLogHandler
121
logging.handlers.SysLogHandler.LOG_DAEMON,
122
address = "/dev/log"))
119
123
syslogger.setFormatter(logging.Formatter
120
124
('Mandos [%(process)d]: %(levelname)s:'
174
176
def password_encode(self, password):
175
177
# Passphrase can not be empty and can not contain newlines or
176
178
# NUL bytes. So we prefix it and hex encode it.
177
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"))
179
187
def encrypt(self, data, password):
180
self.gnupg.passphrase = self.password_encode(password)
181
with open(os.devnull, "w") as devnull:
183
proc = self.gnupg.run(['--symmetric'],
184
create_fhs=['stdin', 'stdout'],
185
attach_fhs={'stderr': devnull})
186
with contextlib.closing(proc.handles['stdin']) as f:
188
with contextlib.closing(proc.handles['stdout']) as f:
189
ciphertext = f.read()
193
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:
194
203
return ciphertext
196
205
def decrypt(self, data, password):
197
self.gnupg.passphrase = self.password_encode(password)
198
with open(os.devnull, "w") as devnull:
200
proc = self.gnupg.run(['--decrypt'],
201
create_fhs=['stdin', 'stdout'],
202
attach_fhs={'stderr': devnull})
203
with contextlib.closing(proc.handles['stdin']) as f:
205
with contextlib.closing(proc.handles['stdout']) as f:
206
decrypted_plaintext = f.read()
210
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:
211
222
return decrypted_plaintext
214
225
class AvahiError(Exception):
215
226
def __init__(self, value, *args, **kwargs):
216
227
self.value = value
217
super(AvahiError, self).__init__(value, *args, **kwargs)
218
def __unicode__(self):
219
return unicode(repr(self.value))
228
return super(AvahiError, self).__init__(value, *args,
221
231
class AvahiServiceError(AvahiError):
266
276
self.entry_group_state_changed_match = None
278
def rename(self, remove=True):
269
279
"""Derived from the Avahi example code"""
270
280
if self.rename_count >= self.max_renames:
271
281
logger.critical("No suitable Zeroconf service name found"
272
282
" after %i retries, exiting.",
273
283
self.rename_count)
274
284
raise AvahiServiceError("Too many renames")
275
self.name = unicode(self.server
276
.GetAlternativeServiceName(self.name))
285
self.name = str(self.server
286
.GetAlternativeServiceName(self.name))
287
self.rename_count += 1
277
288
logger.info("Changing Zeroconf service name to %r ...",
282
294
except dbus.exceptions.DBusException as error:
283
logger.critical("D-Bus Exception", exc_info=error)
286
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)
288
304
def remove(self):
289
305
"""Derived from the Avahi example code"""
383
399
class AvahiServiceToSyslog(AvahiService):
400
def rename(self, *args, **kwargs):
385
401
"""Add the new name to the syslog messages"""
386
ret = AvahiService.rename(self)
402
ret = AvahiService.rename(self, *args, **kwargs)
387
403
syslogger.setFormatter(logging.Formatter
388
('Mandos ({0}) [%(process)d]:'
404
('Mandos ({}) [%(process)d]:'
389
405
' %(levelname)s: %(message)s'
390
406
.format(self.name)))
394
def timedelta_to_milliseconds(td):
395
"Convert a datetime.timedelta() to milliseconds"
396
return ((td.days * 24 * 60 * 60 * 1000)
397
+ (td.seconds * 1000)
398
+ (td.microseconds // 1000))
401
410
class Client(object):
402
411
"""A representation of a client host served by this server.
446
456
"fingerprint", "host", "interval",
447
457
"last_approval_request", "last_checked_ok",
448
458
"last_enabled", "name", "timeout")
449
client_defaults = { "timeout": "5m",
450
"extended_timeout": "15m",
459
client_defaults = { "timeout": "PT5M",
460
"extended_timeout": "PT15M",
452
462
"checker": "fping -q -- %%(host)s",
454
"approval_delay": "0s",
455
"approval_duration": "1s",
464
"approval_delay": "PT0S",
465
"approval_duration": "PT1S",
456
466
"approved_by_default": "True",
457
467
"enabled": "True",
460
def timeout_milliseconds(self):
461
"Return the 'timeout' attribute in milliseconds"
462
return timedelta_to_milliseconds(self.timeout)
464
def extended_timeout_milliseconds(self):
465
"Return the 'extended_timeout' attribute in milliseconds"
466
return timedelta_to_milliseconds(self.extended_timeout)
468
def interval_milliseconds(self):
469
"Return the 'interval' attribute in milliseconds"
470
return timedelta_to_milliseconds(self.interval)
472
def approval_delay_milliseconds(self):
473
return timedelta_to_milliseconds(self.approval_delay)
476
471
def config_parser(config):
477
472
"""Construct a new dict of client settings of this form:
710
710
# in normal mode, that is already done by daemon(),
711
711
# and in debug mode we don't want to. (Stdin is
712
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,
713
721
self.checker = subprocess.Popen(command,
716
725
except OSError as error:
717
726
logger.error("Failed to start subprocess",
719
729
self.checker_callback_tag = (gobject.child_watch_add
720
730
(self.checker.pid,
721
731
self.checker_callback,
723
733
# The checker may have completed before the gobject
724
734
# watch was added. Check for this.
725
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",
727
745
gobject.source_remove(self.checker_callback_tag)
728
746
self.checker_callback(pid, status, command)
1234
1263
to the D-Bus. Default: no transform
1235
1264
variant_level: D-Bus variant level. Default: 1
1237
attrname = "_{0}".format(dbus_name)
1266
attrname = "_{}".format(dbus_name)
1238
1267
def setter(self, value):
1239
1268
if hasattr(self, "dbus_object_path"):
1240
1269
if (not hasattr(self, attrname) or
1241
1270
type_func(getattr(self, attrname, None))
1242
1271
!= type_func(value)):
1243
dbus_value = transform_func(type_func(value),
1246
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())
1248
1287
setattr(self, attrname, value)
1250
1289
return property(lambda self: getattr(self, attrname), setter)
1270
1309
approval_delay = notifychangeproperty(dbus.UInt64,
1271
1310
"ApprovalDelay",
1273
timedelta_to_milliseconds)
1312
lambda td: td.total_seconds()
1274
1314
approval_duration = notifychangeproperty(
1275
1315
dbus.UInt64, "ApprovalDuration",
1276
type_func = timedelta_to_milliseconds)
1316
type_func = lambda td: td.total_seconds() * 1000)
1277
1317
host = notifychangeproperty(dbus.String, "Host")
1278
1318
timeout = notifychangeproperty(dbus.UInt64, "Timeout",
1280
timedelta_to_milliseconds)
1319
type_func = lambda td:
1320
td.total_seconds() * 1000)
1281
1321
extended_timeout = notifychangeproperty(
1282
1322
dbus.UInt64, "ExtendedTimeout",
1283
type_func = timedelta_to_milliseconds)
1323
type_func = lambda td: td.total_seconds() * 1000)
1284
1324
interval = notifychangeproperty(dbus.UInt64,
1287
timedelta_to_milliseconds)
1327
lambda td: td.total_seconds()
1288
1329
checker_command = notifychangeproperty(dbus.String, "Checker")
1330
secret = notifychangeproperty(dbus.ByteArray, "Secret",
1331
invalidate_only=True)
1290
1333
del notifychangeproperty
2127
def rfc3339_duration_to_delta(duration):
2128
"""Parse an RFC 3339 "duration" and return a datetime.timedelta
2130
>>> rfc3339_duration_to_delta("P7D")
2131
datetime.timedelta(7)
2132
>>> rfc3339_duration_to_delta("PT60S")
2133
datetime.timedelta(0, 60)
2134
>>> rfc3339_duration_to_delta("PT60M")
2135
datetime.timedelta(0, 3600)
2136
>>> rfc3339_duration_to_delta("PT24H")
2137
datetime.timedelta(1)
2138
>>> rfc3339_duration_to_delta("P1W")
2139
datetime.timedelta(7)
2140
>>> rfc3339_duration_to_delta("PT5M30S")
2141
datetime.timedelta(0, 330)
2142
>>> rfc3339_duration_to_delta("P1DT3M20S")
2143
datetime.timedelta(1, 200)
2146
# Parsing an RFC 3339 duration with regular expressions is not
2147
# possible - there would have to be multiple places for the same
2148
# values, like seconds. The current code, while more esoteric, is
2149
# cleaner without depending on a parsing library. If Python had a
2150
# built-in library for parsing we would use it, but we'd like to
2151
# avoid excessive use of external libraries.
2153
# New type for defining tokens, syntax, and semantics all-in-one
2154
Token = collections.namedtuple("Token",
2155
("regexp", # To match token; if
2156
# "value" is not None,
2157
# must have a "group"
2159
"value", # datetime.timedelta or
2161
"followers")) # Tokens valid after
2163
# RFC 3339 "duration" tokens, syntax, and semantics; taken from
2164
# the "duration" ABNF definition in RFC 3339, Appendix A.
2165
token_end = Token(re.compile(r"$"), None, frozenset())
2166
token_second = Token(re.compile(r"(\d+)S"),
2167
datetime.timedelta(seconds=1),
2168
frozenset((token_end,)))
2169
token_minute = Token(re.compile(r"(\d+)M"),
2170
datetime.timedelta(minutes=1),
2171
frozenset((token_second, token_end)))
2172
token_hour = Token(re.compile(r"(\d+)H"),
2173
datetime.timedelta(hours=1),
2174
frozenset((token_minute, token_end)))
2175
token_time = Token(re.compile(r"T"),
2177
frozenset((token_hour, token_minute,
2179
token_day = Token(re.compile(r"(\d+)D"),
2180
datetime.timedelta(days=1),
2181
frozenset((token_time, token_end)))
2182
token_month = Token(re.compile(r"(\d+)M"),
2183
datetime.timedelta(weeks=4),
2184
frozenset((token_day, token_end)))
2185
token_year = Token(re.compile(r"(\d+)Y"),
2186
datetime.timedelta(weeks=52),
2187
frozenset((token_month, token_end)))
2188
token_week = Token(re.compile(r"(\d+)W"),
2189
datetime.timedelta(weeks=1),
2190
frozenset((token_end,)))
2191
token_duration = Token(re.compile(r"P"), None,
2192
frozenset((token_year, token_month,
2193
token_day, token_time,
2195
# Define starting values
2196
value = datetime.timedelta() # Value so far
2198
followers = frozenset((token_duration,)) # Following valid tokens
2199
s = duration # String left to parse
2200
# Loop until end token is found
2201
while found_token is not token_end:
2202
# Search for any currently valid tokens
2203
for token in followers:
2204
match = token.regexp.match(s)
2205
if match is not None:
2207
if token.value is not None:
2208
# Value found, parse digits
2209
factor = int(match.group(1), 10)
2210
# Add to value so far
2211
value += factor * token.value
2212
# Strip token from string
2213
s = token.regexp.sub("", s, 1)
2216
# Set valid next tokens
2217
followers = found_token.followers
2220
# No currently valid tokens were found
2221
raise ValueError("Invalid RFC 3339 duration")
2093
2226
def string_to_delta(interval):
2094
2227
"""Parse a string and return a datetime.timedelta
2188
2326
parser.add_argument("--no-dbus", action="store_false",
2189
2327
dest="use_dbus", help="Do not provide D-Bus"
2190
" system bus interface")
2328
" system bus interface", default=None)
2191
2329
parser.add_argument("--no-ipv6", action="store_false",
2192
dest="use_ipv6", help="Do not use IPv6")
2330
dest="use_ipv6", help="Do not use IPv6",
2193
2332
parser.add_argument("--no-restore", action="store_false",
2194
2333
dest="restore", help="Do not restore stored"
2334
" state", default=None)
2196
2335
parser.add_argument("--socket", type=int,
2197
2336
help="Specify a file descriptor to a network"
2198
2337
" socket to use instead of creating one")
2199
2338
parser.add_argument("--statedir", metavar="DIR",
2200
2339
help="Directory to save/restore state in")
2201
2340
parser.add_argument("--foreground", action="store_true",
2202
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",
2204
2346
options = parser.parse_args()
2206
2348
if options.check:
2350
fail_count, test_count = doctest.testmod()
2351
sys.exit(os.EX_OK if fail_count == 0 else 1)
2211
2353
# Default values for config file for server-global settings
2212
2354
server_defaults = { "interface": "",
2255
2398
for option in ("interface", "address", "port", "debug",
2256
2399
"priority", "servicename", "configdir",
2257
2400
"use_dbus", "use_ipv6", "debuglevel", "restore",
2258
"statedir", "socket", "foreground"):
2401
"statedir", "socket", "foreground", "zeroconf"):
2259
2402
value = getattr(options, option)
2260
2403
if value is not None:
2261
2404
server_settings[option] = value
2263
2406
# Force all strings to be unicode
2264
2407
for option in server_settings.keys():
2265
if type(server_settings[option]) is str:
2266
server_settings[option] = unicode(server_settings[option])
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])
2267
2415
# Debug implies foreground
2268
2416
if server_settings["debug"]:
2269
2417
server_settings["foreground"] = True
2389
2548
use_dbus = False
2390
2549
server_settings["use_dbus"] = False
2391
2550
tcp_server.use_dbus = False
2392
protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
2393
service = AvahiServiceToSyslog(name =
2394
server_settings["servicename"],
2395
servicetype = "_mandos._tcp",
2396
protocol = protocol, bus = bus)
2397
if server_settings["interface"]:
2398
service.interface = (if_nametoindex
2399
(str(server_settings["interface"])))
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"]
2401
2562
global multiprocessing_manager
2402
2563
multiprocessing_manager = multiprocessing.Manager()