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