11
11
# "AvahiService" class, and some lines in "main".
13
13
# Everything else is
14
# Copyright © 2008-2012 Teddy Hogeborn
15
# Copyright © 2008-2012 Björn Påhlsson
14
# Copyright © 2008-2011 Teddy Hogeborn
15
# Copyright © 2008-2011 Björn Påhlsson
17
17
# This program is free software: you can redistribute it and/or modify
18
18
# it under the terms of the GNU General Public License as published by
111
110
return interface_index
114
def initlogger(debug, level=logging.WARNING):
113
def initlogger(level=logging.WARNING):
115
114
"""init logger and add loglevel"""
117
116
syslogger.setFormatter(logging.Formatter
120
119
logger.addHandler(syslogger)
123
console = logging.StreamHandler()
124
console.setFormatter(logging.Formatter('%(asctime)s %(name)s'
128
logger.addHandler(console)
121
console = logging.StreamHandler()
122
console.setFormatter(logging.Formatter('%(asctime)s %(name)s'
126
logger.addHandler(console)
129
127
logger.setLevel(level)
177
174
def encrypt(self, data, password):
178
175
self.gnupg.passphrase = self.password_encode(password)
179
with open(os.devnull, "w") as devnull:
176
with open(os.devnull) as devnull:
181
178
proc = self.gnupg.run(['--symmetric'],
182
179
create_fhs=['stdin', 'stdout'],
194
191
def decrypt(self, data, password):
195
192
self.gnupg.passphrase = self.password_encode(password)
196
with open(os.devnull, "w") as devnull:
193
with open(os.devnull) as devnull:
198
195
proc = self.gnupg.run(['--decrypt'],
199
196
create_fhs=['stdin', 'stdout'],
200
197
attach_fhs={'stderr': devnull})
201
with contextlib.closing(proc.handles['stdin']) as f:
198
with contextlib.closing(proc.handles['stdin'] ) as f:
203
200
with contextlib.closing(proc.handles['stdout']) as f:
204
201
decrypted_plaintext = f.read()
416
413
last_checked_ok: datetime.datetime(); (UTC) or None
417
414
last_checker_status: integer between 0 and 255 reflecting exit
418
415
status of last checker. -1 reflects crashed
419
checker, -2 means no checker completed yet.
420
417
last_enabled: datetime.datetime(); (UTC) or None
421
418
name: string; from the config file, used in log messages and
422
419
D-Bus identifiers
423
420
secret: bytestring; sent verbatim (over TLS) to client
424
421
timeout: datetime.timedelta(); How long from last_checked_ok
425
422
until this client is disabled
426
extended_timeout: extra long timeout when secret has been sent
423
extended_timeout: extra long timeout when password has been sent
427
424
runtime_expansions: Allowed attributes for runtime expansion.
428
425
expires: datetime.datetime(); time (UTC) when a client will be
429
426
disabled, or None
463
460
def config_parser(config):
464
"""Construct a new dict of client settings of this form:
461
""" Construct a new dict of client settings of this form:
465
462
{ client_name: {setting_name: value, ...}, ...}
466
with exceptions for any special settings as defined above.
467
NOTE: Must be a pure function. Must return the same result
468
value given the same arguments.
463
with exceptions for any special settings as defined above"""
471
465
for client_name in config.sections():
472
466
section = dict(config.items(client_name))
476
470
# Reformat values from string types to Python types
477
471
client["approved_by_default"] = config.getboolean(
478
472
client_name, "approved_by_default")
479
client["enabled"] = config.getboolean(client_name,
473
client["enabled"] = config.getboolean(client_name, "enabled")
482
475
client["fingerprint"] = (section["fingerprint"].upper()
483
476
.replace(" ", ""))
502
495
client["checker_command"] = section["checker"]
503
496
client["last_approval_request"] = None
504
497
client["last_checked_ok"] = None
505
client["last_checker_status"] = -2
498
client["last_checker_status"] = None
499
if client["enabled"]:
500
client["last_enabled"] = datetime.datetime.utcnow()
501
client["expires"] = (datetime.datetime.utcnow()
504
client["last_enabled"] = None
505
client["expires"] = None
516
516
for setting, value in settings.iteritems():
517
517
setattr(self, setting, value)
520
if not hasattr(self, "last_enabled"):
521
self.last_enabled = datetime.datetime.utcnow()
522
if not hasattr(self, "expires"):
523
self.expires = (datetime.datetime.utcnow()
526
self.last_enabled = None
529
519
logger.debug("Creating client %r", self.name)
530
520
# Uppercase and remove spaces from fingerprint for later
531
521
# comparison purposes with return value from the fingerprint()
533
523
logger.debug(" Fingerprint: %s", self.fingerprint)
534
self.created = settings.get("created",
535
datetime.datetime.utcnow())
524
self.created = settings.get("created", datetime.datetime.utcnow())
537
526
# attributes specific for this server instance
538
527
self.checker = None
627
616
logger.warning("Checker for %(name)s crashed?",
630
def checked_ok(self):
631
"""Assert that the client has been seen, alive and well."""
632
self.last_checked_ok = datetime.datetime.utcnow()
633
self.last_checker_status = 0
636
def bump_timeout(self, timeout=None):
637
"""Bump up the timeout for this client."""
619
def checked_ok(self, timeout=None):
620
"""Bump up the timeout for this client.
622
This should only be called when the client has been seen,
638
625
if timeout is None:
639
626
timeout = self.timeout
627
self.last_checked_ok = datetime.datetime.utcnow()
640
628
if self.disable_initiator_tag is not None:
641
629
gobject.source_remove(self.disable_initiator_tag)
642
630
if getattr(self, "enabled", False):
733
721
logger.debug("Stopping checker for %(name)s", vars(self))
735
self.checker.terminate()
723
os.kill(self.checker.pid, signal.SIGTERM)
737
725
#if self.checker.poll() is None:
738
# self.checker.kill()
726
# os.kill(self.checker.pid, signal.SIGKILL)
739
727
except OSError as error:
740
728
if error.errno != errno.ESRCH: # No such process
775
def dbus_interface_annotations(dbus_interface):
776
"""Decorator for marking functions returning interface annotations.
780
@dbus_interface_annotations("org.example.Interface")
781
def _foo(self): # Function name does not matter
782
return {"org.freedesktop.DBus.Deprecated": "true",
783
"org.freedesktop.DBus.Property.EmitsChangedSignal":
787
func._dbus_is_interface = True
788
func._dbus_interface = dbus_interface
789
func._dbus_name = dbus_interface
794
def dbus_annotations(annotations):
795
"""Decorator to annotate D-Bus methods, signals or properties
798
@dbus_service_property("org.example.Interface", signature="b",
800
@dbus_annotations({{"org.freedesktop.DBus.Deprecated": "true",
801
"org.freedesktop.DBus.Property."
802
"EmitsChangedSignal": "false"})
803
def Property_dbus_property(self):
804
return dbus.Boolean(False)
807
func._dbus_annotations = annotations
812
763
class DBusPropertyException(dbus.exceptions.DBusException):
813
764
"""A base class for D-Bus property-related exceptions
840
def _is_dbus_thing(thing):
841
"""Returns a function testing if an attribute is a D-Bus thing
843
If called like _is_dbus_thing("method") it returns a function
844
suitable for use as predicate to inspect.getmembers().
846
return lambda obj: getattr(obj, "_dbus_is_{0}".format(thing),
791
def _is_dbus_property(obj):
792
return getattr(obj, "_dbus_is_property", False)
849
def _get_all_dbus_things(self, thing):
794
def _get_all_dbus_properties(self):
850
795
"""Returns a generator of (name, attribute) pairs
852
return ((getattr(athing.__get__(self), "_dbus_name",
854
athing.__get__(self))
797
return ((prop.__get__(self)._dbus_name, prop.__get__(self))
855
798
for cls in self.__class__.__mro__
857
inspect.getmembers(cls,
858
self._is_dbus_thing(thing)))
800
inspect.getmembers(cls, self._is_dbus_property))
860
802
def _get_dbus_property(self, interface_name, property_name):
861
803
"""Returns a bound method if one exists which is a D-Bus
864
806
for cls in self.__class__.__mro__:
865
807
for name, value in (inspect.getmembers
867
self._is_dbus_thing("property"))):
808
(cls, self._is_dbus_property)):
868
809
if (value._dbus_name == property_name
869
810
and value._dbus_interface == interface_name):
870
811
return value.__get__(self)
899
840
# signatures other than "ay".
900
841
if prop._dbus_signature != "ay":
902
value = dbus.ByteArray(b''.join(chr(byte)
843
value = dbus.ByteArray(''.join(unichr(byte)
906
847
@dbus.service.method(dbus.PROPERTIES_IFACE, in_signature="s",
912
853
Note: Will not include properties with access="write".
915
for name, prop in self._get_all_dbus_things("property"):
856
for name, prop in self._get_all_dbus_properties():
916
857
if (interface_name
917
858
and interface_name != prop._dbus_interface):
918
859
# Interface non-empty but did not match
933
874
path_keyword='object_path',
934
875
connection_keyword='connection')
935
876
def Introspect(self, object_path, connection):
936
"""Overloading of standard D-Bus method.
938
Inserts property tags and interface annotation tags.
877
"""Standard D-Bus method, overloaded to insert property tags.
940
879
xmlstring = dbus.service.Object.Introspect(self, object_path,
948
887
e.setAttribute("access", prop._dbus_access)
950
889
for if_tag in document.getElementsByTagName("interface"):
952
890
for tag in (make_tag(document, name, prop)
954
in self._get_all_dbus_things("property")
892
in self._get_all_dbus_properties()
955
893
if prop._dbus_interface
956
894
== if_tag.getAttribute("name")):
957
895
if_tag.appendChild(tag)
958
# Add annotation tags
959
for typ in ("method", "signal", "property"):
960
for tag in if_tag.getElementsByTagName(typ):
962
for name, prop in (self.
963
_get_all_dbus_things(typ)):
964
if (name == tag.getAttribute("name")
965
and prop._dbus_interface
966
== if_tag.getAttribute("name")):
967
annots.update(getattr
971
for name, value in annots.iteritems():
972
ann_tag = document.createElement(
974
ann_tag.setAttribute("name", name)
975
ann_tag.setAttribute("value", value)
976
tag.appendChild(ann_tag)
977
# Add interface annotation tags
978
for annotation, value in dict(
980
*(annotations().iteritems()
981
for name, annotations in
982
self._get_all_dbus_things("interface")
983
if name == if_tag.getAttribute("name")
985
ann_tag = document.createElement("annotation")
986
ann_tag.setAttribute("name", annotation)
987
ann_tag.setAttribute("value", value)
988
if_tag.appendChild(ann_tag)
989
896
# Add the names to the return values for the
990
897
# "org.freedesktop.DBus.Properties" methods
991
898
if (if_tag.getAttribute("name")
1026
933
def __new__(mcs, name, bases, attr):
1027
934
# Go through all the base classes which could have D-Bus
1028
935
# methods, signals, or properties in them
1029
old_interface_names = []
1030
936
for base in (b for b in bases
1031
937
if issubclass(b, dbus.service.Object)):
1032
938
# Go though all attributes of the base class
1042
948
alt_interface = (attribute._dbus_interface
1043
949
.replace("se.recompile.Mandos",
1044
950
"se.bsnet.fukt.Mandos"))
1045
if alt_interface != attribute._dbus_interface:
1046
old_interface_names.append(alt_interface)
1047
951
# Is this a D-Bus signal?
1048
952
if getattr(attribute, "_dbus_is_signal", False):
1049
953
# Extract the original non-method function by
1064
968
nonmethod_func.func_name,
1065
969
nonmethod_func.func_defaults,
1066
970
nonmethod_func.func_closure)))
1067
# Copy annotations, if any
1069
new_function._dbus_annotations = (
1070
dict(attribute._dbus_annotations))
1071
except AttributeError:
1073
971
# Define a creator of a function to call both the
1074
972
# old and new functions, so both the old and new
1075
973
# signals gets sent when the function is called
1103
1001
attribute.func_name,
1104
1002
attribute.func_defaults,
1105
1003
attribute.func_closure)))
1106
# Copy annotations, if any
1108
attr[attrname]._dbus_annotations = (
1109
dict(attribute._dbus_annotations))
1110
except AttributeError:
1112
1004
# Is this a D-Bus property?
1113
1005
elif getattr(attribute, "_dbus_is_property", False):
1114
1006
# Create a new, but exactly alike, function
1128
1020
attribute.func_name,
1129
1021
attribute.func_defaults,
1130
1022
attribute.func_closure)))
1131
# Copy annotations, if any
1133
attr[attrname]._dbus_annotations = (
1134
dict(attribute._dbus_annotations))
1135
except AttributeError:
1137
# Is this a D-Bus interface?
1138
elif getattr(attribute, "_dbus_is_interface", False):
1139
# Create a new, but exactly alike, function
1140
# object. Decorate it to be a new D-Bus interface
1141
# with the alternate D-Bus interface name. Add it
1143
attr[attrname] = (dbus_interface_annotations
1146
(attribute.func_code,
1147
attribute.func_globals,
1148
attribute.func_name,
1149
attribute.func_defaults,
1150
attribute.func_closure)))
1151
# Deprecate all old interfaces
1152
basename="_AlternateDBusNamesMetaclass_interface_annotation{0}"
1153
for old_interface_name in old_interface_names:
1154
@dbus_interface_annotations(old_interface_name)
1156
return { "org.freedesktop.DBus.Deprecated": "true" }
1157
# Find an unused name
1158
for aname in (basename.format(i) for i in
1160
if aname not in attr:
1163
1023
return type.__new__(mcs, name, bases, attr)
1179
1039
def __init__(self, bus = None, *args, **kwargs):
1181
1041
Client.__init__(self, *args, **kwargs)
1042
self._approvals_pending = 0
1044
self._approvals_pending = 0
1182
1045
# Only now, when this client is initialized, can it show up on
1184
1047
client_object_name = unicode(self.name).translate(
1230
1093
checker is not None)
1231
1094
last_checked_ok = notifychangeproperty(datetime_to_dbus,
1232
1095
"LastCheckedOK")
1233
last_checker_status = notifychangeproperty(dbus.Int16,
1234
"LastCheckerStatus")
1235
1096
last_approval_request = notifychangeproperty(
1236
1097
datetime_to_dbus, "LastApprovalRequest")
1237
1098
approved_by_default = notifychangeproperty(dbus.Boolean,
1315
1176
## D-Bus methods, signals & properties
1316
1177
_interface = "se.recompile.Mandos.Client"
1320
@dbus_interface_annotations(_interface)
1322
return { "org.freedesktop.DBus.Property.EmitsChangedSignal":
1327
1181
# CheckerCompleted - signal
1364
1218
return self.need_approval()
1220
# NeRwequest - signal
1221
@dbus.service.signal(_interface, signature="s")
1222
def NewRequest(self, ip):
1224
Is sent after a client request a password.
1368
1230
# Approve - method
1479
1341
return datetime_to_dbus(self.last_checked_ok)
1481
# LastCheckerStatus - property
1482
@dbus_service_property(_interface, signature="n",
1484
def LastCheckerStatus_dbus_property(self):
1485
return dbus.Int16(self.last_checker_status)
1487
1343
# Expires - property
1488
1344
@dbus_service_property(_interface, signature="s", access="read")
1489
1345
def Expires_dbus_property(self):
1501
1357
if value is None: # get
1502
1358
return dbus.UInt64(self.timeout_milliseconds())
1503
1359
self.timeout = datetime.timedelta(0, 0, 0, value)
1360
if getattr(self, "disable_initiator_tag", None) is None:
1504
1362
# Reschedule timeout
1506
now = datetime.datetime.utcnow()
1507
time_to_die = timedelta_to_milliseconds(
1508
(self.last_checked_ok + self.timeout) - now)
1509
if time_to_die <= 0:
1510
# The timeout has passed
1513
self.expires = (now +
1514
datetime.timedelta(milliseconds =
1516
if (getattr(self, "disable_initiator_tag", None)
1519
gobject.source_remove(self.disable_initiator_tag)
1520
self.disable_initiator_tag = (gobject.timeout_add
1363
gobject.source_remove(self.disable_initiator_tag)
1364
self.disable_initiator_tag = None
1366
time_to_die = timedelta_to_milliseconds((self
1371
if time_to_die <= 0:
1372
# The timeout has passed
1375
self.expires = (datetime.datetime.utcnow()
1376
+ datetime.timedelta(milliseconds =
1378
self.disable_initiator_tag = (gobject.timeout_add
1379
(time_to_die, self.disable))
1524
1381
# ExtendedTimeout - property
1525
1382
@dbus_service_property(_interface, signature="t",
1751
1612
logger.info("Sending secret to %s", client.name)
1752
1613
# bump the timeout using extended_timeout
1753
client.bump_timeout(client.extended_timeout)
1614
client.checked_ok(client.extended_timeout)
1754
1615
if self.server.use_dbus:
1755
1616
# Emit D-Bus signal
1756
1617
client.GotSecret()
2100
1961
if not noclose:
2101
1962
# Close all standard open file descriptors
2102
null = os.open(os.devnull, os.O_NOCTTY | os.O_RDWR)
1963
null = os.open(os.path.devnull, os.O_NOCTTY | os.O_RDWR)
2103
1964
if not stat.S_ISCHR(os.fstat(null).st_mode):
2104
1965
raise OSError(errno.ENODEV,
2105
1966
"%s not a character device"
2107
1968
os.dup2(null, sys.stdin.fileno())
2108
1969
os.dup2(null, sys.stdout.fileno())
2109
1970
os.dup2(null, sys.stderr.fileno())
2217
2078
stored_state_file)
2220
initlogger(debug, logging.DEBUG)
2081
initlogger(logging.DEBUG)
2222
2083
if not debuglevel:
2225
2086
level = getattr(logging, debuglevel.upper())
2226
initlogger(debug, level)
2228
2089
if server_settings["servicename"] != "Mandos":
2229
2090
syslogger.setFormatter(logging.Formatter
2232
2093
% server_settings["servicename"]))
2234
2095
# Parse config file with clients
2235
client_config = configparser.SafeConfigParser(Client
2096
client_config = configparser.SafeConfigParser(Client.client_defaults)
2237
2097
client_config.read(os.path.join(server_settings["configdir"],
2238
2098
"clients.conf"))
2292
2152
.gnutls_global_set_log_function(debug_gnutls))
2294
2154
# Redirect stdin so all checkers get /dev/null
2295
null = os.open(os.devnull, os.O_NOCTTY | os.O_RDWR)
2155
null = os.open(os.path.devnull, os.O_NOCTTY | os.O_RDWR)
2296
2156
os.dup2(null, sys.stdin.fileno())
2160
# No console logging
2161
logger.removeHandler(console)
2300
2163
# Need to fork before connecting to D-Bus
2302
2165
# Close all input and output, do double fork, etc.
2305
gobject.threads_init()
2307
2168
global main_loop
2308
2169
# From the Avahi example code
2309
DBusGMainLoop(set_as_default=True)
2170
DBusGMainLoop(set_as_default=True )
2310
2171
main_loop = gobject.MainLoop()
2311
2172
bus = dbus.SystemBus()
2312
2173
# End of Avahi example code
2356
2217
if e.errno != errno.ENOENT:
2358
except EOFError as e:
2359
logger.warning("Could not load persistent state: "
2360
"EOFError: {0}".format(e))
2362
2220
with PGPEngine() as pgp:
2363
2221
for client_name, client in clients_data.iteritems():
2381
2239
# Clients who has passed its expire date can still be
2382
2240
# enabled if its last checker was successful. Clients
2383
# whose checker succeeded before we stored its state is
2384
# assumed to have successfully run all checkers during
2241
# whose checker failed before we stored its state is
2242
# assumed to have failed all checkers during downtime.
2386
2243
if client["enabled"]:
2387
2244
if datetime.datetime.utcnow() >= client["expires"]:
2388
2245
if not client["last_checked_ok"]:
2389
2246
logger.warning(
2390
2247
"disabling client {0} - Client never "
2391
"performed a successful checker"
2392
.format(client_name))
2248
"performed a successfull checker"
2249
.format(client["name"]))
2393
2250
client["enabled"] = False
2394
2251
elif client["last_checker_status"] != 0:
2395
2252
logger.warning(
2396
2253
"disabling client {0} - Client "
2397
2254
"last checker failed with error code {1}"
2398
.format(client_name,
2255
.format(client["name"],
2399
2256
client["last_checker_status"]))
2400
2257
client["enabled"] = False
2402
2259
client["expires"] = (datetime.datetime
2404
2261
+ client["timeout"])
2405
logger.debug("Last checker succeeded,"
2406
" keeping {0} enabled"
2407
.format(client_name))
2409
2264
client["secret"] = (
2410
2265
pgp.decrypt(client["encrypted_secret"],
2421
2276
# Add/remove clients based on new changes made to config
2422
for client_name in (set(old_client_settings)
2423
- set(client_settings)):
2277
for client_name in set(old_client_settings) - set(client_settings):
2424
2278
del clients_data[client_name]
2425
for client_name in (set(client_settings)
2426
- set(old_client_settings)):
2279
for client_name in set(client_settings) - set(old_client_settings):
2427
2280
clients_data[client_name] = client_settings[client_name]
2429
# Create all client objects
2282
# Create clients all clients
2430
2283
for client_name, client in clients_data.iteritems():
2431
2284
tcp_server.clients[client_name] = client_class(
2432
2285
name = client_name, settings = client)
2453
2306
signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit())
2456
class MandosDBusService(DBusObjectWithProperties):
2309
class MandosDBusService(dbus.service.Object):
2457
2310
"""A D-Bus proxy object"""
2458
2311
def __init__(self):
2459
2312
dbus.service.Object.__init__(self, bus, "/")
2460
2313
_interface = "se.recompile.Mandos"
2462
@dbus_interface_annotations(_interface)
2464
return { "org.freedesktop.DBus.Property"
2465
".EmitsChangedSignal":
2468
2315
@dbus.service.signal(_interface, signature="o")
2469
2316
def ClientAdded(self, objpath):
2553
2400
del client_settings[client.name]["secret"]
2556
tempfd, tempname = tempfile.mkstemp(suffix=".pickle",
2559
(stored_state_path))
2560
with os.fdopen(tempfd, "wb") as stored_state:
2403
with os.fdopen(os.open(stored_state_path,
2404
os.O_CREAT|os.O_WRONLY|os.O_TRUNC,
2405
0600), "wb") as stored_state:
2561
2406
pickle.dump((clients, client_settings), stored_state)
2562
os.rename(tempname, stored_state_path)
2563
2407
except (IOError, OSError) as e:
2564
2408
logger.warning("Could not save persistent state: {0}"
2571
if e.errno not in set((errno.ENOENT, errno.EACCES,
2410
if e.errno not in (errno.ENOENT, errno.EACCES):
2575
2413
# Delete all clients, and settings from config
2576
2414
while tcp_server.clients: