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):
439
442
runtime_expansions: Allowed attributes for runtime expansion.
440
443
expires: datetime.datetime(); time (UTC) when a client will be
441
444
disabled, or None
445
server_settings: The server_settings dict from main()
444
448
runtime_expansions = ("approval_delay", "approval_duration",
445
"created", "enabled", "fingerprint",
446
"host", "interval", "last_checked_ok",
449
"created", "enabled", "expires",
450
"fingerprint", "host", "interval",
451
"last_approval_request", "last_checked_ok",
447
452
"last_enabled", "name", "timeout")
448
client_defaults = { "timeout": "5m",
449
"extended_timeout": "15m",
453
client_defaults = { "timeout": "PT5M",
454
"extended_timeout": "PT15M",
451
456
"checker": "fping -q -- %%(host)s",
453
"approval_delay": "0s",
454
"approval_duration": "1s",
458
"approval_delay": "PT0S",
459
"approval_duration": "PT1S",
455
460
"approved_by_default": "True",
456
461
"enabled": "True",
459
def timeout_milliseconds(self):
460
"Return the 'timeout' attribute in milliseconds"
461
return timedelta_to_milliseconds(self.timeout)
463
def extended_timeout_milliseconds(self):
464
"Return the 'extended_timeout' attribute in milliseconds"
465
return timedelta_to_milliseconds(self.extended_timeout)
467
def interval_milliseconds(self):
468
"Return the 'interval' attribute in milliseconds"
469
return timedelta_to_milliseconds(self.interval)
471
def approval_delay_milliseconds(self):
472
return timedelta_to_milliseconds(self.approval_delay)
475
465
def config_parser(config):
476
466
"""Construct a new dict of client settings of this form:
690
686
self.current_checker_command)
691
687
# Start a new checker if needed
692
688
if self.checker is None:
689
# Escape attributes for the shell
690
escaped_attrs = { attr:
691
re.escape(str(getattr(self, attr)))
692
for attr in self.runtime_expansions }
694
# In case checker_command has exactly one % operator
695
command = self.checker_command % self.host
697
# Escape attributes for the shell
698
escaped_attrs = dict(
700
re.escape(unicode(str(getattr(self, attr, "")),
704
self.runtime_expansions)
707
command = self.checker_command % escaped_attrs
708
except TypeError as error:
709
logger.error('Could not format string "%s"',
710
self.checker_command, exc_info=error)
711
return True # Try again later
694
command = self.checker_command % escaped_attrs
695
except TypeError as error:
696
logger.error('Could not format string "%s"',
697
self.checker_command, exc_info=error)
698
return True # Try again later
712
699
self.current_checker_command = command
714
701
logger.info("Starting checker %r for %s",
717
704
# in normal mode, that is already done by daemon(),
718
705
# and in debug mode we don't want to. (Stdin is
719
706
# always replaced by /dev/null.)
707
# The exception is when not debugging but nevertheless
708
# running in the foreground; use the previously
711
if (not self.server_settings["debug"]
712
and self.server_settings["foreground"]):
713
popen_args.update({"stdout": wnull,
720
715
self.checker = subprocess.Popen(command,
723
self.checker_callback_tag = (gobject.child_watch_add
725
self.checker_callback,
727
# The checker may have completed before the gobject
728
# watch was added. Check for this.
729
pid, status = os.waitpid(self.checker.pid, os.WNOHANG)
731
gobject.source_remove(self.checker_callback_tag)
732
self.checker_callback(pid, status, command)
733
719
except OSError as error:
734
720
logger.error("Failed to start subprocess",
723
self.checker_callback_tag = (gobject.child_watch_add
725
self.checker_callback,
727
# The checker may have completed before the gobject
728
# watch was added. Check for this.
730
pid, status = os.waitpid(self.checker.pid, os.WNOHANG)
731
except OSError as error:
732
if error.errno == errno.ECHILD:
733
# This should never happen
734
logger.error("Child process vanished",
739
gobject.source_remove(self.checker_callback_tag)
740
self.checker_callback(pid, status, command)
736
741
# Re-run this periodically if run by gobject.timeout_add
1241
1257
to the D-Bus. Default: no transform
1242
1258
variant_level: D-Bus variant level. Default: 1
1244
attrname = "_{0}".format(dbus_name)
1260
attrname = "_{}".format(dbus_name)
1245
1261
def setter(self, value):
1246
1262
if hasattr(self, "dbus_object_path"):
1247
1263
if (not hasattr(self, attrname) or
1248
1264
type_func(getattr(self, attrname, None))
1249
1265
!= type_func(value)):
1250
dbus_value = transform_func(type_func(value),
1253
self.PropertyChanged(dbus.String(dbus_name),
1267
self.PropertiesChanged(_interface,
1272
dbus_value = transform_func(type_func(value),
1275
self.PropertyChanged(dbus.String(dbus_name),
1277
self.PropertiesChanged(_interface,
1279
dbus.String(dbus_name):
1280
dbus_value }), dbus.Array())
1255
1281
setattr(self, attrname, value)
1257
1283
return property(lambda self: getattr(self, attrname), setter)
1277
1303
approval_delay = notifychangeproperty(dbus.UInt64,
1278
1304
"ApprovalDelay",
1280
timedelta_to_milliseconds)
1306
lambda td: td.total_seconds()
1281
1308
approval_duration = notifychangeproperty(
1282
1309
dbus.UInt64, "ApprovalDuration",
1283
type_func = timedelta_to_milliseconds)
1310
type_func = lambda td: td.total_seconds() * 1000)
1284
1311
host = notifychangeproperty(dbus.String, "Host")
1285
1312
timeout = notifychangeproperty(dbus.UInt64, "Timeout",
1287
timedelta_to_milliseconds)
1313
type_func = lambda td:
1314
td.total_seconds() * 1000)
1288
1315
extended_timeout = notifychangeproperty(
1289
1316
dbus.UInt64, "ExtendedTimeout",
1290
type_func = timedelta_to_milliseconds)
1317
type_func = lambda td: td.total_seconds() * 1000)
1291
1318
interval = notifychangeproperty(dbus.UInt64,
1294
timedelta_to_milliseconds)
1321
lambda td: td.total_seconds()
1295
1323
checker_command = notifychangeproperty(dbus.String, "Checker")
1324
secret = notifychangeproperty(dbus.ByteArray, "Secret",
1325
invalidate_only=True)
1297
1327
del notifychangeproperty
1906
1926
use_ipv6: Boolean; to use IPv6 or not
1908
1928
def __init__(self, server_address, RequestHandlerClass,
1909
interface=None, use_ipv6=True):
1929
interface=None, use_ipv6=True, socketfd=None):
1930
"""If socketfd is set, use that file descriptor instead of
1931
creating a new one with socket.socket().
1910
1933
self.interface = interface
1912
1935
self.address_family = socket.AF_INET6
1936
if socketfd is not None:
1937
# Save the file descriptor
1938
self.socketfd = socketfd
1939
# Save the original socket.socket() function
1940
self.socket_socket = socket.socket
1941
# To implement --socket, we monkey patch socket.socket.
1943
# (When socketserver.TCPServer is a new-style class, we
1944
# could make self.socket into a property instead of monkey
1945
# patching socket.socket.)
1947
# Create a one-time-only replacement for socket.socket()
1948
@functools.wraps(socket.socket)
1949
def socket_wrapper(*args, **kwargs):
1950
# Restore original function so subsequent calls are
1952
socket.socket = self.socket_socket
1953
del self.socket_socket
1954
# This time only, return a new socket object from the
1955
# saved file descriptor.
1956
return socket.fromfd(self.socketfd, *args, **kwargs)
1957
# Replace socket.socket() function with wrapper
1958
socket.socket = socket_wrapper
1959
# The socketserver.TCPServer.__init__ will call
1960
# socket.socket(), which might be our replacement,
1961
# socket_wrapper(), if socketfd was set.
1913
1962
socketserver.TCPServer.__init__(self, server_address,
1914
1963
RequestHandlerClass)
1915
1965
def server_bind(self):
1916
1966
"""This overrides the normal server_bind() function
1917
1967
to bind to an interface if one was specified, and also NOT to
1926
1976
self.socket.setsockopt(socket.SOL_SOCKET,
1927
1977
SO_BINDTODEVICE,
1978
(self.interface + "\0")
1930
1980
except socket.error as error:
1931
1981
if error.errno == errno.EPERM:
1932
logger.error("No permission to"
1933
" bind to interface %s",
1982
logger.error("No permission to bind to"
1983
" interface %s", self.interface)
1935
1984
elif error.errno == errno.ENOPROTOOPT:
1936
1985
logger.error("SO_BINDTODEVICE not available;"
1937
1986
" cannot bind to interface %s",
1938
1987
self.interface)
1939
1988
elif error.errno == errno.ENODEV:
1940
logger.error("Interface %s does not"
1941
" exist, cannot bind",
1989
logger.error("Interface %s does not exist,"
1990
" cannot bind", self.interface)
1945
1993
# Only bind(2) the socket if we really need to.
2121
def rfc3339_duration_to_delta(duration):
2122
"""Parse an RFC 3339 "duration" and return a datetime.timedelta
2124
>>> rfc3339_duration_to_delta("P7D")
2125
datetime.timedelta(7)
2126
>>> rfc3339_duration_to_delta("PT60S")
2127
datetime.timedelta(0, 60)
2128
>>> rfc3339_duration_to_delta("PT60M")
2129
datetime.timedelta(0, 3600)
2130
>>> rfc3339_duration_to_delta("PT24H")
2131
datetime.timedelta(1)
2132
>>> rfc3339_duration_to_delta("P1W")
2133
datetime.timedelta(7)
2134
>>> rfc3339_duration_to_delta("PT5M30S")
2135
datetime.timedelta(0, 330)
2136
>>> rfc3339_duration_to_delta("P1DT3M20S")
2137
datetime.timedelta(1, 200)
2140
# Parsing an RFC 3339 duration with regular expressions is not
2141
# possible - there would have to be multiple places for the same
2142
# values, like seconds. The current code, while more esoteric, is
2143
# cleaner without depending on a parsing library. If Python had a
2144
# built-in library for parsing we would use it, but we'd like to
2145
# avoid excessive use of external libraries.
2147
# New type for defining tokens, syntax, and semantics all-in-one
2148
Token = collections.namedtuple("Token",
2149
("regexp", # To match token; if
2150
# "value" is not None,
2151
# must have a "group"
2153
"value", # datetime.timedelta or
2155
"followers")) # Tokens valid after
2157
# RFC 3339 "duration" tokens, syntax, and semantics; taken from
2158
# the "duration" ABNF definition in RFC 3339, Appendix A.
2159
token_end = Token(re.compile(r"$"), None, frozenset())
2160
token_second = Token(re.compile(r"(\d+)S"),
2161
datetime.timedelta(seconds=1),
2162
frozenset((token_end,)))
2163
token_minute = Token(re.compile(r"(\d+)M"),
2164
datetime.timedelta(minutes=1),
2165
frozenset((token_second, token_end)))
2166
token_hour = Token(re.compile(r"(\d+)H"),
2167
datetime.timedelta(hours=1),
2168
frozenset((token_minute, token_end)))
2169
token_time = Token(re.compile(r"T"),
2171
frozenset((token_hour, token_minute,
2173
token_day = Token(re.compile(r"(\d+)D"),
2174
datetime.timedelta(days=1),
2175
frozenset((token_time, token_end)))
2176
token_month = Token(re.compile(r"(\d+)M"),
2177
datetime.timedelta(weeks=4),
2178
frozenset((token_day, token_end)))
2179
token_year = Token(re.compile(r"(\d+)Y"),
2180
datetime.timedelta(weeks=52),
2181
frozenset((token_month, token_end)))
2182
token_week = Token(re.compile(r"(\d+)W"),
2183
datetime.timedelta(weeks=1),
2184
frozenset((token_end,)))
2185
token_duration = Token(re.compile(r"P"), None,
2186
frozenset((token_year, token_month,
2187
token_day, token_time,
2189
# Define starting values
2190
value = datetime.timedelta() # Value so far
2192
followers = frozenset((token_duration,)) # Following valid tokens
2193
s = duration # String left to parse
2194
# Loop until end token is found
2195
while found_token is not token_end:
2196
# Search for any currently valid tokens
2197
for token in followers:
2198
match = token.regexp.match(s)
2199
if match is not None:
2201
if token.value is not None:
2202
# Value found, parse digits
2203
factor = int(match.group(1), 10)
2204
# Add to value so far
2205
value += factor * token.value
2206
# Strip token from string
2207
s = token.regexp.sub("", s, 1)
2210
# Set valid next tokens
2211
followers = found_token.followers
2214
# No currently valid tokens were found
2215
raise ValueError("Invalid RFC 3339 duration")
2072
2220
def string_to_delta(interval):
2073
2221
"""Parse a string and return a datetime.timedelta
2167
2320
parser.add_argument("--no-dbus", action="store_false",
2168
2321
dest="use_dbus", help="Do not provide D-Bus"
2169
" system bus interface")
2322
" system bus interface", default=None)
2170
2323
parser.add_argument("--no-ipv6", action="store_false",
2171
dest="use_ipv6", help="Do not use IPv6")
2324
dest="use_ipv6", help="Do not use IPv6",
2172
2326
parser.add_argument("--no-restore", action="store_false",
2173
2327
dest="restore", help="Do not restore stored"
2328
" state", default=None)
2329
parser.add_argument("--socket", type=int,
2330
help="Specify a file descriptor to a network"
2331
" socket to use instead of creating one")
2175
2332
parser.add_argument("--statedir", metavar="DIR",
2176
2333
help="Directory to save/restore state in")
2334
parser.add_argument("--foreground", action="store_true",
2335
help="Run in foreground", default=None)
2336
parser.add_argument("--no-zeroconf", action="store_false",
2337
dest="zeroconf", help="Do not use Zeroconf",
2178
2340
options = parser.parse_args()
2180
2342
if options.check:
2344
fail_count, test_count = doctest.testmod()
2345
sys.exit(os.EX_OK if fail_count == 0 else 1)
2185
2347
# Default values for config file for server-global settings
2186
2348
server_defaults = { "interface": "",
2205
2370
# Convert the SafeConfigParser object to a dict
2206
2371
server_settings = server_config.defaults()
2207
2372
# Use the appropriate methods on the non-string config options
2208
for option in ("debug", "use_dbus", "use_ipv6"):
2373
for option in ("debug", "use_dbus", "use_ipv6", "foreground"):
2209
2374
server_settings[option] = server_config.getboolean("DEFAULT",
2211
2376
if server_settings["port"]:
2212
2377
server_settings["port"] = server_config.getint("DEFAULT",
2379
if server_settings["socket"]:
2380
server_settings["socket"] = server_config.getint("DEFAULT",
2382
# Later, stdin will, and stdout and stderr might, be dup'ed
2383
# over with an opened os.devnull. But we don't want this to
2384
# happen with a supplied network socket.
2385
if 0 <= server_settings["socket"] <= 2:
2386
server_settings["socket"] = os.dup(server_settings
2214
2388
del server_config
2216
2390
# Override the settings from the config file with command line
2218
2392
for option in ("interface", "address", "port", "debug",
2219
2393
"priority", "servicename", "configdir",
2220
2394
"use_dbus", "use_ipv6", "debuglevel", "restore",
2395
"statedir", "socket", "foreground", "zeroconf"):
2222
2396
value = getattr(options, option)
2223
2397
if value is not None:
2224
2398
server_settings[option] = value
2226
2400
# Force all strings to be unicode
2227
2401
for option in server_settings.keys():
2228
if type(server_settings[option]) is str:
2229
server_settings[option] = unicode(server_settings[option])
2402
if isinstance(server_settings[option], bytes):
2403
server_settings[option] = (server_settings[option]
2405
# Force all boolean options to be boolean
2406
for option in ("debug", "use_dbus", "use_ipv6", "restore",
2407
"foreground", "zeroconf"):
2408
server_settings[option] = bool(server_settings[option])
2409
# Debug implies foreground
2410
if server_settings["debug"]:
2411
server_settings["foreground"] = True
2230
2412
# Now we have our good server settings in "server_settings"
2232
2414
##################################################################
2416
if (not server_settings["zeroconf"] and
2417
not (server_settings["port"]
2418
or server_settings["socket"] != "")):
2419
parser.error("Needs port or socket to work without"
2234
2422
# For convenience
2235
2423
debug = server_settings["debug"]
2236
2424
debuglevel = server_settings["debuglevel"]
2343
2542
use_dbus = False
2344
2543
server_settings["use_dbus"] = False
2345
2544
tcp_server.use_dbus = False
2346
protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
2347
service = AvahiServiceToSyslog(name =
2348
server_settings["servicename"],
2349
servicetype = "_mandos._tcp",
2350
protocol = protocol, bus = bus)
2351
if server_settings["interface"]:
2352
service.interface = (if_nametoindex
2353
(str(server_settings["interface"])))
2546
protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
2547
service = AvahiServiceToSyslog(name =
2548
server_settings["servicename"],
2549
servicetype = "_mandos._tcp",
2550
protocol = protocol, bus = bus)
2551
if server_settings["interface"]:
2552
service.interface = (if_nametoindex
2553
(server_settings["interface"]
2355
2556
global multiprocessing_manager
2356
2557
multiprocessing_manager = multiprocessing.Manager()
2449
2662
clients_data[client_name] = client_settings[client_name]
2451
2664
# Create all client objects
2452
for client_name, client in clients_data.iteritems():
2665
for client_name, client in clients_data.items():
2453
2666
tcp_server.clients[client_name] = client_class(
2454
name = client_name, settings = client)
2667
name = client_name, settings = client,
2668
server_settings = server_settings)
2456
2670
if not tcp_server.clients:
2457
2671
logger.warning("No clients defined")
2463
pidfile.write(str(pid) + "\n".encode("utf-8"))
2466
logger.error("Could not write to file %r with PID %d",
2469
# "pidfile" was never created
2674
if pidfile is not None:
2678
pidfile.write("{}\n".format(pid).encode("utf-8"))
2680
logger.error("Could not write to file %r with PID %d",
2471
2683
del pidfilename
2472
signal.signal(signal.SIGINT, signal.SIG_IGN)
2474
2685
signal.signal(signal.SIGHUP, lambda signum, frame: sys.exit())
2475
2686
signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit())