220
223
instance %(name)s can be used in the command.
221
224
current_checker_command: string; current running checker_command
228
def _datetime_to_milliseconds(dt):
229
"Convert a datetime.datetime() to milliseconds"
230
return ((dt.days * 24 * 60 * 60 * 1000)
231
+ (dt.seconds * 1000)
232
+ (dt.microseconds // 1000))
223
234
def timeout_milliseconds(self):
224
235
"Return the 'timeout' attribute in milliseconds"
225
return ((self.timeout.days * 24 * 60 * 60 * 1000)
226
+ (self.timeout.seconds * 1000)
227
+ (self.timeout.microseconds // 1000))
236
return self._datetime_to_milliseconds(self.timeout)
229
238
def interval_milliseconds(self):
230
239
"Return the 'interval' attribute in milliseconds"
231
return ((self.interval.days * 24 * 60 * 60 * 1000)
232
+ (self.interval.seconds * 1000)
233
+ (self.interval.microseconds // 1000))
240
return self._datetime_to_milliseconds(self.interval)
235
242
def __init__(self, name = None, disable_hook=None, config=None):
236
243
"""Note: the 'checker' key in 'config' sets the
243
250
# Uppercase and remove spaces from fingerprint for later
244
251
# comparison purposes with return value from the fingerprint()
246
self.fingerprint = (config["fingerprint"].upper()
253
self.fingerprint = (config[u"fingerprint"].upper()
247
254
.replace(u" ", u""))
248
255
logger.debug(u" Fingerprint: %s", self.fingerprint)
249
if "secret" in config:
250
self.secret = config["secret"].decode(u"base64")
251
elif "secfile" in config:
256
if u"secret" in config:
257
self.secret = config[u"secret"].decode(u"base64")
258
elif u"secfile" in config:
252
259
with closing(open(os.path.expanduser
253
260
(os.path.expandvars
254
(config["secfile"])))) as secfile:
261
(config[u"secfile"])))) as secfile:
255
262
self.secret = secfile.read()
257
264
raise TypeError(u"No secret or secfile for client %s"
259
self.host = config.get("host", "")
266
self.host = config.get(u"host", u"")
260
267
self.created = datetime.datetime.utcnow()
261
268
self.enabled = False
262
269
self.last_enabled = None
263
270
self.last_checked_ok = None
264
self.timeout = string_to_delta(config["timeout"])
265
self.interval = string_to_delta(config["interval"])
271
self.timeout = string_to_delta(config[u"timeout"])
272
self.interval = string_to_delta(config[u"interval"])
266
273
self.disable_hook = disable_hook
267
274
self.checker = None
268
275
self.checker_initiator_tag = None
269
276
self.disable_initiator_tag = None
270
277
self.checker_callback_tag = None
271
self.checker_command = config["checker"]
278
self.checker_command = config[u"checker"]
272
279
self.current_checker_command = None
273
280
self.last_connect = None
524
534
# Emit D-Bus signal
525
535
self.CheckerStarted(self.current_checker_command)
526
536
self.PropertyChanged(
527
dbus.String("checker_running"),
537
dbus.String(u"checker_running"),
528
538
dbus.Boolean(True, variant_level=1))
531
541
def stop_checker(self, *args, **kwargs):
532
old_checker = getattr(self, "checker", None)
542
old_checker = getattr(self, u"checker", None)
533
543
r = Client.stop_checker(self, *args, **kwargs)
534
544
if (old_checker is not None
535
and getattr(self, "checker", None) is None):
545
and getattr(self, u"checker", None) is None):
536
546
self.PropertyChanged(dbus.String(u"checker_running"),
537
547
dbus.Boolean(False, variant_level=1))
541
551
_interface = u"se.bsnet.fukt.Mandos.Client"
543
553
# CheckedOK - method
544
CheckedOK = dbus.service.method(_interface)(checked_ok)
545
CheckedOK.__name__ = "CheckedOK"
554
@dbus.service.method(_interface)
556
return self.checked_ok()
547
558
# CheckerCompleted - signal
548
@dbus.service.signal(_interface, signature="nxs")
559
@dbus.service.signal(_interface, signature=u"nxs")
549
560
def CheckerCompleted(self, exitcode, waitstatus, command):
553
564
# CheckerStarted - signal
554
@dbus.service.signal(_interface, signature="s")
565
@dbus.service.signal(_interface, signature=u"s")
555
566
def CheckerStarted(self, command):
559
570
# GetAllProperties - method
560
@dbus.service.method(_interface, out_signature="a{sv}")
571
@dbus.service.method(_interface, out_signature=u"a{sv}")
561
572
def GetAllProperties(self):
563
574
return dbus.Dictionary({
575
dbus.String(u"name"):
565
576
dbus.String(self.name, variant_level=1),
566
dbus.String("fingerprint"):
577
dbus.String(u"fingerprint"):
567
578
dbus.String(self.fingerprint, variant_level=1),
579
dbus.String(u"host"):
569
580
dbus.String(self.host, variant_level=1),
570
dbus.String("created"):
581
dbus.String(u"created"):
571
582
_datetime_to_dbus(self.created, variant_level=1),
572
dbus.String("last_enabled"):
583
dbus.String(u"last_enabled"):
573
584
(_datetime_to_dbus(self.last_enabled,
575
586
if self.last_enabled is not None
576
587
else dbus.Boolean(False, variant_level=1)),
577
dbus.String("enabled"):
588
dbus.String(u"enabled"):
578
589
dbus.Boolean(self.enabled, variant_level=1),
579
dbus.String("last_checked_ok"):
590
dbus.String(u"last_checked_ok"):
580
591
(_datetime_to_dbus(self.last_checked_ok,
582
593
if self.last_checked_ok is not None
583
594
else dbus.Boolean (False, variant_level=1)),
584
dbus.String("timeout"):
595
dbus.String(u"timeout"):
585
596
dbus.UInt64(self.timeout_milliseconds(),
586
597
variant_level=1),
587
dbus.String("interval"):
598
dbus.String(u"interval"):
588
599
dbus.UInt64(self.interval_milliseconds(),
589
600
variant_level=1),
590
dbus.String("checker"):
601
dbus.String(u"checker"):
591
602
dbus.String(self.checker_command,
592
603
variant_level=1),
593
dbus.String("checker_running"):
604
dbus.String(u"checker_running"):
594
605
dbus.Boolean(self.checker is not None,
595
606
variant_level=1),
596
dbus.String("object_path"):
607
dbus.String(u"object_path"):
597
608
dbus.ObjectPath(self.dbus_object_path,
601
612
# IsStillValid - method
602
@dbus.service.method(_interface, out_signature="b")
613
@dbus.service.method(_interface, out_signature=u"b")
603
614
def IsStillValid(self):
604
615
return self.still_valid()
606
617
# PropertyChanged - signal
607
@dbus.service.signal(_interface, signature="sv")
618
@dbus.service.signal(_interface, signature=u"sv")
608
619
def PropertyChanged(self, property, value):
927
941
self.enabled = True
928
942
def handle_ipc(self, source, condition, file_objects={}):
929
943
condition_names = {
930
gobject.IO_IN: "IN", # There is data to read.
931
gobject.IO_OUT: "OUT", # Data can be written (without
933
gobject.IO_PRI: "PRI", # There is urgent data to read.
934
gobject.IO_ERR: "ERR", # Error condition.
935
gobject.IO_HUP: "HUP" # Hung up (the connection has been
936
# broken, usually for pipes and
944
gobject.IO_IN: u"IN", # There is data to read.
945
gobject.IO_OUT: u"OUT", # Data can be written (without
947
gobject.IO_PRI: u"PRI", # There is urgent data to read.
948
gobject.IO_ERR: u"ERR", # Error condition.
949
gobject.IO_HUP: u"HUP" # Hung up (the connection has been
950
# broken, usually for pipes and
939
953
conditions_string = ' | '.join(name
940
954
for cond, name in
941
955
condition_names.iteritems()
942
956
if cond & condition)
943
logger.debug("Handling IPC: FD = %d, condition = %s", source,
957
logger.debug(u"Handling IPC: FD = %d, condition = %s", source,
944
958
conditions_string)
946
960
# Turn the pipe file descriptor into a Python file object
947
961
if source not in file_objects:
948
file_objects[source] = os.fdopen(source, "r", 1)
962
file_objects[source] = os.fdopen(source, u"r", 1)
950
964
# Read a line from the file object
951
965
cmdline = file_objects[source].readline()
1060
1074
raise AvahiGroupError(u"State changed: %s" % unicode(error))
1062
1076
def if_nametoindex(interface):
1063
"""Call the C function if_nametoindex(), or equivalent"""
1077
"""Call the C function if_nametoindex(), or equivalent
1079
Note: This function cannot accept a unicode string."""
1064
1080
global if_nametoindex
1066
1082
if_nametoindex = (ctypes.cdll.LoadLibrary
1067
(ctypes.util.find_library("c"))
1083
(ctypes.util.find_library(u"c"))
1068
1084
.if_nametoindex)
1069
1085
except (OSError, AttributeError):
1070
if "struct" not in sys.modules:
1072
if "fcntl" not in sys.modules:
1086
logger.warning(u"Doing if_nametoindex the hard way")
1074
1087
def if_nametoindex(interface):
1075
1088
"Get an interface index the hard way, i.e. using fcntl()"
1076
1089
SIOCGIFINDEX = 0x8933 # From /usr/include/linux/sockios.h
1077
1090
with closing(socket.socket()) as s:
1078
1091
ifreq = fcntl.ioctl(s, SIOCGIFINDEX,
1079
struct.pack("16s16x", interface))
1080
interface_index = struct.unpack("I", ifreq[16:20])[0]
1092
struct.pack(str(u"16s16x"),
1094
interface_index = struct.unpack(str(u"I"),
1081
1096
return interface_index
1082
1097
return if_nametoindex(interface)
1112
1127
# Parsing of options, both command line and config file
1114
1129
parser = optparse.OptionParser(version = "%%prog %s" % version)
1115
parser.add_option("-i", "--interface", type="string",
1116
metavar="IF", help="Bind to interface IF")
1117
parser.add_option("-a", "--address", type="string",
1118
help="Address to listen for requests on")
1119
parser.add_option("-p", "--port", type="int",
1120
help="Port number to receive requests on")
1121
parser.add_option("--check", action="store_true",
1122
help="Run self-test")
1123
parser.add_option("--debug", action="store_true",
1124
help="Debug mode; run in foreground and log to"
1126
parser.add_option("--priority", type="string", help="GnuTLS"
1127
" priority string (see GnuTLS documentation)")
1128
parser.add_option("--servicename", type="string", metavar="NAME",
1129
help="Zeroconf service name")
1130
parser.add_option("--configdir", type="string",
1131
default="/etc/mandos", metavar="DIR",
1132
help="Directory to search for configuration"
1134
parser.add_option("--no-dbus", action="store_false",
1136
help="Do not provide D-Bus system bus"
1138
parser.add_option("--no-ipv6", action="store_false",
1139
dest="use_ipv6", help="Do not use IPv6")
1130
parser.add_option("-i", u"--interface", type=u"string",
1131
metavar="IF", help=u"Bind to interface IF")
1132
parser.add_option("-a", u"--address", type=u"string",
1133
help=u"Address to listen for requests on")
1134
parser.add_option("-p", u"--port", type=u"int",
1135
help=u"Port number to receive requests on")
1136
parser.add_option("--check", action=u"store_true",
1137
help=u"Run self-test")
1138
parser.add_option("--debug", action=u"store_true",
1139
help=u"Debug mode; run in foreground and log to"
1141
parser.add_option("--priority", type=u"string", help=u"GnuTLS"
1142
u" priority string (see GnuTLS documentation)")
1143
parser.add_option("--servicename", type=u"string",
1144
metavar=u"NAME", help=u"Zeroconf service name")
1145
parser.add_option("--configdir", type=u"string",
1146
default=u"/etc/mandos", metavar=u"DIR",
1147
help=u"Directory to search for configuration"
1149
parser.add_option("--no-dbus", action=u"store_false",
1150
dest=u"use_dbus", help=u"Do not provide D-Bus"
1151
u" system bus interface")
1152
parser.add_option("--no-ipv6", action=u"store_false",
1153
dest=u"use_ipv6", help=u"Do not use IPv6")
1140
1154
options = parser.parse_args()[0]
1142
1156
if options.check:
1147
1161
# Default values for config file for server-global settings
1148
server_defaults = { "interface": "",
1153
"SECURE256:!CTYPE-X.509:+CTYPE-OPENPGP",
1154
"servicename": "Mandos",
1162
server_defaults = { u"interface": u"",
1167
u"SECURE256:!CTYPE-X.509:+CTYPE-OPENPGP",
1168
u"servicename": u"Mandos",
1169
u"use_dbus": u"True",
1170
u"use_ipv6": u"True",
1159
1173
# Parse config file for server-global settings
1160
1174
server_config = ConfigParser.SafeConfigParser(server_defaults)
1161
1175
del server_defaults
1162
server_config.read(os.path.join(options.configdir, "mandos.conf"))
1176
server_config.read(os.path.join(options.configdir,
1163
1178
# Convert the SafeConfigParser object to a dict
1164
1179
server_settings = server_config.defaults()
1165
1180
# Use the appropriate methods on the non-string config options
1166
server_settings["debug"] = server_config.getboolean("DEFAULT",
1168
server_settings["use_dbus"] = server_config.getboolean("DEFAULT",
1170
server_settings["use_ipv6"] = server_config.getboolean("DEFAULT",
1181
for option in (u"debug", u"use_dbus", u"use_ipv6"):
1182
server_settings[option] = server_config.getboolean(u"DEFAULT",
1172
1184
if server_settings["port"]:
1173
server_settings["port"] = server_config.getint("DEFAULT",
1185
server_settings["port"] = server_config.getint(u"DEFAULT",
1175
1187
del server_config
1177
1189
# Override the settings from the config file with command line
1178
1190
# options, if set.
1179
for option in ("interface", "address", "port", "debug",
1180
"priority", "servicename", "configdir",
1181
"use_dbus", "use_ipv6"):
1191
for option in (u"interface", u"address", u"port", u"debug",
1192
u"priority", u"servicename", u"configdir",
1193
u"use_dbus", u"use_ipv6"):
1182
1194
value = getattr(options, option)
1183
1195
if value is not None:
1184
1196
server_settings[option] = value
1198
# Force all strings to be unicode
1199
for option in server_settings.keys():
1200
if type(server_settings[option]) is str:
1201
server_settings[option] = unicode(server_settings[option])
1186
1202
# Now we have our good server settings in "server_settings"
1188
1204
##################################################################
1190
1206
# For convenience
1191
debug = server_settings["debug"]
1192
use_dbus = server_settings["use_dbus"]
1193
use_ipv6 = server_settings["use_ipv6"]
1207
debug = server_settings[u"debug"]
1208
use_dbus = server_settings[u"use_dbus"]
1209
use_ipv6 = server_settings[u"use_ipv6"]
1196
1212
syslogger.setLevel(logging.WARNING)
1197
1213
console.setLevel(logging.WARNING)
1199
if server_settings["servicename"] != "Mandos":
1215
if server_settings[u"servicename"] != u"Mandos":
1200
1216
syslogger.setFormatter(logging.Formatter
1201
('Mandos (%s) [%%(process)d]:'
1202
' %%(levelname)s: %%(message)s'
1203
% server_settings["servicename"]))
1217
(u'Mandos (%s) [%%(process)d]:'
1218
u' %%(levelname)s: %%(message)s'
1219
% server_settings[u"servicename"]))
1205
1221
# Parse config file with clients
1206
client_defaults = { "timeout": "1h",
1208
"checker": "fping -q -- %%(host)s",
1222
client_defaults = { u"timeout": u"1h",
1224
u"checker": u"fping -q -- %%(host)s",
1211
1227
client_config = ConfigParser.SafeConfigParser(client_defaults)
1212
client_config.read(os.path.join(server_settings["configdir"],
1228
client_config.read(os.path.join(server_settings[u"configdir"],
1215
1231
global mandos_dbus_service
1216
1232
mandos_dbus_service = None
1218
1234
clients = Set()
1219
tcp_server = IPv6_TCPServer((server_settings["address"],
1220
server_settings["port"]),
1235
tcp_server = IPv6_TCPServer((server_settings[u"address"],
1236
server_settings[u"port"]),
1223
server_settings["interface"],
1239
server_settings[u"interface"],
1224
1240
use_ipv6=use_ipv6,
1225
1241
clients=clients,
1226
1242
gnutls_priority=
1227
server_settings["priority"],
1243
server_settings[u"priority"],
1228
1244
use_dbus=use_dbus)
1229
pidfilename = "/var/run/mandos.pid"
1245
pidfilename = u"/var/run/mandos.pid"
1231
pidfile = open(pidfilename, "w")
1247
pidfile = open(pidfilename, u"w")
1232
1248
except IOError:
1233
logger.error("Could not open file %r", pidfilename)
1249
logger.error(u"Could not open file %r", pidfilename)
1236
uid = pwd.getpwnam("_mandos").pw_uid
1237
gid = pwd.getpwnam("_mandos").pw_gid
1252
uid = pwd.getpwnam(u"_mandos").pw_uid
1253
gid = pwd.getpwnam(u"_mandos").pw_gid
1238
1254
except KeyError:
1240
uid = pwd.getpwnam("mandos").pw_uid
1241
gid = pwd.getpwnam("mandos").pw_gid
1256
uid = pwd.getpwnam(u"mandos").pw_uid
1257
gid = pwd.getpwnam(u"mandos").pw_gid
1242
1258
except KeyError:
1244
uid = pwd.getpwnam("nobody").pw_uid
1245
gid = pwd.getpwnam("nogroup").pw_gid
1260
uid = pwd.getpwnam(u"nobody").pw_uid
1261
gid = pwd.getpwnam(u"nobody").pw_gid
1246
1262
except KeyError:
1349
1365
class MandosDBusService(dbus.service.Object):
1350
1366
"""A D-Bus proxy object"""
1351
1367
def __init__(self):
1352
dbus.service.Object.__init__(self, bus, "/")
1368
dbus.service.Object.__init__(self, bus, u"/")
1353
1369
_interface = u"se.bsnet.fukt.Mandos"
1355
@dbus.service.signal(_interface, signature="oa{sv}")
1371
@dbus.service.signal(_interface, signature=u"oa{sv}")
1356
1372
def ClientAdded(self, objpath, properties):
1360
@dbus.service.signal(_interface, signature="s")
1376
@dbus.service.signal(_interface, signature=u"s")
1361
1377
def ClientNotFound(self, fingerprint):
1365
@dbus.service.signal(_interface, signature="os")
1381
@dbus.service.signal(_interface, signature=u"os")
1366
1382
def ClientRemoved(self, objpath, name):
1370
@dbus.service.method(_interface, out_signature="ao")
1386
@dbus.service.method(_interface, out_signature=u"ao")
1371
1387
def GetAllClients(self):
1373
1389
return dbus.Array(c.dbus_object_path for c in clients)
1375
@dbus.service.method(_interface, out_signature="a{oa{sv}}")
1391
@dbus.service.method(_interface,
1392
out_signature=u"a{oa{sv}}")
1376
1393
def GetAllClientsWithProperties(self):
1378
1395
return dbus.Dictionary(
1379
1396
((c.dbus_object_path, c.GetAllProperties())
1380
1397
for c in clients),
1398
signature=u"oa{sv}")
1383
@dbus.service.method(_interface, in_signature="o")
1400
@dbus.service.method(_interface, in_signature=u"o")
1384
1401
def RemoveClient(self, object_path):
1386
1403
for c in clients: