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
1899
1932
use_ipv6: Boolean; to use IPv6 or not
1901
1934
def __init__(self, server_address, RequestHandlerClass,
1902
interface=None, use_ipv6=True):
1935
interface=None, use_ipv6=True, socketfd=None):
1936
"""If socketfd is set, use that file descriptor instead of
1937
creating a new one with socket.socket().
1903
1939
self.interface = interface
1905
1941
self.address_family = socket.AF_INET6
1942
if socketfd is not None:
1943
# Save the file descriptor
1944
self.socketfd = socketfd
1945
# Save the original socket.socket() function
1946
self.socket_socket = socket.socket
1947
# To implement --socket, we monkey patch socket.socket.
1949
# (When socketserver.TCPServer is a new-style class, we
1950
# could make self.socket into a property instead of monkey
1951
# patching socket.socket.)
1953
# Create a one-time-only replacement for socket.socket()
1954
@functools.wraps(socket.socket)
1955
def socket_wrapper(*args, **kwargs):
1956
# Restore original function so subsequent calls are
1958
socket.socket = self.socket_socket
1959
del self.socket_socket
1960
# This time only, return a new socket object from the
1961
# saved file descriptor.
1962
return socket.fromfd(self.socketfd, *args, **kwargs)
1963
# Replace socket.socket() function with wrapper
1964
socket.socket = socket_wrapper
1965
# The socketserver.TCPServer.__init__ will call
1966
# socket.socket(), which might be our replacement,
1967
# socket_wrapper(), if socketfd was set.
1906
1968
socketserver.TCPServer.__init__(self, server_address,
1907
1969
RequestHandlerClass)
1908
1971
def server_bind(self):
1909
1972
"""This overrides the normal server_bind() function
1910
1973
to bind to an interface if one was specified, and also NOT to
1919
1982
self.socket.setsockopt(socket.SOL_SOCKET,
1920
1983
SO_BINDTODEVICE,
1984
(self.interface + "\0")
1923
1986
except socket.error as error:
1924
1987
if error.errno == errno.EPERM:
1925
logger.error("No permission to"
1926
" bind to interface %s",
1988
logger.error("No permission to bind to"
1989
" interface %s", self.interface)
1928
1990
elif error.errno == errno.ENOPROTOOPT:
1929
1991
logger.error("SO_BINDTODEVICE not available;"
1930
1992
" cannot bind to interface %s",
1931
1993
self.interface)
1932
1994
elif error.errno == errno.ENODEV:
1933
logger.error("Interface %s does not"
1934
" exist, cannot bind",
1995
logger.error("Interface %s does not exist,"
1996
" cannot bind", self.interface)
1938
1999
# Only bind(2) the socket if we really need to.
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")
2065
2226
def string_to_delta(interval):
2066
2227
"""Parse a string and return a datetime.timedelta
2160
2326
parser.add_argument("--no-dbus", action="store_false",
2161
2327
dest="use_dbus", help="Do not provide D-Bus"
2162
" system bus interface")
2328
" system bus interface", default=None)
2163
2329
parser.add_argument("--no-ipv6", action="store_false",
2164
dest="use_ipv6", help="Do not use IPv6")
2330
dest="use_ipv6", help="Do not use IPv6",
2165
2332
parser.add_argument("--no-restore", action="store_false",
2166
2333
dest="restore", help="Do not restore stored"
2334
" state", default=None)
2335
parser.add_argument("--socket", type=int,
2336
help="Specify a file descriptor to a network"
2337
" socket to use instead of creating one")
2168
2338
parser.add_argument("--statedir", metavar="DIR",
2169
2339
help="Directory to save/restore state in")
2340
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",
2171
2346
options = parser.parse_args()
2173
2348
if options.check:
2350
fail_count, test_count = doctest.testmod()
2351
sys.exit(os.EX_OK if fail_count == 0 else 1)
2178
2353
# Default values for config file for server-global settings
2179
2354
server_defaults = { "interface": "",
2198
2377
# Convert the SafeConfigParser object to a dict
2199
2378
server_settings = server_config.defaults()
2200
2379
# Use the appropriate methods on the non-string config options
2201
for option in ("debug", "use_dbus", "use_ipv6"):
2380
for option in ("debug", "use_dbus", "use_ipv6", "foreground"):
2202
2381
server_settings[option] = server_config.getboolean("DEFAULT",
2204
2383
if server_settings["port"]:
2205
2384
server_settings["port"] = server_config.getint("DEFAULT",
2386
if server_settings["socket"]:
2387
server_settings["socket"] = server_config.getint("DEFAULT",
2389
# Later, stdin will, and stdout and stderr might, be dup'ed
2390
# over with an opened os.devnull. But we don't want this to
2391
# happen with a supplied network socket.
2392
if 0 <= server_settings["socket"] <= 2:
2393
server_settings["socket"] = os.dup(server_settings
2207
2395
del server_config
2209
2397
# Override the settings from the config file with command line
2211
2399
for option in ("interface", "address", "port", "debug",
2212
2400
"priority", "servicename", "configdir",
2213
2401
"use_dbus", "use_ipv6", "debuglevel", "restore",
2402
"statedir", "socket", "foreground", "zeroconf"):
2215
2403
value = getattr(options, option)
2216
2404
if value is not None:
2217
2405
server_settings[option] = value
2219
2407
# Force all strings to be unicode
2220
2408
for option in server_settings.keys():
2221
if type(server_settings[option]) is str:
2222
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])
2416
# Debug implies foreground
2417
if server_settings["debug"]:
2418
server_settings["foreground"] = True
2223
2419
# Now we have our good server settings in "server_settings"
2225
2421
##################################################################
2423
if (not server_settings["zeroconf"] and
2424
not (server_settings["port"]
2425
or server_settings["socket"] != "")):
2426
parser.error("Needs port or socket to work without"
2227
2429
# For convenience
2228
2430
debug = server_settings["debug"]
2229
2431
debuglevel = server_settings["debuglevel"]
2336
2549
use_dbus = False
2337
2550
server_settings["use_dbus"] = False
2338
2551
tcp_server.use_dbus = False
2339
protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
2340
service = AvahiServiceToSyslog(name =
2341
server_settings["servicename"],
2342
servicetype = "_mandos._tcp",
2343
protocol = protocol, bus = bus)
2344
if server_settings["interface"]:
2345
service.interface = (if_nametoindex
2346
(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"]
2348
2563
global multiprocessing_manager
2349
2564
multiprocessing_manager = multiprocessing.Manager()
2442
2669
clients_data[client_name] = client_settings[client_name]
2444
2671
# Create all client objects
2445
for client_name, client in clients_data.iteritems():
2672
for client_name, client in clients_data.items():
2446
2673
tcp_server.clients[client_name] = client_class(
2447
name = client_name, settings = client)
2674
name = client_name, settings = client,
2675
server_settings = server_settings)
2449
2677
if not tcp_server.clients:
2450
2678
logger.warning("No clients defined")
2456
pidfile.write(str(pid) + "\n".encode("utf-8"))
2459
logger.error("Could not write to file %r with PID %d",
2462
# "pidfile" was never created
2681
if pidfile is not None:
2685
pidfile.write("{}\n".format(pid).encode("utf-8"))
2687
logger.error("Could not write to file %r with PID %d",
2464
2690
del pidfilename
2466
2692
signal.signal(signal.SIGHUP, lambda signum, frame: sys.exit())