107
106
SIOCGIFINDEX = 0x8933 # From /usr/include/linux/sockios.h
108
107
with contextlib.closing(socket.socket()) as s:
109
108
ifreq = fcntl.ioctl(s, SIOCGIFINDEX,
110
struct.pack(b"16s16x", interface))
111
interface_index = struct.unpack("I", ifreq[16:20])[0]
109
struct.pack(str("16s16x"),
111
interface_index = struct.unpack(str("I"),
112
113
return interface_index
115
116
def initlogger(debug, level=logging.WARNING):
116
117
"""init logger and add loglevel"""
119
syslogger = (logging.handlers.SysLogHandler
121
logging.handlers.SysLogHandler.LOG_DAEMON,
122
address = "/dev/log"))
123
119
syslogger.setFormatter(logging.Formatter
124
120
('Mandos [%(process)d]: %(levelname)s:'
176
174
def password_encode(self, password):
177
175
# Passphrase can not be empty and can not contain newlines or
178
176
# 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"))
177
return b"mandos" + binascii.hexlify(password)
187
179
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:
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
203
194
return ciphertext
205
196
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:
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
222
211
return decrypted_plaintext
225
214
class AvahiError(Exception):
226
215
def __init__(self, value, *args, **kwargs):
227
216
self.value = value
228
return super(AvahiError, self).__init__(value, *args,
217
super(AvahiError, self).__init__(value, *args, **kwargs)
218
def __unicode__(self):
219
return unicode(repr(self.value))
231
221
class AvahiServiceError(AvahiError):
450
446
"fingerprint", "host", "interval",
451
447
"last_approval_request", "last_checked_ok",
452
448
"last_enabled", "name", "timeout")
453
client_defaults = { "timeout": "PT5M",
454
"extended_timeout": "PT15M",
449
client_defaults = { "timeout": "5m",
450
"extended_timeout": "15m",
456
452
"checker": "fping -q -- %%(host)s",
458
"approval_delay": "PT0S",
459
"approval_duration": "PT1S",
454
"approval_delay": "0s",
455
"approval_duration": "1s",
460
456
"approved_by_default": "True",
461
457
"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)
465
476
def config_parser(config):
466
477
"""Construct a new dict of client settings of this form:
704
710
# in normal mode, that is already done by daemon(),
705
711
# and in debug mode we don't want to. (Stdin is
706
712
# 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,
715
713
self.checker = subprocess.Popen(command,
719
716
except OSError as error:
720
717
logger.error("Failed to start subprocess",
723
719
self.checker_callback_tag = (gobject.child_watch_add
724
720
(self.checker.pid,
725
721
self.checker_callback,
727
723
# The checker may have completed before the gobject
728
724
# 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",
725
pid, status = os.waitpid(self.checker.pid, os.WNOHANG)
739
727
gobject.source_remove(self.checker_callback_tag)
740
728
self.checker_callback(pid, status, command)
1257
1234
to the D-Bus. Default: no transform
1258
1235
variant_level: D-Bus variant level. Default: 1
1260
attrname = "_{}".format(dbus_name)
1237
attrname = "_{0}".format(dbus_name)
1261
1238
def setter(self, value):
1262
1239
if hasattr(self, "dbus_object_path"):
1263
1240
if (not hasattr(self, attrname) or
1264
1241
type_func(getattr(self, attrname, None))
1265
1242
!= type_func(value)):
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())
1243
dbus_value = transform_func(type_func(value),
1246
self.PropertyChanged(dbus.String(dbus_name),
1281
1248
setattr(self, attrname, value)
1283
1250
return property(lambda self: getattr(self, attrname), setter)
1303
1270
approval_delay = notifychangeproperty(dbus.UInt64,
1304
1271
"ApprovalDelay",
1306
lambda td: td.total_seconds()
1273
timedelta_to_milliseconds)
1308
1274
approval_duration = notifychangeproperty(
1309
1275
dbus.UInt64, "ApprovalDuration",
1310
type_func = lambda td: td.total_seconds() * 1000)
1276
type_func = timedelta_to_milliseconds)
1311
1277
host = notifychangeproperty(dbus.String, "Host")
1312
1278
timeout = notifychangeproperty(dbus.UInt64, "Timeout",
1313
type_func = lambda td:
1314
td.total_seconds() * 1000)
1280
timedelta_to_milliseconds)
1315
1281
extended_timeout = notifychangeproperty(
1316
1282
dbus.UInt64, "ExtendedTimeout",
1317
type_func = lambda td: td.total_seconds() * 1000)
1283
type_func = timedelta_to_milliseconds)
1318
1284
interval = notifychangeproperty(dbus.UInt64,
1321
lambda td: td.total_seconds()
1287
timedelta_to_milliseconds)
1323
1288
checker_command = notifychangeproperty(dbus.String, "Checker")
1324
secret = notifychangeproperty(dbus.ByteArray, "Secret",
1325
invalidate_only=True)
1327
1290
del notifychangeproperty
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")
2220
2093
def string_to_delta(interval):
2221
2094
"""Parse a string and return a datetime.timedelta
2320
2188
parser.add_argument("--no-dbus", action="store_false",
2321
2189
dest="use_dbus", help="Do not provide D-Bus"
2322
" system bus interface", default=None)
2190
" system bus interface")
2323
2191
parser.add_argument("--no-ipv6", action="store_false",
2324
dest="use_ipv6", help="Do not use IPv6",
2192
dest="use_ipv6", help="Do not use IPv6")
2326
2193
parser.add_argument("--no-restore", action="store_false",
2327
2194
dest="restore", help="Do not restore stored"
2328
" state", default=None)
2329
2196
parser.add_argument("--socket", type=int,
2330
2197
help="Specify a file descriptor to a network"
2331
2198
" socket to use instead of creating one")
2332
2199
parser.add_argument("--statedir", metavar="DIR",
2333
2200
help="Directory to save/restore state in")
2334
2201
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",
2202
help="Run in foreground")
2340
2204
options = parser.parse_args()
2342
2206
if options.check:
2344
fail_count, test_count = doctest.testmod()
2345
sys.exit(os.EX_OK if fail_count == 0 else 1)
2347
2211
# Default values for config file for server-global settings
2348
2212
server_defaults = { "interface": "",
2392
2255
for option in ("interface", "address", "port", "debug",
2393
2256
"priority", "servicename", "configdir",
2394
2257
"use_dbus", "use_ipv6", "debuglevel", "restore",
2395
"statedir", "socket", "foreground", "zeroconf"):
2258
"statedir", "socket", "foreground"):
2396
2259
value = getattr(options, option)
2397
2260
if value is not None:
2398
2261
server_settings[option] = value
2400
2263
# Force all strings to be unicode
2401
2264
for option in server_settings.keys():
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])
2265
if type(server_settings[option]) is str:
2266
server_settings[option] = unicode(server_settings[option])
2409
2267
# Debug implies foreground
2410
2268
if server_settings["debug"]:
2411
2269
server_settings["foreground"] = True
2542
2389
use_dbus = False
2543
2390
server_settings["use_dbus"] = False
2544
2391
tcp_server.use_dbus = False
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"]
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"])))
2556
2401
global multiprocessing_manager
2557
2402
multiprocessing_manager = multiprocessing.Manager()