153
150
self.group = None # our entry group
154
151
self.server = None
156
self.entry_group_state_changed_match = None
157
153
def rename(self):
158
154
"""Derived from the Avahi example code"""
159
155
if self.rename_count >= self.max_renames:
160
logger.critical("No suitable Zeroconf service name found"
161
" after %i retries, exiting.",
156
logger.critical(u"No suitable Zeroconf service name found"
157
u" after %i retries, exiting.",
162
158
self.rename_count)
163
raise AvahiServiceError("Too many renames")
164
self.name = unicode(self.server
165
.GetAlternativeServiceName(self.name))
166
logger.info("Changing Zeroconf service name to %r ...",
159
raise AvahiServiceError(u"Too many renames")
160
self.name = unicode(self.server.GetAlternativeServiceName(self.name))
161
logger.info(u"Changing Zeroconf service name to %r ...",
163
syslogger.setFormatter(logging.Formatter
164
(u'Mandos (%s) [%%(process)d]:'
165
u' %%(levelname)s: %%(message)s'
171
except dbus.exceptions.DBusException as error:
172
logger.critical("DBusException: %s", error)
170
except dbus.exceptions.DBusException, error:
171
logger.critical(u"DBusException: %s", error)
175
174
self.rename_count += 1
176
175
def remove(self):
177
176
"""Derived from the Avahi example code"""
178
if self.entry_group_state_changed_match is not None:
179
self.entry_group_state_changed_match.remove()
180
self.entry_group_state_changed_match = None
181
177
if self.group is not None:
182
178
self.group.Reset()
184
180
"""Derived from the Avahi example code"""
186
181
if self.group is None:
187
182
self.group = dbus.Interface(
188
183
self.bus.get_object(avahi.DBUS_NAME,
189
184
self.server.EntryGroupNew()),
190
185
avahi.DBUS_INTERFACE_ENTRY_GROUP)
191
self.entry_group_state_changed_match = (
192
self.group.connect_to_signal(
193
'StateChanged', self.entry_group_state_changed))
194
logger.debug("Adding Zeroconf service '%s' of type '%s' ...",
186
self.group.connect_to_signal('StateChanged',
188
.entry_group_state_changed)
189
logger.debug(u"Adding Zeroconf service '%s' of type '%s' ...",
195
190
self.name, self.type)
196
191
self.group.AddService(
204
199
self.group.Commit()
205
200
def entry_group_state_changed(self, state, error):
206
201
"""Derived from the Avahi example code"""
207
logger.debug("Avahi entry group state change: %i", state)
202
logger.debug(u"Avahi entry group state change: %i", state)
209
204
if state == avahi.ENTRY_GROUP_ESTABLISHED:
210
logger.debug("Zeroconf service established.")
205
logger.debug(u"Zeroconf service established.")
211
206
elif state == avahi.ENTRY_GROUP_COLLISION:
212
logger.info("Zeroconf service name collision.")
207
logger.warning(u"Zeroconf service name collision.")
214
209
elif state == avahi.ENTRY_GROUP_FAILURE:
215
logger.critical("Avahi: Error in group state changed %s",
210
logger.critical(u"Avahi: Error in group state changed %s",
217
raise AvahiGroupError("State changed: %s"
212
raise AvahiGroupError(u"State changed: %s"
218
213
% unicode(error))
219
214
def cleanup(self):
220
215
"""Derived from the Avahi example code"""
221
216
if self.group is not None:
224
except (dbus.exceptions.UnknownMethodException,
225
dbus.exceptions.DBusException) as e:
227
218
self.group = None
229
def server_state_changed(self, state, error=None):
219
def server_state_changed(self, state):
230
220
"""Derived from the Avahi example code"""
231
logger.debug("Avahi server state change: %i", state)
232
bad_states = { avahi.SERVER_INVALID:
233
"Zeroconf server invalid",
234
avahi.SERVER_REGISTERING: None,
235
avahi.SERVER_COLLISION:
236
"Zeroconf server name collision",
237
avahi.SERVER_FAILURE:
238
"Zeroconf server failure" }
239
if state in bad_states:
240
if bad_states[state] is not None:
242
logger.error(bad_states[state])
244
logger.error(bad_states[state] + ": %r", error)
221
logger.debug(u"Avahi server state change: %i", state)
222
if state == avahi.SERVER_COLLISION:
223
logger.error(u"Zeroconf server name collision")
246
225
elif state == avahi.SERVER_RUNNING:
250
logger.debug("Unknown state: %r", state)
252
logger.debug("Unknown state: %r: %r", state, error)
253
227
def activate(self):
254
228
"""Derived from the Avahi example code"""
255
229
if self.server is None:
256
230
self.server = dbus.Interface(
257
231
self.bus.get_object(avahi.DBUS_NAME,
258
avahi.DBUS_PATH_SERVER,
259
follow_name_owner_changes=True),
232
avahi.DBUS_PATH_SERVER),
260
233
avahi.DBUS_INTERFACE_SERVER)
261
self.server.connect_to_signal("StateChanged",
234
self.server.connect_to_signal(u"StateChanged",
262
235
self.server_state_changed)
263
236
self.server_state_changed(self.server.GetState())
265
class AvahiServiceToSyslog(AvahiService):
267
"""Add the new name to the syslog messages"""
268
ret = AvahiService.rename(self)
269
syslogger.setFormatter(logging.Formatter
270
('Mandos (%s) [%%(process)d]:'
271
' %%(levelname)s: %%(message)s'
275
def _timedelta_to_milliseconds(td):
276
"Convert a datetime.timedelta() to milliseconds"
277
return ((td.days * 24 * 60 * 60 * 1000)
278
+ (td.seconds * 1000)
279
+ (td.microseconds // 1000))
281
239
class Client(object):
282
240
"""A representation of a client host served by this server.
285
_approved: bool(); 'None' if not yet approved/disapproved
286
approval_delay: datetime.timedelta(); Time to wait for approval
287
approval_duration: datetime.timedelta(); Duration of one approval
243
name: string; from the config file, used in log messages and
245
fingerprint: string (40 or 32 hexadecimal digits); used to
246
uniquely identify the client
247
secret: bytestring; sent verbatim (over TLS) to client
248
host: string; available for use by the checker command
249
created: datetime.datetime(); (UTC) object creation
250
last_enabled: datetime.datetime(); (UTC)
252
last_checked_ok: datetime.datetime(); (UTC) or None
253
timeout: datetime.timedelta(); How long from last_checked_ok
254
until this client is disabled
255
interval: datetime.timedelta(); How often to start a new checker
256
disable_hook: If set, called by disable() as disable_hook(self)
288
257
checker: subprocess.Popen(); a running checker process used
289
258
to see if the client lives.
290
259
'None' if no process is running.
291
checker_callback_tag: a gobject event source tag, or None
292
checker_command: string; External command which is run to check
293
if client lives. %() expansions are done at
260
checker_initiator_tag: a gobject event source tag, or None
261
disable_initiator_tag: - '' -
262
checker_callback_tag: - '' -
263
checker_command: string; External command which is run to check if
264
client lives. %() expansions are done at
294
265
runtime with vars(self) as dict, so that for
295
266
instance %(name)s can be used in the command.
296
checker_initiator_tag: a gobject event source tag, or None
297
created: datetime.datetime(); (UTC) object creation
298
267
current_checker_command: string; current running checker_command
299
disable_hook: If set, called by disable() as disable_hook(self)
300
disable_initiator_tag: a gobject event source tag, or None
302
fingerprint: string (40 or 32 hexadecimal digits); used to
303
uniquely identify the client
304
host: string; available for use by the checker command
305
interval: datetime.timedelta(); How often to start a new checker
306
last_approval_request: datetime.datetime(); (UTC) or None
307
last_checked_ok: datetime.datetime(); (UTC) or None
308
last_enabled: datetime.datetime(); (UTC)
309
name: string; from the config file, used in log messages and
311
secret: bytestring; sent verbatim (over TLS) to client
312
timeout: datetime.timedelta(); How long from last_checked_ok
313
until this client is disabled
314
extended_timeout: extra long timeout when password has been sent
315
runtime_expansions: Allowed attributes for runtime expansion.
316
expires: datetime.datetime(); time (UTC) when a client will be
268
approved_delay: datetime.timedelta(); Time to wait for approval
269
_approved: bool(); 'None' if not yet approved/disapproved
270
approved_duration: datetime.timedelta(); Duration of one approval
320
runtime_expansions = ("approval_delay", "approval_duration",
321
"created", "enabled", "fingerprint",
322
"host", "interval", "last_checked_ok",
323
"last_enabled", "name", "timeout")
274
def _timedelta_to_milliseconds(td):
275
"Convert a datetime.timedelta() to milliseconds"
276
return ((td.days * 24 * 60 * 60 * 1000)
277
+ (td.seconds * 1000)
278
+ (td.microseconds // 1000))
325
280
def timeout_milliseconds(self):
326
281
"Return the 'timeout' attribute in milliseconds"
327
return _timedelta_to_milliseconds(self.timeout)
329
def extended_timeout_milliseconds(self):
330
"Return the 'extended_timeout' attribute in milliseconds"
331
return _timedelta_to_milliseconds(self.extended_timeout)
282
return self._timedelta_to_milliseconds(self.timeout)
333
284
def interval_milliseconds(self):
334
285
"Return the 'interval' attribute in milliseconds"
335
return _timedelta_to_milliseconds(self.interval)
337
def approval_delay_milliseconds(self):
338
return _timedelta_to_milliseconds(self.approval_delay)
286
return self._timedelta_to_milliseconds(self.interval)
288
def approved_delay_milliseconds(self):
289
return self._timedelta_to_milliseconds(self.approved_delay)
340
291
def __init__(self, name = None, disable_hook=None, config=None):
341
292
"""Note: the 'checker' key in 'config' sets the
345
296
if config is None:
347
logger.debug("Creating client %r", self.name)
298
logger.debug(u"Creating client %r", self.name)
348
299
# Uppercase and remove spaces from fingerprint for later
349
300
# comparison purposes with return value from the fingerprint()
351
self.fingerprint = (config["fingerprint"].upper()
353
logger.debug(" Fingerprint: %s", self.fingerprint)
354
if "secret" in config:
355
self.secret = config["secret"].decode("base64")
356
elif "secfile" in config:
302
self.fingerprint = (config[u"fingerprint"].upper()
304
logger.debug(u" Fingerprint: %s", self.fingerprint)
305
if u"secret" in config:
306
self.secret = config[u"secret"].decode(u"base64")
307
elif u"secfile" in config:
357
308
with open(os.path.expanduser(os.path.expandvars
358
(config["secfile"])),
309
(config[u"secfile"])),
359
310
"rb") as secfile:
360
311
self.secret = secfile.read()
362
raise TypeError("No secret or secfile for client %s"
313
raise TypeError(u"No secret or secfile for client %s"
364
self.host = config.get("host", "")
315
self.host = config.get(u"host", u"")
365
316
self.created = datetime.datetime.utcnow()
366
317
self.enabled = False
367
self.last_approval_request = None
368
318
self.last_enabled = None
369
319
self.last_checked_ok = None
370
self.timeout = string_to_delta(config["timeout"])
371
self.extended_timeout = string_to_delta(config
372
["extended_timeout"])
373
self.interval = string_to_delta(config["interval"])
320
self.timeout = string_to_delta(config[u"timeout"])
321
self.interval = string_to_delta(config[u"interval"])
374
322
self.disable_hook = disable_hook
375
323
self.checker = None
376
324
self.checker_initiator_tag = None
377
325
self.disable_initiator_tag = None
379
326
self.checker_callback_tag = None
380
self.checker_command = config["checker"]
327
self.checker_command = config[u"checker"]
381
328
self.current_checker_command = None
382
329
self.last_connect = None
383
330
self._approved = None
384
self.approved_by_default = config.get("approved_by_default",
331
self.approved_by_default = config.get(u"approved_by_default",
386
333
self.approvals_pending = 0
387
self.approval_delay = string_to_delta(
388
config["approval_delay"])
389
self.approval_duration = string_to_delta(
390
config["approval_duration"])
391
self.changedstate = (multiprocessing_manager
392
.Condition(multiprocessing_manager
334
self.approved_delay = string_to_delta(
335
config[u"approved_delay"])
336
self.approved_duration = string_to_delta(
337
config[u"approved_duration"])
338
self.changedstate = multiprocessing_manager.Condition(multiprocessing_manager.Lock())
395
340
def send_changedstate(self):
396
341
self.changedstate.acquire()
397
342
self.changedstate.notify_all()
398
343
self.changedstate.release()
400
345
def enable(self):
401
346
"""Start this client's checker and timeout hooks"""
402
if getattr(self, "enabled", False):
347
if getattr(self, u"enabled", False):
403
348
# Already enabled
405
350
self.send_changedstate()
351
self.last_enabled = datetime.datetime.utcnow()
406
352
# Schedule a new checker to be started an 'interval' from now,
407
353
# and every interval from then on.
408
354
self.checker_initiator_tag = (gobject.timeout_add
409
355
(self.interval_milliseconds(),
410
356
self.start_checker))
411
357
# Schedule a disable() when 'timeout' has passed
412
self.expires = datetime.datetime.utcnow() + self.timeout
413
358
self.disable_initiator_tag = (gobject.timeout_add
414
359
(self.timeout_milliseconds(),
416
361
self.enabled = True
417
self.last_enabled = datetime.datetime.utcnow()
418
362
# Also start a new checker *right now*.
419
363
self.start_checker()
451
394
if os.WIFEXITED(condition):
452
395
exitstatus = os.WEXITSTATUS(condition)
453
396
if exitstatus == 0:
454
logger.info("Checker for %(name)s succeeded",
397
logger.info(u"Checker for %(name)s succeeded",
456
399
self.checked_ok()
458
logger.info("Checker for %(name)s failed",
401
logger.info(u"Checker for %(name)s failed",
461
logger.warning("Checker for %(name)s crashed?",
404
logger.warning(u"Checker for %(name)s crashed?",
464
def checked_ok(self, timeout=None):
407
def checked_ok(self):
465
408
"""Bump up the timeout for this client.
467
410
This should only be called when the client has been seen,
471
timeout = self.timeout
472
413
self.last_checked_ok = datetime.datetime.utcnow()
473
if self.disable_initiator_tag is not None:
474
gobject.source_remove(self.disable_initiator_tag)
475
if getattr(self, "enabled", False):
476
self.disable_initiator_tag = (gobject.timeout_add
477
(_timedelta_to_milliseconds
478
(timeout), self.disable))
479
self.expires = datetime.datetime.utcnow() + timeout
481
def need_approval(self):
482
self.last_approval_request = datetime.datetime.utcnow()
414
gobject.source_remove(self.disable_initiator_tag)
415
self.disable_initiator_tag = (gobject.timeout_add
416
(self.timeout_milliseconds(),
484
419
def start_checker(self):
485
420
"""Start a new checker subprocess if one is not running.
636
568
def _is_dbus_property(obj):
637
return getattr(obj, "_dbus_is_property", False)
569
return getattr(obj, u"_dbus_is_property", False)
639
571
def _get_all_dbus_properties(self):
640
572
"""Returns a generator of (name, attribute) pairs
642
return ((prop.__get__(self)._dbus_name, prop.__get__(self))
643
for cls in self.__class__.__mro__
574
return ((prop._dbus_name, prop)
644
575
for name, prop in
645
inspect.getmembers(cls, self._is_dbus_property))
576
inspect.getmembers(self, self._is_dbus_property))
647
578
def _get_dbus_property(self, interface_name, property_name):
648
579
"""Returns a bound method if one exists which is a D-Bus
649
580
property with the specified name and interface.
651
for cls in self.__class__.__mro__:
652
for name, value in (inspect.getmembers
653
(cls, self._is_dbus_property)):
654
if (value._dbus_name == property_name
655
and value._dbus_interface == interface_name):
656
return value.__get__(self)
582
for name in (property_name,
583
property_name + u"_dbus_property"):
584
prop = getattr(self, name, None)
586
or not self._is_dbus_property(prop)
587
or prop._dbus_name != property_name
588
or (interface_name and prop._dbus_interface
589
and interface_name != prop._dbus_interface)):
658
592
# No such property
659
raise DBusPropertyNotFound(self.dbus_object_path + ":"
660
+ interface_name + "."
593
raise DBusPropertyNotFound(self.dbus_object_path + u":"
594
+ interface_name + u"."
663
@dbus.service.method(dbus.PROPERTIES_IFACE, in_signature="ss",
597
@dbus.service.method(dbus.PROPERTIES_IFACE, in_signature=u"ss",
665
599
def Get(self, interface_name, property_name):
666
600
"""Standard D-Bus property Get() method, see D-Bus standard.
668
602
prop = self._get_dbus_property(interface_name, property_name)
669
if prop._dbus_access == "write":
603
if prop._dbus_access == u"write":
670
604
raise DBusPropertyAccessException(property_name)
672
if not hasattr(value, "variant_level"):
606
if not hasattr(value, u"variant_level"):
674
608
return type(value)(value, variant_level=value.variant_level+1)
676
@dbus.service.method(dbus.PROPERTIES_IFACE, in_signature="ssv")
610
@dbus.service.method(dbus.PROPERTIES_IFACE, in_signature=u"ssv")
677
611
def Set(self, interface_name, property_name, value):
678
612
"""Standard D-Bus property Set() method, see D-Bus standard.
680
614
prop = self._get_dbus_property(interface_name, property_name)
681
if prop._dbus_access == "read":
615
if prop._dbus_access == u"read":
682
616
raise DBusPropertyAccessException(property_name)
683
if prop._dbus_get_args_options["byte_arrays"]:
617
if prop._dbus_get_args_options[u"byte_arrays"]:
684
618
# The byte_arrays option is not supported yet on
685
619
# signatures other than "ay".
686
if prop._dbus_signature != "ay":
620
if prop._dbus_signature != u"ay":
688
622
value = dbus.ByteArray(''.join(unichr(byte)
689
623
for byte in value))
692
@dbus.service.method(dbus.PROPERTIES_IFACE, in_signature="s",
693
out_signature="a{sv}")
626
@dbus.service.method(dbus.PROPERTIES_IFACE, in_signature=u"s",
627
out_signature=u"a{sv}")
694
628
def GetAll(self, interface_name):
695
629
"""Standard D-Bus property GetAll() method, see D-Bus
698
632
Note: Will not include properties with access="write".
727
661
document = xml.dom.minidom.parseString(xmlstring)
728
662
def make_tag(document, name, prop):
729
e = document.createElement("property")
730
e.setAttribute("name", name)
731
e.setAttribute("type", prop._dbus_signature)
732
e.setAttribute("access", prop._dbus_access)
663
e = document.createElement(u"property")
664
e.setAttribute(u"name", name)
665
e.setAttribute(u"type", prop._dbus_signature)
666
e.setAttribute(u"access", prop._dbus_access)
734
for if_tag in document.getElementsByTagName("interface"):
668
for if_tag in document.getElementsByTagName(u"interface"):
735
669
for tag in (make_tag(document, name, prop)
737
671
in self._get_all_dbus_properties()
738
672
if prop._dbus_interface
739
== if_tag.getAttribute("name")):
673
== if_tag.getAttribute(u"name")):
740
674
if_tag.appendChild(tag)
741
675
# Add the names to the return values for the
742
676
# "org.freedesktop.DBus.Properties" methods
743
if (if_tag.getAttribute("name")
744
== "org.freedesktop.DBus.Properties"):
745
for cn in if_tag.getElementsByTagName("method"):
746
if cn.getAttribute("name") == "Get":
747
for arg in cn.getElementsByTagName("arg"):
748
if (arg.getAttribute("direction")
750
arg.setAttribute("name", "value")
751
elif cn.getAttribute("name") == "GetAll":
752
for arg in cn.getElementsByTagName("arg"):
753
if (arg.getAttribute("direction")
755
arg.setAttribute("name", "props")
756
xmlstring = document.toxml("utf-8")
677
if (if_tag.getAttribute(u"name")
678
== u"org.freedesktop.DBus.Properties"):
679
for cn in if_tag.getElementsByTagName(u"method"):
680
if cn.getAttribute(u"name") == u"Get":
681
for arg in cn.getElementsByTagName(u"arg"):
682
if (arg.getAttribute(u"direction")
684
arg.setAttribute(u"name", u"value")
685
elif cn.getAttribute(u"name") == u"GetAll":
686
for arg in cn.getElementsByTagName(u"arg"):
687
if (arg.getAttribute(u"direction")
689
arg.setAttribute(u"name", u"props")
690
xmlstring = document.toxml(u"utf-8")
757
691
document.unlink()
758
692
except (AttributeError, xml.dom.DOMException,
759
xml.parsers.expat.ExpatError) as error:
760
logger.error("Failed to override Introspection method",
693
xml.parsers.expat.ExpatError), error:
694
logger.error(u"Failed to override Introspection method",
765
def datetime_to_dbus (dt, variant_level=0):
766
"""Convert a UTC datetime.datetime() to a D-Bus type."""
768
return dbus.String("", variant_level = variant_level)
769
return dbus.String(dt.isoformat(),
770
variant_level=variant_level)
772
class AlternateDBusNamesMetaclass(DBusObjectWithProperties
774
"""Applied to an empty subclass of a D-Bus object, this metaclass
775
will add additional D-Bus attributes matching a certain pattern.
777
def __new__(mcs, name, bases, attr):
778
# Go through all the base classes which could have D-Bus
779
# methods, signals, or properties in them
780
for base in (b for b in bases
781
if issubclass(b, dbus.service.Object)):
782
# Go though all attributes of the base class
783
for attrname, attribute in inspect.getmembers(base):
784
# Ignore non-D-Bus attributes, and D-Bus attributes
785
# with the wrong interface name
786
if (not hasattr(attribute, "_dbus_interface")
787
or not attribute._dbus_interface
788
.startswith("se.recompile.Mandos")):
790
# Create an alternate D-Bus interface name based on
792
alt_interface = (attribute._dbus_interface
793
.replace("se.recompile.Mandos",
794
"se.bsnet.fukt.Mandos"))
795
# Is this a D-Bus signal?
796
if getattr(attribute, "_dbus_is_signal", False):
797
# Extract the original non-method function by
799
nonmethod_func = (dict(
800
zip(attribute.func_code.co_freevars,
801
attribute.__closure__))["func"]
803
# Create a new, but exactly alike, function
804
# object, and decorate it to be a new D-Bus signal
805
# with the alternate D-Bus interface name
806
new_function = (dbus.service.signal
808
attribute._dbus_signature)
810
nonmethod_func.func_code,
811
nonmethod_func.func_globals,
812
nonmethod_func.func_name,
813
nonmethod_func.func_defaults,
814
nonmethod_func.func_closure)))
815
# Define a creator of a function to call both the
816
# old and new functions, so both the old and new
817
# signals gets sent when the function is called
818
def fixscope(func1, func2):
819
"""This function is a scope container to pass
820
func1 and func2 to the "call_both" function
821
outside of its arguments"""
822
def call_both(*args, **kwargs):
823
"""This function will emit two D-Bus
824
signals by calling func1 and func2"""
825
func1(*args, **kwargs)
826
func2(*args, **kwargs)
828
# Create the "call_both" function and add it to
830
attr[attrname] = fixscope(attribute,
832
# Is this a D-Bus method?
833
elif getattr(attribute, "_dbus_is_method", False):
834
# Create a new, but exactly alike, function
835
# object. Decorate it to be a new D-Bus method
836
# with the alternate D-Bus interface name. Add it
838
attr[attrname] = (dbus.service.method
840
attribute._dbus_in_signature,
841
attribute._dbus_out_signature)
843
(attribute.func_code,
844
attribute.func_globals,
846
attribute.func_defaults,
847
attribute.func_closure)))
848
# Is this a D-Bus property?
849
elif getattr(attribute, "_dbus_is_property", False):
850
# Create a new, but exactly alike, function
851
# object, and decorate it to be a new D-Bus
852
# property with the alternate D-Bus interface
853
# name. Add it to the class.
854
attr[attrname] = (dbus_service_property
856
attribute._dbus_signature,
857
attribute._dbus_access,
859
._dbus_get_args_options
862
(attribute.func_code,
863
attribute.func_globals,
865
attribute.func_defaults,
866
attribute.func_closure)))
867
return type.__new__(mcs, name, bases, attr)
869
699
class ClientDBus(Client, DBusObjectWithProperties):
870
700
"""A Client class using D-Bus
885
711
Client.__init__(self, *args, **kwargs)
886
712
# Only now, when this client is initialized, can it show up on
888
client_object_name = unicode(self.name).translate(
891
714
self.dbus_object_path = (dbus.ObjectPath
892
("/clients/" + client_object_name))
716
+ self.name.replace(u".", u"_")))
893
717
DBusObjectWithProperties.__init__(self, self.bus,
894
718
self.dbus_object_path)
896
def notifychangeproperty(transform_func,
897
dbus_name, type_func=lambda x: x,
899
""" Modify a variable so that it's a property which announces
902
transform_fun: Function that takes a value and a variant_level
903
and transforms it to a D-Bus type.
904
dbus_name: D-Bus name of the variable
905
type_func: Function that transform the value before sending it
906
to the D-Bus. Default: no transform
907
variant_level: D-Bus variant level. Default: 1
909
attrname = "_{0}".format(dbus_name)
910
def setter(self, value):
911
if hasattr(self, "dbus_object_path"):
912
if (not hasattr(self, attrname) or
913
type_func(getattr(self, attrname, None))
914
!= type_func(value)):
915
dbus_value = transform_func(type_func(value),
918
self.PropertyChanged(dbus.String(dbus_name),
920
setattr(self, attrname, value)
922
return property(lambda self: getattr(self, attrname), setter)
925
expires = notifychangeproperty(datetime_to_dbus, "Expires")
926
approvals_pending = notifychangeproperty(dbus.Boolean,
929
enabled = notifychangeproperty(dbus.Boolean, "Enabled")
930
last_enabled = notifychangeproperty(datetime_to_dbus,
932
checker = notifychangeproperty(dbus.Boolean, "CheckerRunning",
933
type_func = lambda checker:
935
last_checked_ok = notifychangeproperty(datetime_to_dbus,
937
last_approval_request = notifychangeproperty(
938
datetime_to_dbus, "LastApprovalRequest")
939
approved_by_default = notifychangeproperty(dbus.Boolean,
941
approval_delay = notifychangeproperty(dbus.UInt16,
944
_timedelta_to_milliseconds)
945
approval_duration = notifychangeproperty(
946
dbus.UInt16, "ApprovalDuration",
947
type_func = _timedelta_to_milliseconds)
948
host = notifychangeproperty(dbus.String, "Host")
949
timeout = notifychangeproperty(dbus.UInt16, "Timeout",
951
_timedelta_to_milliseconds)
952
extended_timeout = notifychangeproperty(
953
dbus.UInt16, "ExtendedTimeout",
954
type_func = _timedelta_to_milliseconds)
955
interval = notifychangeproperty(dbus.UInt16,
958
_timedelta_to_milliseconds)
959
checker_command = notifychangeproperty(dbus.String, "Checker")
961
del notifychangeproperty
720
def _get_approvals_pending(self):
721
return self._approvals_pending
722
def _set_approvals_pending(self, value):
723
old_value = self._approvals_pending
724
self._approvals_pending = value
726
if (hasattr(self, "dbus_object_path")
727
and bval is not bool(old_value)):
728
dbus_bool = dbus.Boolean(bval, variant_level=1)
729
self.PropertyChanged(dbus.String(u"approved_pending"),
732
approvals_pending = property(_get_approvals_pending,
733
_set_approvals_pending)
734
del _get_approvals_pending, _set_approvals_pending
737
def _datetime_to_dbus(dt, variant_level=0):
738
"""Convert a UTC datetime.datetime() to a D-Bus type."""
739
return dbus.String(dt.isoformat(),
740
variant_level=variant_level)
743
oldstate = getattr(self, u"enabled", False)
744
r = Client.enable(self)
745
if oldstate != self.enabled:
747
self.PropertyChanged(dbus.String(u"enabled"),
748
dbus.Boolean(True, variant_level=1))
749
self.PropertyChanged(
750
dbus.String(u"last_enabled"),
751
self._datetime_to_dbus(self.last_enabled,
755
def disable(self, quiet = False):
756
oldstate = getattr(self, u"enabled", False)
757
r = Client.disable(self, quiet=quiet)
758
if not quiet and oldstate != self.enabled:
760
self.PropertyChanged(dbus.String(u"enabled"),
761
dbus.Boolean(False, variant_level=1))
963
764
def __del__(self, *args, **kwargs):
965
766
self.remove_from_connection()
966
767
except LookupError:
968
if hasattr(DBusObjectWithProperties, "__del__"):
769
if hasattr(DBusObjectWithProperties, u"__del__"):
969
770
DBusObjectWithProperties.__del__(self, *args, **kwargs)
970
771
Client.__del__(self, *args, **kwargs)
1098
# ApprovalPending - property
1099
@dbus_service_property(_interface, signature="b", access="read")
1100
def ApprovalPending_dbus_property(self):
922
# approved_pending - property
923
@dbus_service_property(_interface, signature=u"b", access=u"read")
924
def approved_pending_dbus_property(self):
1101
925
return dbus.Boolean(bool(self.approvals_pending))
1103
# ApprovedByDefault - property
1104
@dbus_service_property(_interface, signature="b",
1106
def ApprovedByDefault_dbus_property(self, value=None):
1107
if value is None: # get
1108
return dbus.Boolean(self.approved_by_default)
1109
self.approved_by_default = bool(value)
1111
# ApprovalDelay - property
1112
@dbus_service_property(_interface, signature="t",
1114
def ApprovalDelay_dbus_property(self, value=None):
1115
if value is None: # get
1116
return dbus.UInt64(self.approval_delay_milliseconds())
1117
self.approval_delay = datetime.timedelta(0, 0, 0, value)
1119
# ApprovalDuration - property
1120
@dbus_service_property(_interface, signature="t",
1122
def ApprovalDuration_dbus_property(self, value=None):
1123
if value is None: # get
1124
return dbus.UInt64(_timedelta_to_milliseconds(
1125
self.approval_duration))
1126
self.approval_duration = datetime.timedelta(0, 0, 0, value)
1129
@dbus_service_property(_interface, signature="s", access="read")
1130
def Name_dbus_property(self):
927
# approved_by_default - property
928
@dbus_service_property(_interface, signature=u"b",
930
def approved_by_default_dbus_property(self):
931
return dbus.Boolean(self.approved_by_default)
933
# approved_delay - property
934
@dbus_service_property(_interface, signature=u"t",
936
def approved_delay_dbus_property(self):
937
return dbus.UInt64(self.approved_delay_milliseconds())
939
# approved_duration - property
940
@dbus_service_property(_interface, signature=u"t",
942
def approved_duration_dbus_property(self):
943
return dbus.UInt64(self._timedelta_to_milliseconds(
944
self.approved_duration))
947
@dbus_service_property(_interface, signature=u"s", access=u"read")
948
def name_dbus_property(self):
1131
949
return dbus.String(self.name)
1133
# Fingerprint - property
1134
@dbus_service_property(_interface, signature="s", access="read")
1135
def Fingerprint_dbus_property(self):
951
# fingerprint - property
952
@dbus_service_property(_interface, signature=u"s", access=u"read")
953
def fingerprint_dbus_property(self):
1136
954
return dbus.String(self.fingerprint)
1139
@dbus_service_property(_interface, signature="s",
1141
def Host_dbus_property(self, value=None):
957
@dbus_service_property(_interface, signature=u"s",
959
def host_dbus_property(self, value=None):
1142
960
if value is None: # get
1143
961
return dbus.String(self.host)
1144
962
self.host = value
1146
# Created - property
1147
@dbus_service_property(_interface, signature="s", access="read")
1148
def Created_dbus_property(self):
1149
return dbus.String(datetime_to_dbus(self.created))
1151
# LastEnabled - property
1152
@dbus_service_property(_interface, signature="s", access="read")
1153
def LastEnabled_dbus_property(self):
1154
return datetime_to_dbus(self.last_enabled)
1156
# Enabled - property
1157
@dbus_service_property(_interface, signature="b",
1159
def Enabled_dbus_property(self, value=None):
964
self.PropertyChanged(dbus.String(u"host"),
965
dbus.String(value, variant_level=1))
968
@dbus_service_property(_interface, signature=u"s", access=u"read")
969
def created_dbus_property(self):
970
return dbus.String(self._datetime_to_dbus(self.created))
972
# last_enabled - property
973
@dbus_service_property(_interface, signature=u"s", access=u"read")
974
def last_enabled_dbus_property(self):
975
if self.last_enabled is None:
976
return dbus.String(u"")
977
return dbus.String(self._datetime_to_dbus(self.last_enabled))
980
@dbus_service_property(_interface, signature=u"b",
982
def enabled_dbus_property(self, value=None):
1160
983
if value is None: # get
1161
984
return dbus.Boolean(self.enabled)
1167
# LastCheckedOK - property
1168
@dbus_service_property(_interface, signature="s",
1170
def LastCheckedOK_dbus_property(self, value=None):
990
# last_checked_ok - property
991
@dbus_service_property(_interface, signature=u"s",
993
def last_checked_ok_dbus_property(self, value=None):
1171
994
if value is not None:
1172
995
self.checked_ok()
1174
return datetime_to_dbus(self.last_checked_ok)
1176
# Expires - property
1177
@dbus_service_property(_interface, signature="s", access="read")
1178
def Expires_dbus_property(self):
1179
return datetime_to_dbus(self.expires)
1181
# LastApprovalRequest - property
1182
@dbus_service_property(_interface, signature="s", access="read")
1183
def LastApprovalRequest_dbus_property(self):
1184
return datetime_to_dbus(self.last_approval_request)
1186
# Timeout - property
1187
@dbus_service_property(_interface, signature="t",
1189
def Timeout_dbus_property(self, value=None):
997
if self.last_checked_ok is None:
998
return dbus.String(u"")
999
return dbus.String(self._datetime_to_dbus(self
1002
# timeout - property
1003
@dbus_service_property(_interface, signature=u"t",
1004
access=u"readwrite")
1005
def timeout_dbus_property(self, value=None):
1190
1006
if value is None: # get
1191
1007
return dbus.UInt64(self.timeout_milliseconds())
1192
1008
self.timeout = datetime.timedelta(0, 0, 0, value)
1193
if getattr(self, "disable_initiator_tag", None) is None:
1010
self.PropertyChanged(dbus.String(u"timeout"),
1011
dbus.UInt64(value, variant_level=1))
1012
if getattr(self, u"disable_initiator_tag", None) is None:
1195
1014
# Reschedule timeout
1196
1015
gobject.source_remove(self.disable_initiator_tag)
1197
1016
self.disable_initiator_tag = None
1199
time_to_die = _timedelta_to_milliseconds((self
1017
time_to_die = (self.
1018
_timedelta_to_milliseconds((self
1204
1023
if time_to_die <= 0:
1205
1024
# The timeout has passed
1208
self.expires = (datetime.datetime.utcnow()
1209
+ datetime.timedelta(milliseconds =
1211
1027
self.disable_initiator_tag = (gobject.timeout_add
1212
1028
(time_to_die, self.disable))
1214
# ExtendedTimeout - property
1215
@dbus_service_property(_interface, signature="t",
1217
def ExtendedTimeout_dbus_property(self, value=None):
1218
if value is None: # get
1219
return dbus.UInt64(self.extended_timeout_milliseconds())
1220
self.extended_timeout = datetime.timedelta(0, 0, 0, value)
1222
# Interval - property
1223
@dbus_service_property(_interface, signature="t",
1225
def Interval_dbus_property(self, value=None):
1030
# interval - property
1031
@dbus_service_property(_interface, signature=u"t",
1032
access=u"readwrite")
1033
def interval_dbus_property(self, value=None):
1226
1034
if value is None: # get
1227
1035
return dbus.UInt64(self.interval_milliseconds())
1228
1036
self.interval = datetime.timedelta(0, 0, 0, value)
1229
if getattr(self, "checker_initiator_tag", None) is None:
1038
self.PropertyChanged(dbus.String(u"interval"),
1039
dbus.UInt64(value, variant_level=1))
1040
if getattr(self, u"checker_initiator_tag", None) is None:
1231
1042
# Reschedule checker run
1232
1043
gobject.source_remove(self.checker_initiator_tag)
1233
1044
self.checker_initiator_tag = (gobject.timeout_add
1234
1045
(value, self.start_checker))
1235
1046
self.start_checker() # Start one now, too
1237
# Checker - property
1238
@dbus_service_property(_interface, signature="s",
1240
def Checker_dbus_property(self, value=None):
1048
# checker - property
1049
@dbus_service_property(_interface, signature=u"s",
1050
access=u"readwrite")
1051
def checker_dbus_property(self, value=None):
1241
1052
if value is None: # get
1242
1053
return dbus.String(self.checker_command)
1243
1054
self.checker_command = value
1056
self.PropertyChanged(dbus.String(u"checker"),
1057
dbus.String(self.checker_command,
1245
# CheckerRunning - property
1246
@dbus_service_property(_interface, signature="b",
1248
def CheckerRunning_dbus_property(self, value=None):
1060
# checker_running - property
1061
@dbus_service_property(_interface, signature=u"b",
1062
access=u"readwrite")
1063
def checker_running_dbus_property(self, value=None):
1249
1064
if value is None: # get
1250
1065
return dbus.Boolean(self.checker is not None)
1304
1117
def handle(self):
1305
1118
with contextlib.closing(self.server.child_pipe) as child_pipe:
1306
logger.info("TCP connection from: %s",
1119
logger.info(u"TCP connection from: %s",
1307
1120
unicode(self.client_address))
1308
logger.debug("Pipe FD: %d",
1121
logger.debug(u"Pipe FD: %d",
1309
1122
self.server.child_pipe.fileno())
1311
1124
session = (gnutls.connection
1312
1125
.ClientSession(self.request,
1313
1126
gnutls.connection
1314
1127
.X509Credentials()))
1316
1129
# Note: gnutls.connection.X509Credentials is really a
1317
1130
# generic GnuTLS certificate credentials object so long as
1318
1131
# no X.509 keys are added to it. Therefore, we can use it
1319
1132
# here despite using OpenPGP certificates.
1321
#priority = ':'.join(("NONE", "+VERS-TLS1.1",
1322
# "+AES-256-CBC", "+SHA1",
1323
# "+COMP-NULL", "+CTYPE-OPENPGP",
1134
#priority = u':'.join((u"NONE", u"+VERS-TLS1.1",
1135
# u"+AES-256-CBC", u"+SHA1",
1136
# u"+COMP-NULL", u"+CTYPE-OPENPGP",
1325
1138
# Use a fallback default, since this MUST be set.
1326
1139
priority = self.server.gnutls_priority
1327
1140
if priority is None:
1141
priority = u"NORMAL"
1329
1142
(gnutls.library.functions
1330
1143
.gnutls_priority_set_direct(session._c_object,
1331
1144
priority, None))
1333
1146
# Start communication using the Mandos protocol
1334
1147
# Get protocol number
1335
1148
line = self.request.makefile().readline()
1336
logger.debug("Protocol version: %r", line)
1149
logger.debug(u"Protocol version: %r", line)
1338
1151
if int(line.strip().split()[0]) > 1:
1339
1152
raise RuntimeError
1340
except (ValueError, IndexError, RuntimeError) as error:
1341
logger.error("Unknown protocol version: %s", error)
1153
except (ValueError, IndexError, RuntimeError), error:
1154
logger.error(u"Unknown protocol version: %s", error)
1344
1157
# Start GnuTLS connection
1346
1159
session.handshake()
1347
except gnutls.errors.GNUTLSError as error:
1348
logger.warning("Handshake failed: %s", error)
1160
except gnutls.errors.GNUTLSError, error:
1161
logger.warning(u"Handshake failed: %s", error)
1349
1162
# Do not run session.bye() here: the session is not
1350
1163
# established. Just abandon the request.
1352
logger.debug("Handshake succeeded")
1165
logger.debug(u"Handshake succeeded")
1354
1167
approval_required = False
1357
1170
fpr = self.fingerprint(self.peer_certificate
1360
gnutls.errors.GNUTLSError) as error:
1361
logger.warning("Bad certificate: %s", error)
1172
except (TypeError, gnutls.errors.GNUTLSError), error:
1173
logger.warning(u"Bad certificate: %s", error)
1363
logger.debug("Fingerprint: %s", fpr)
1175
logger.debug(u"Fingerprint: %s", fpr)
1366
1178
client = ProxyClient(child_pipe, fpr,
1367
1179
self.client_address)
1368
1180
except KeyError:
1371
if client.approval_delay:
1372
delay = client.approval_delay
1183
if client.approved_delay:
1184
delay = client.approved_delay
1373
1185
client.approvals_pending += 1
1374
1186
approval_required = True
1377
1189
if not client.enabled:
1378
logger.info("Client %s is disabled",
1190
logger.warning(u"Client %s is disabled",
1380
1192
if self.server.use_dbus:
1381
1193
# Emit D-Bus signal
1382
client.Rejected("Disabled")
1194
client.Rejected("Disabled")
1385
if client._approved or not client.approval_delay:
1197
if client._approved or not client.approved_delay:
1386
1198
#We are approved or approval is disabled
1388
1200
elif client._approved is None:
1389
logger.info("Client %s needs approval",
1201
logger.info(u"Client %s need approval",
1391
1203
if self.server.use_dbus:
1392
1204
# Emit D-Bus signal
1393
1205
client.NeedApproval(
1394
client.approval_delay_milliseconds(),
1206
client.approved_delay_milliseconds(),
1395
1207
client.approved_by_default)
1397
logger.warning("Client %s was not approved",
1209
logger.warning(u"Client %s was not approved",
1399
1211
if self.server.use_dbus:
1400
1212
# Emit D-Bus signal
1401
client.Rejected("Denied")
1213
client.Rejected("Disapproved")
1404
1216
#wait until timeout or approved
1217
#x = float(client._timedelta_to_milliseconds(delay))
1405
1218
time = datetime.datetime.now()
1406
1219
client.changedstate.acquire()
1407
(client.changedstate.wait
1408
(float(client._timedelta_to_milliseconds(delay)
1220
client.changedstate.wait(float(client._timedelta_to_milliseconds(delay) / 1000))
1410
1221
client.changedstate.release()
1411
1222
time2 = datetime.datetime.now()
1412
1223
if (time2 - time) >= delay:
1640
1446
def server_activate(self):
1641
1447
if self.enabled:
1642
1448
return socketserver.TCPServer.server_activate(self)
1644
1449
def enable(self):
1645
1450
self.enabled = True
1647
def add_pipe(self, parent_pipe, proc):
1451
def add_pipe(self, parent_pipe):
1648
1452
# Call "handle_ipc" for both data and EOF events
1649
1453
gobject.io_add_watch(parent_pipe.fileno(),
1650
1454
gobject.IO_IN | gobject.IO_HUP,
1651
1455
functools.partial(self.handle_ipc,
1456
parent_pipe = parent_pipe))
1656
1458
def handle_ipc(self, source, condition, parent_pipe=None,
1657
proc = None, client_object=None):
1459
client_object=None):
1658
1460
condition_names = {
1659
gobject.IO_IN: "IN", # There is data to read.
1660
gobject.IO_OUT: "OUT", # Data can be written (without
1461
gobject.IO_IN: u"IN", # There is data to read.
1462
gobject.IO_OUT: u"OUT", # Data can be written (without
1662
gobject.IO_PRI: "PRI", # There is urgent data to read.
1663
gobject.IO_ERR: "ERR", # Error condition.
1664
gobject.IO_HUP: "HUP" # Hung up (the connection has been
1464
gobject.IO_PRI: u"PRI", # There is urgent data to read.
1465
gobject.IO_ERR: u"ERR", # Error condition.
1466
gobject.IO_HUP: u"HUP" # Hung up (the connection has been
1665
1467
# broken, usually for pipes and
1691
logger.info("Client not found for fingerprint: %s, ad"
1692
"dress: %s", fpr, address)
1495
logger.warning(u"Client not found for fingerprint: %s, ad"
1496
u"dress: %s", fpr, address)
1693
1497
if self.use_dbus:
1694
1498
# Emit D-Bus signal
1695
mandos_dbus_service.ClientNotFound(fpr,
1499
mandos_dbus_service.ClientNotFound(fpr, address)
1697
1500
parent_pipe.send(False)
1700
1503
gobject.io_add_watch(parent_pipe.fileno(),
1701
1504
gobject.IO_IN | gobject.IO_HUP,
1702
1505
functools.partial(self.handle_ipc,
1506
parent_pipe = parent_pipe,
1507
client_object = client))
1708
1508
parent_pipe.send(True)
1709
# remove the old hook in favor of the new above hook on
1509
# remove the old hook in favor of the new above hook on same fileno
1712
1511
if command == 'funcall':
1713
1512
funcname = request[1]
1714
1513
args = request[2]
1715
1514
kwargs = request[3]
1717
parent_pipe.send(('data', getattr(client_object,
1516
parent_pipe.send(('data', getattr(client_object, funcname)(*args, **kwargs)))
1721
1518
if command == 'getattr':
1722
1519
attrname = request[1]
1723
1520
if callable(client_object.__getattribute__(attrname)):
1724
1521
parent_pipe.send(('function',))
1726
parent_pipe.send(('data', client_object
1727
.__getattribute__(attrname)))
1523
parent_pipe.send(('data', client_object.__getattribute__(attrname)))
1729
1525
if command == 'setattr':
1730
1526
attrname = request[1]
1731
1527
value = request[2]
1732
1528
setattr(client_object, attrname, value)
1737
1533
def string_to_delta(interval):
1738
1534
"""Parse a string and return a datetime.timedelta
1740
>>> string_to_delta('7d')
1536
>>> string_to_delta(u'7d')
1741
1537
datetime.timedelta(7)
1742
>>> string_to_delta('60s')
1538
>>> string_to_delta(u'60s')
1743
1539
datetime.timedelta(0, 60)
1744
>>> string_to_delta('60m')
1540
>>> string_to_delta(u'60m')
1745
1541
datetime.timedelta(0, 3600)
1746
>>> string_to_delta('24h')
1542
>>> string_to_delta(u'24h')
1747
1543
datetime.timedelta(1)
1748
>>> string_to_delta('1w')
1544
>>> string_to_delta(u'1w')
1749
1545
datetime.timedelta(7)
1750
>>> string_to_delta('5m 30s')
1546
>>> string_to_delta(u'5m 30s')
1751
1547
datetime.timedelta(0, 330)
1753
1549
timevalue = datetime.timedelta(0)
1827
1623
##################################################################
1828
1624
# Parsing of options, both command line and config file
1830
parser = argparse.ArgumentParser()
1831
parser.add_argument("-v", "--version", action="version",
1832
version = "%%(prog)s %s" % version,
1833
help="show version number and exit")
1834
parser.add_argument("-i", "--interface", metavar="IF",
1835
help="Bind to interface IF")
1836
parser.add_argument("-a", "--address",
1837
help="Address to listen for requests on")
1838
parser.add_argument("-p", "--port", type=int,
1839
help="Port number to receive requests on")
1840
parser.add_argument("--check", action="store_true",
1841
help="Run self-test")
1842
parser.add_argument("--debug", action="store_true",
1843
help="Debug mode; run in foreground and log"
1845
parser.add_argument("--debuglevel", metavar="LEVEL",
1846
help="Debug level for stdout output")
1847
parser.add_argument("--priority", help="GnuTLS"
1848
" priority string (see GnuTLS documentation)")
1849
parser.add_argument("--servicename",
1850
metavar="NAME", help="Zeroconf service name")
1851
parser.add_argument("--configdir",
1852
default="/etc/mandos", metavar="DIR",
1853
help="Directory to search for configuration"
1855
parser.add_argument("--no-dbus", action="store_false",
1856
dest="use_dbus", help="Do not provide D-Bus"
1857
" system bus interface")
1858
parser.add_argument("--no-ipv6", action="store_false",
1859
dest="use_ipv6", help="Do not use IPv6")
1860
options = parser.parse_args()
1626
parser = optparse.OptionParser(version = "%%prog %s" % version)
1627
parser.add_option("-i", u"--interface", type=u"string",
1628
metavar="IF", help=u"Bind to interface IF")
1629
parser.add_option("-a", u"--address", type=u"string",
1630
help=u"Address to listen for requests on")
1631
parser.add_option("-p", u"--port", type=u"int",
1632
help=u"Port number to receive requests on")
1633
parser.add_option("--check", action=u"store_true",
1634
help=u"Run self-test")
1635
parser.add_option("--debug", action=u"store_true",
1636
help=u"Debug mode; run in foreground and log to"
1638
parser.add_option("--debuglevel", type=u"string", metavar="Level",
1639
help=u"Debug level for stdout output")
1640
parser.add_option("--priority", type=u"string", help=u"GnuTLS"
1641
u" priority string (see GnuTLS documentation)")
1642
parser.add_option("--servicename", type=u"string",
1643
metavar=u"NAME", help=u"Zeroconf service name")
1644
parser.add_option("--configdir", type=u"string",
1645
default=u"/etc/mandos", metavar=u"DIR",
1646
help=u"Directory to search for configuration"
1648
parser.add_option("--no-dbus", action=u"store_false",
1649
dest=u"use_dbus", help=u"Do not provide D-Bus"
1650
u" system bus interface")
1651
parser.add_option("--no-ipv6", action=u"store_false",
1652
dest=u"use_ipv6", help=u"Do not use IPv6")
1653
options = parser.parse_args()[0]
1862
1655
if options.check:
1867
1660
# Default values for config file for server-global settings
1868
server_defaults = { "interface": "",
1873
"SECURE256:!CTYPE-X.509:+CTYPE-OPENPGP",
1874
"servicename": "Mandos",
1661
server_defaults = { u"interface": u"",
1666
u"SECURE256:!CTYPE-X.509:+CTYPE-OPENPGP",
1667
u"servicename": u"Mandos",
1668
u"use_dbus": u"True",
1669
u"use_ipv6": u"True",
1880
1673
# Parse config file for server-global settings
1881
1674
server_config = configparser.SafeConfigParser(server_defaults)
1882
1675
del server_defaults
1883
1676
server_config.read(os.path.join(options.configdir,
1885
1678
# Convert the SafeConfigParser object to a dict
1886
1679
server_settings = server_config.defaults()
1887
1680
# Use the appropriate methods on the non-string config options
1888
for option in ("debug", "use_dbus", "use_ipv6"):
1889
server_settings[option] = server_config.getboolean("DEFAULT",
1681
for option in (u"debug", u"use_dbus", u"use_ipv6"):
1682
server_settings[option] = server_config.getboolean(u"DEFAULT",
1891
1684
if server_settings["port"]:
1892
server_settings["port"] = server_config.getint("DEFAULT",
1685
server_settings["port"] = server_config.getint(u"DEFAULT",
1894
1687
del server_config
1896
1689
# Override the settings from the config file with command line
1897
1690
# options, if set.
1898
for option in ("interface", "address", "port", "debug",
1899
"priority", "servicename", "configdir",
1900
"use_dbus", "use_ipv6", "debuglevel"):
1691
for option in (u"interface", u"address", u"port", u"debug",
1692
u"priority", u"servicename", u"configdir",
1693
u"use_dbus", u"use_ipv6", u"debuglevel"):
1901
1694
value = getattr(options, option)
1902
1695
if value is not None:
1903
1696
server_settings[option] = value
1911
1704
##################################################################
1913
1706
# For convenience
1914
debug = server_settings["debug"]
1915
debuglevel = server_settings["debuglevel"]
1916
use_dbus = server_settings["use_dbus"]
1917
use_ipv6 = server_settings["use_ipv6"]
1919
if server_settings["servicename"] != "Mandos":
1707
debug = server_settings[u"debug"]
1708
debuglevel = server_settings[u"debuglevel"]
1709
use_dbus = server_settings[u"use_dbus"]
1710
use_ipv6 = server_settings[u"use_ipv6"]
1712
if server_settings[u"servicename"] != u"Mandos":
1920
1713
syslogger.setFormatter(logging.Formatter
1921
('Mandos (%s) [%%(process)d]:'
1922
' %%(levelname)s: %%(message)s'
1923
% server_settings["servicename"]))
1714
(u'Mandos (%s) [%%(process)d]:'
1715
u' %%(levelname)s: %%(message)s'
1716
% server_settings[u"servicename"]))
1925
1718
# Parse config file with clients
1926
client_defaults = { "timeout": "5m",
1927
"extended_timeout": "15m",
1929
"checker": "fping -q -- %%(host)s",
1931
"approval_delay": "0s",
1932
"approval_duration": "1s",
1719
client_defaults = { u"timeout": u"1h",
1721
u"checker": u"fping -q -- %%(host)s",
1723
u"approved_delay": u"0s",
1724
u"approved_duration": u"1s",
1934
1726
client_config = configparser.SafeConfigParser(client_defaults)
1935
client_config.read(os.path.join(server_settings["configdir"],
1727
client_config.read(os.path.join(server_settings[u"configdir"],
1938
1730
global mandos_dbus_service
1939
1731
mandos_dbus_service = None
1941
tcp_server = MandosServer((server_settings["address"],
1942
server_settings["port"]),
1733
tcp_server = MandosServer((server_settings[u"address"],
1734
server_settings[u"port"]),
1944
interface=(server_settings["interface"]
1736
interface=server_settings[u"interface"],
1946
1737
use_ipv6=use_ipv6,
1947
1738
gnutls_priority=
1948
server_settings["priority"],
1739
server_settings[u"priority"],
1949
1740
use_dbus=use_dbus)
1951
pidfilename = "/var/run/mandos.pid"
1953
pidfile = open(pidfilename, "w")
1955
logger.error("Could not open file %r", pidfilename)
1741
pidfilename = u"/var/run/mandos.pid"
1743
pidfile = open(pidfilename, u"w")
1745
logger.error(u"Could not open file %r", pidfilename)
1958
uid = pwd.getpwnam("_mandos").pw_uid
1959
gid = pwd.getpwnam("_mandos").pw_gid
1748
uid = pwd.getpwnam(u"_mandos").pw_uid
1749
gid = pwd.getpwnam(u"_mandos").pw_gid
1960
1750
except KeyError:
1962
uid = pwd.getpwnam("mandos").pw_uid
1963
gid = pwd.getpwnam("mandos").pw_gid
1752
uid = pwd.getpwnam(u"mandos").pw_uid
1753
gid = pwd.getpwnam(u"mandos").pw_gid
1964
1754
except KeyError:
1966
uid = pwd.getpwnam("nobody").pw_uid
1967
gid = pwd.getpwnam("nobody").pw_gid
1756
uid = pwd.getpwnam(u"nobody").pw_uid
1757
gid = pwd.getpwnam(u"nobody").pw_gid
1968
1758
except KeyError:
1974
except OSError as error:
1764
except OSError, error:
1975
1765
if error[0] != errno.EPERM:
1768
# Enable all possible GnuTLS debugging
1978
1771
if not debug and not debuglevel:
1979
logger.setLevel(logging.WARNING)
1772
syslogger.setLevel(logging.WARNING)
1773
console.setLevel(logging.WARNING)
1981
1775
level = getattr(logging, debuglevel.upper())
1982
logger.setLevel(level)
1776
syslogger.setLevel(level)
1777
console.setLevel(level)
1985
logger.setLevel(logging.DEBUG)
1986
# Enable all possible GnuTLS debugging
1988
1780
# "Use a log level over 10 to enable all debugging options."
1989
1781
# - GnuTLS manual
1990
1782
gnutls.library.functions.gnutls_global_set_log_level(11)
1992
1784
@gnutls.library.types.gnutls_log_func
1993
1785
def debug_gnutls(level, string):
1994
logger.debug("GnuTLS: %s", string[:-1])
1786
logger.debug(u"GnuTLS: %s", string[:-1])
1996
1788
(gnutls.library.functions
1997
1789
.gnutls_global_set_log_function(debug_gnutls))
1999
1791
# Redirect stdin so all checkers get /dev/null
2000
1792
null = os.open(os.path.devnull, os.O_NOCTTY | os.O_RDWR)
2001
1793
os.dup2(null, sys.stdin.fileno())
2018
1806
# End of Avahi example code
2021
bus_name = dbus.service.BusName("se.recompile.Mandos",
1809
bus_name = dbus.service.BusName(u"se.bsnet.fukt.Mandos",
2022
1810
bus, do_not_queue=True)
2023
old_bus_name = (dbus.service.BusName
2024
("se.bsnet.fukt.Mandos", bus,
2026
except dbus.exceptions.NameExistsException as e:
2027
logger.error(unicode(e) + ", disabling D-Bus")
1811
except dbus.exceptions.NameExistsException, e:
1812
logger.error(unicode(e) + u", disabling D-Bus")
2028
1813
use_dbus = False
2029
server_settings["use_dbus"] = False
1814
server_settings[u"use_dbus"] = False
2030
1815
tcp_server.use_dbus = False
2031
1816
protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
2032
service = AvahiServiceToSyslog(name =
2033
server_settings["servicename"],
2034
servicetype = "_mandos._tcp",
2035
protocol = protocol, bus = bus)
1817
service = AvahiService(name = server_settings[u"servicename"],
1818
servicetype = u"_mandos._tcp",
1819
protocol = protocol, bus = bus)
2036
1820
if server_settings["interface"]:
2037
1821
service.interface = (if_nametoindex
2038
(str(server_settings["interface"])))
1822
(str(server_settings[u"interface"])))
1825
# Close all input and output, do double fork, etc.
2040
1828
global multiprocessing_manager
2041
1829
multiprocessing_manager = multiprocessing.Manager()
2043
1831
client_class = Client
2045
client_class = functools.partial(ClientDBusTransitional,
1833
client_class = functools.partial(ClientDBus, bus = bus)
2047
1834
def client_config_items(config, section):
2048
1835
special_settings = {
2049
1836
"approved_by_default":
2087
1873
class MandosDBusService(dbus.service.Object):
2088
1874
"""A D-Bus proxy object"""
2089
1875
def __init__(self):
2090
dbus.service.Object.__init__(self, bus, "/")
2091
_interface = "se.recompile.Mandos"
1876
dbus.service.Object.__init__(self, bus, u"/")
1877
_interface = u"se.bsnet.fukt.Mandos"
2093
@dbus.service.signal(_interface, signature="o")
1879
@dbus.service.signal(_interface, signature=u"o")
2094
1880
def ClientAdded(self, objpath):
2098
@dbus.service.signal(_interface, signature="ss")
1884
@dbus.service.signal(_interface, signature=u"ss")
2099
1885
def ClientNotFound(self, fingerprint, address):
2103
@dbus.service.signal(_interface, signature="os")
1889
@dbus.service.signal(_interface, signature=u"os")
2104
1890
def ClientRemoved(self, objpath, name):
2108
@dbus.service.method(_interface, out_signature="ao")
1894
@dbus.service.method(_interface, out_signature=u"ao")
2109
1895
def GetAllClients(self):
2111
1897
return dbus.Array(c.dbus_object_path
2112
1898
for c in tcp_server.clients)
2114
1900
@dbus.service.method(_interface,
2115
out_signature="a{oa{sv}}")
1901
out_signature=u"a{oa{sv}}")
2116
1902
def GetAllClientsWithProperties(self):
2118
1904
return dbus.Dictionary(
2119
((c.dbus_object_path, c.GetAll(""))
1905
((c.dbus_object_path, c.GetAll(u""))
2120
1906
for c in tcp_server.clients),
1907
signature=u"oa{sv}")
2123
@dbus.service.method(_interface, in_signature="o")
1909
@dbus.service.method(_interface, in_signature=u"o")
2124
1910
def RemoveClient(self, object_path):
2126
1912
for c in tcp_server.clients: