148
126
self.rename_count = 0
149
127
self.max_renames = max_renames
150
128
self.protocol = protocol
151
self.group = None # our entry group
154
self.entry_group_state_changed_match = None
155
129
def rename(self):
156
130
"""Derived from the Avahi example code"""
157
131
if self.rename_count >= self.max_renames:
158
logger.critical("No suitable Zeroconf service name found"
159
" after %i retries, exiting.",
132
logger.critical(u"No suitable Zeroconf service name found"
133
u" after %i retries, exiting.",
160
134
self.rename_count)
161
raise AvahiServiceError("Too many renames")
162
self.name = unicode(self.server.GetAlternativeServiceName(self.name))
163
logger.info("Changing Zeroconf service name to %r ...",
135
raise AvahiServiceError(u"Too many renames")
136
self.name = server.GetAlternativeServiceName(self.name)
137
logger.info(u"Changing Zeroconf service name to %r ...",
165
139
syslogger.setFormatter(logging.Formatter
166
('Mandos (%s) [%%(process)d]:'
167
' %%(levelname)s: %%(message)s'
140
('Mandos (%s): %%(levelname)s:'
141
' %%(message)s' % self.name))
172
except dbus.exceptions.DBusException as error:
173
logger.critical("DBusException: %s", error)
176
144
self.rename_count += 1
177
145
def remove(self):
178
146
"""Derived from the Avahi example code"""
179
if self.entry_group_state_changed_match is not None:
180
self.entry_group_state_changed_match.remove()
181
self.entry_group_state_changed_match = None
182
if self.group is not None:
147
if group is not None:
185
150
"""Derived from the Avahi example code"""
187
if self.group is None:
188
self.group = dbus.Interface(
189
self.bus.get_object(avahi.DBUS_NAME,
190
self.server.EntryGroupNew()),
191
avahi.DBUS_INTERFACE_ENTRY_GROUP)
192
self.entry_group_state_changed_match = (
193
self.group.connect_to_signal(
194
'StateChanged', self .entry_group_state_changed))
195
logger.debug("Adding Zeroconf service '%s' of type '%s' ...",
196
self.name, self.type)
197
self.group.AddService(
200
dbus.UInt32(0), # flags
201
self.name, self.type,
202
self.domain, self.host,
203
dbus.UInt16(self.port),
204
avahi.string_array_to_txt_array(self.TXT))
206
def entry_group_state_changed(self, state, error):
207
"""Derived from the Avahi example code"""
208
logger.debug("Avahi entry group state change: %i", state)
210
if state == avahi.ENTRY_GROUP_ESTABLISHED:
211
logger.debug("Zeroconf service established.")
212
elif state == avahi.ENTRY_GROUP_COLLISION:
213
logger.info("Zeroconf service name collision.")
215
elif state == avahi.ENTRY_GROUP_FAILURE:
216
logger.critical("Avahi: Error in group state changed %s",
218
raise AvahiGroupError("State changed: %s"
221
"""Derived from the Avahi example code"""
222
if self.group is not None:
225
except (dbus.exceptions.UnknownMethodException,
226
dbus.exceptions.DBusException) as e:
230
def server_state_changed(self, state, error=None):
231
"""Derived from the Avahi example code"""
232
logger.debug("Avahi server state change: %i", state)
233
bad_states = { avahi.SERVER_INVALID:
234
"Zeroconf server invalid",
235
avahi.SERVER_REGISTERING: None,
236
avahi.SERVER_COLLISION:
237
"Zeroconf server name collision",
238
avahi.SERVER_FAILURE:
239
"Zeroconf server failure" }
240
if state in bad_states:
241
if bad_states[state] is not None:
243
logger.error(bad_states[state])
245
logger.error(bad_states[state] + ": %r", error)
247
elif state == avahi.SERVER_RUNNING:
251
logger.debug("Unknown state: %r", state)
253
logger.debug("Unknown state: %r: %r", state, error)
255
"""Derived from the Avahi example code"""
256
if self.server is None:
257
self.server = dbus.Interface(
258
self.bus.get_object(avahi.DBUS_NAME,
259
avahi.DBUS_PATH_SERVER,
260
follow_name_owner_changes=True),
261
avahi.DBUS_INTERFACE_SERVER)
262
self.server.connect_to_signal("StateChanged",
263
self.server_state_changed)
264
self.server_state_changed(self.server.GetState())
267
def _timedelta_to_milliseconds(td):
268
"Convert a datetime.timedelta() to milliseconds"
269
return ((td.days * 24 * 60 * 60 * 1000)
270
+ (td.seconds * 1000)
271
+ (td.microseconds // 1000))
273
class Client(object):
153
group = dbus.Interface(bus.get_object
155
server.EntryGroupNew()),
156
avahi.DBUS_INTERFACE_ENTRY_GROUP)
157
group.connect_to_signal('StateChanged',
158
entry_group_state_changed)
159
logger.debug(u"Adding Zeroconf service '%s' of type '%s' ...",
160
service.name, service.type)
162
self.interface, # interface
163
self.protocol, # protocol
164
dbus.UInt32(0), # flags
165
self.name, self.type,
166
self.domain, self.host,
167
dbus.UInt16(self.port),
168
avahi.string_array_to_txt_array(self.TXT))
171
# From the Avahi example code:
172
group = None # our entry group
173
# End of Avahi example code
176
def _datetime_to_dbus(dt, variant_level=0):
177
"""Convert a UTC datetime.datetime() to a D-Bus type."""
178
return dbus.String(dt.isoformat(), variant_level=variant_level)
181
class Client(dbus.service.Object):
274
182
"""A representation of a client host served by this server.
277
_approved: bool(); 'None' if not yet approved/disapproved
278
approval_delay: datetime.timedelta(); Time to wait for approval
279
approval_duration: datetime.timedelta(); Duration of one approval
184
name: string; from the config file, used in log messages and
186
fingerprint: string (40 or 32 hexadecimal digits); used to
187
uniquely identify the client
188
secret: bytestring; sent verbatim (over TLS) to client
189
host: string; available for use by the checker command
190
created: datetime.datetime(); (UTC) object creation
191
last_enabled: datetime.datetime(); (UTC)
193
last_checked_ok: datetime.datetime(); (UTC) or None
194
timeout: datetime.timedelta(); How long from last_checked_ok
195
until this client is invalid
196
interval: datetime.timedelta(); How often to start a new checker
197
disable_hook: If set, called by disable() as disable_hook(self)
280
198
checker: subprocess.Popen(); a running checker process used
281
199
to see if the client lives.
282
200
'None' if no process is running.
283
checker_callback_tag: a gobject event source tag, or None
284
checker_command: string; External command which is run to check
285
if client lives. %() expansions are done at
201
checker_initiator_tag: a gobject event source tag, or None
202
disable_initiator_tag: - '' -
203
checker_callback_tag: - '' -
204
checker_command: string; External command which is run to check if
205
client lives. %() expansions are done at
286
206
runtime with vars(self) as dict, so that for
287
207
instance %(name)s can be used in the command.
288
checker_initiator_tag: a gobject event source tag, or None
289
created: datetime.datetime(); (UTC) object creation
290
208
current_checker_command: string; current running checker_command
291
disable_hook: If set, called by disable() as disable_hook(self)
292
disable_initiator_tag: a gobject event source tag, or None
294
fingerprint: string (40 or 32 hexadecimal digits); used to
295
uniquely identify the client
296
host: string; available for use by the checker command
297
interval: datetime.timedelta(); How often to start a new checker
298
last_approval_request: datetime.datetime(); (UTC) or None
299
last_checked_ok: datetime.datetime(); (UTC) or None
300
last_enabled: datetime.datetime(); (UTC)
301
name: string; from the config file, used in log messages and
303
secret: bytestring; sent verbatim (over TLS) to client
304
timeout: datetime.timedelta(); How long from last_checked_ok
305
until this client is disabled
306
extended_timeout: extra long timeout when password has been sent
307
runtime_expansions: Allowed attributes for runtime expansion.
308
expires: datetime.datetime(); time (UTC) when a client will be
209
use_dbus: bool(); Whether to provide D-Bus interface and signals
210
dbus_object_path: dbus.ObjectPath ; only set if self.use_dbus
312
runtime_expansions = ("approval_delay", "approval_duration",
313
"created", "enabled", "fingerprint",
314
"host", "interval", "last_checked_ok",
315
"last_enabled", "name", "timeout")
317
212
def timeout_milliseconds(self):
318
213
"Return the 'timeout' attribute in milliseconds"
319
return _timedelta_to_milliseconds(self.timeout)
321
def extended_timeout_milliseconds(self):
322
"Return the 'extended_timeout' attribute in milliseconds"
323
return _timedelta_to_milliseconds(self.extended_timeout)
214
return ((self.timeout.days * 24 * 60 * 60 * 1000)
215
+ (self.timeout.seconds * 1000)
216
+ (self.timeout.microseconds // 1000))
325
218
def interval_milliseconds(self):
326
219
"Return the 'interval' attribute in milliseconds"
327
return _timedelta_to_milliseconds(self.interval)
329
def approval_delay_milliseconds(self):
330
return _timedelta_to_milliseconds(self.approval_delay)
332
def __init__(self, name = None, disable_hook=None, config=None):
220
return ((self.interval.days * 24 * 60 * 60 * 1000)
221
+ (self.interval.seconds * 1000)
222
+ (self.interval.microseconds // 1000))
224
def __init__(self, name = None, disable_hook=None, config=None,
333
226
"""Note: the 'checker' key in 'config' sets the
334
227
'checker_command' attribute and *not* the 'checker'
337
230
if config is None:
339
logger.debug("Creating client %r", self.name)
232
logger.debug(u"Creating client %r", self.name)
233
self.use_dbus = False # During __init__
340
234
# Uppercase and remove spaces from fingerprint for later
341
235
# comparison purposes with return value from the fingerprint()
343
237
self.fingerprint = (config["fingerprint"].upper()
345
logger.debug(" Fingerprint: %s", self.fingerprint)
239
logger.debug(u" Fingerprint: %s", self.fingerprint)
346
240
if "secret" in config:
347
self.secret = config["secret"].decode("base64")
241
self.secret = config["secret"].decode(u"base64")
348
242
elif "secfile" in config:
349
with open(os.path.expanduser(os.path.expandvars
350
(config["secfile"])),
243
with closing(open(os.path.expanduser
245
(config["secfile"])))) as secfile:
352
246
self.secret = secfile.read()
354
raise TypeError("No secret or secfile for client %s"
248
raise TypeError(u"No secret or secfile for client %s"
356
250
self.host = config.get("host", "")
357
251
self.created = datetime.datetime.utcnow()
358
252
self.enabled = False
359
self.last_approval_request = None
360
253
self.last_enabled = None
361
254
self.last_checked_ok = None
362
255
self.timeout = string_to_delta(config["timeout"])
363
self.extended_timeout = string_to_delta(config["extended_timeout"])
364
256
self.interval = string_to_delta(config["interval"])
365
257
self.disable_hook = disable_hook
366
258
self.checker = None
367
259
self.checker_initiator_tag = None
368
260
self.disable_initiator_tag = None
370
261
self.checker_callback_tag = None
371
262
self.checker_command = config["checker"]
372
263
self.current_checker_command = None
373
264
self.last_connect = None
374
self._approved = None
375
self.approved_by_default = config.get("approved_by_default",
377
self.approvals_pending = 0
378
self.approval_delay = string_to_delta(
379
config["approval_delay"])
380
self.approval_duration = string_to_delta(
381
config["approval_duration"])
382
self.changedstate = multiprocessing_manager.Condition(multiprocessing_manager.Lock())
265
# Only now, when this client is initialized, can it show up on
267
self.use_dbus = use_dbus
269
self.dbus_object_path = (dbus.ObjectPath
271
+ self.name.replace(".", "_")))
272
dbus.service.Object.__init__(self, bus,
273
self.dbus_object_path)
384
def send_changedstate(self):
385
self.changedstate.acquire()
386
self.changedstate.notify_all()
387
self.changedstate.release()
389
275
def enable(self):
390
276
"""Start this client's checker and timeout hooks"""
391
if getattr(self, "enabled", False):
394
self.send_changedstate()
277
self.last_enabled = datetime.datetime.utcnow()
395
278
# Schedule a new checker to be started an 'interval' from now,
396
279
# and every interval from then on.
397
280
self.checker_initiator_tag = (gobject.timeout_add
398
281
(self.interval_milliseconds(),
399
282
self.start_checker))
283
# Also start a new checker *right now*.
400
285
# Schedule a disable() when 'timeout' has passed
401
self.expires = datetime.datetime.utcnow() + self.timeout
402
286
self.disable_initiator_tag = (gobject.timeout_add
403
287
(self.timeout_milliseconds(),
405
289
self.enabled = True
406
self.last_enabled = datetime.datetime.utcnow()
407
# Also start a new checker *right now*.
292
self.PropertyChanged(dbus.String(u"enabled"),
293
dbus.Boolean(True, variant_level=1))
294
self.PropertyChanged(dbus.String(u"last_enabled"),
295
(_datetime_to_dbus(self.last_enabled,
410
def disable(self, quiet=True):
411
299
"""Disable this client."""
412
300
if not getattr(self, "enabled", False):
415
self.send_changedstate()
417
logger.info("Disabling client %s", self.name)
302
logger.info(u"Disabling client %s", self.name)
418
303
if getattr(self, "disable_initiator_tag", False):
419
304
gobject.source_remove(self.disable_initiator_tag)
420
305
self.disable_initiator_tag = None
422
306
if getattr(self, "checker_initiator_tag", False):
423
307
gobject.source_remove(self.checker_initiator_tag)
424
308
self.checker_initiator_tag = None
550
446
self.checker_callback_tag = None
551
447
if getattr(self, "checker", None) is None:
553
logger.debug("Stopping checker for %(name)s", vars(self))
449
logger.debug(u"Stopping checker for %(name)s", vars(self))
555
451
os.kill(self.checker.pid, signal.SIGTERM)
557
453
#if self.checker.poll() is None:
558
454
# os.kill(self.checker.pid, signal.SIGKILL)
559
except OSError as error:
455
except OSError, error:
560
456
if error.errno != errno.ESRCH: # No such process
562
458
self.checker = None
565
def dbus_service_property(dbus_interface, signature="v",
566
access="readwrite", byte_arrays=False):
567
"""Decorators for marking methods of a DBusObjectWithProperties to
568
become properties on the D-Bus.
570
The decorated method will be called with no arguments by "Get"
571
and with one argument by "Set".
573
The parameters, where they are supported, are the same as
574
dbus.service.method, except there is only "signature", since the
575
type from Get() and the type sent to Set() is the same.
577
# Encoding deeply encoded byte arrays is not supported yet by the
578
# "Set" method, so we fail early here:
579
if byte_arrays and signature != "ay":
580
raise ValueError("Byte arrays not supported for non-'ay'"
581
" signature %r" % signature)
583
func._dbus_is_property = True
584
func._dbus_interface = dbus_interface
585
func._dbus_signature = signature
586
func._dbus_access = access
587
func._dbus_name = func.__name__
588
if func._dbus_name.endswith("_dbus_property"):
589
func._dbus_name = func._dbus_name[:-14]
590
func._dbus_get_args_options = {'byte_arrays': byte_arrays }
595
class DBusPropertyException(dbus.exceptions.DBusException):
596
"""A base class for D-Bus property-related exceptions
598
def __unicode__(self):
599
return unicode(str(self))
602
class DBusPropertyAccessException(DBusPropertyException):
603
"""A property's access permissions disallows an operation.
608
class DBusPropertyNotFound(DBusPropertyException):
609
"""An attempt was made to access a non-existing property.
614
class DBusObjectWithProperties(dbus.service.Object):
615
"""A D-Bus object with properties.
617
Classes inheriting from this can use the dbus_service_property
618
decorator to expose methods as D-Bus properties. It exposes the
619
standard Get(), Set(), and GetAll() methods on the D-Bus.
623
def _is_dbus_property(obj):
624
return getattr(obj, "_dbus_is_property", False)
626
def _get_all_dbus_properties(self):
627
"""Returns a generator of (name, attribute) pairs
629
return ((prop._dbus_name, prop)
631
inspect.getmembers(self, self._is_dbus_property))
633
def _get_dbus_property(self, interface_name, property_name):
634
"""Returns a bound method if one exists which is a D-Bus
635
property with the specified name and interface.
637
for name in (property_name,
638
property_name + "_dbus_property"):
639
prop = getattr(self, name, None)
641
or not self._is_dbus_property(prop)
642
or prop._dbus_name != property_name
643
or (interface_name and prop._dbus_interface
644
and interface_name != prop._dbus_interface)):
648
raise DBusPropertyNotFound(self.dbus_object_path + ":"
649
+ interface_name + "."
652
@dbus.service.method(dbus.PROPERTIES_IFACE, in_signature="ss",
654
def Get(self, interface_name, property_name):
655
"""Standard D-Bus property Get() method, see D-Bus standard.
657
prop = self._get_dbus_property(interface_name, property_name)
658
if prop._dbus_access == "write":
659
raise DBusPropertyAccessException(property_name)
661
if not hasattr(value, "variant_level"):
663
return type(value)(value, variant_level=value.variant_level+1)
665
@dbus.service.method(dbus.PROPERTIES_IFACE, in_signature="ssv")
666
def Set(self, interface_name, property_name, value):
667
"""Standard D-Bus property Set() method, see D-Bus standard.
669
prop = self._get_dbus_property(interface_name, property_name)
670
if prop._dbus_access == "read":
671
raise DBusPropertyAccessException(property_name)
672
if prop._dbus_get_args_options["byte_arrays"]:
673
# The byte_arrays option is not supported yet on
674
# signatures other than "ay".
675
if prop._dbus_signature != "ay":
677
value = dbus.ByteArray(''.join(unichr(byte)
681
@dbus.service.method(dbus.PROPERTIES_IFACE, in_signature="s",
682
out_signature="a{sv}")
683
def GetAll(self, interface_name):
684
"""Standard D-Bus property GetAll() method, see D-Bus
687
Note: Will not include properties with access="write".
690
for name, prop in self._get_all_dbus_properties():
692
and interface_name != prop._dbus_interface):
693
# Interface non-empty but did not match
695
# Ignore write-only properties
696
if prop._dbus_access == "write":
699
if not hasattr(value, "variant_level"):
702
all[name] = type(value)(value, variant_level=
703
value.variant_level+1)
704
return dbus.Dictionary(all, signature="sv")
706
@dbus.service.method(dbus.INTROSPECTABLE_IFACE,
708
path_keyword='object_path',
709
connection_keyword='connection')
710
def Introspect(self, object_path, connection):
711
"""Standard D-Bus method, overloaded to insert property tags.
713
xmlstring = dbus.service.Object.Introspect(self, object_path,
716
document = xml.dom.minidom.parseString(xmlstring)
717
def make_tag(document, name, prop):
718
e = document.createElement("property")
719
e.setAttribute("name", name)
720
e.setAttribute("type", prop._dbus_signature)
721
e.setAttribute("access", prop._dbus_access)
723
for if_tag in document.getElementsByTagName("interface"):
724
for tag in (make_tag(document, name, prop)
726
in self._get_all_dbus_properties()
727
if prop._dbus_interface
728
== if_tag.getAttribute("name")):
729
if_tag.appendChild(tag)
730
# Add the names to the return values for the
731
# "org.freedesktop.DBus.Properties" methods
732
if (if_tag.getAttribute("name")
733
== "org.freedesktop.DBus.Properties"):
734
for cn in if_tag.getElementsByTagName("method"):
735
if cn.getAttribute("name") == "Get":
736
for arg in cn.getElementsByTagName("arg"):
737
if (arg.getAttribute("direction")
739
arg.setAttribute("name", "value")
740
elif cn.getAttribute("name") == "GetAll":
741
for arg in cn.getElementsByTagName("arg"):
742
if (arg.getAttribute("direction")
744
arg.setAttribute("name", "props")
745
xmlstring = document.toxml("utf-8")
747
except (AttributeError, xml.dom.DOMException,
748
xml.parsers.expat.ExpatError) as error:
749
logger.error("Failed to override Introspection method",
754
def datetime_to_dbus (dt, variant_level=0):
755
"""Convert a UTC datetime.datetime() to a D-Bus type."""
757
return dbus.String("", variant_level = variant_level)
758
return dbus.String(dt.isoformat(),
759
variant_level=variant_level)
762
class ClientDBus(Client, DBusObjectWithProperties):
763
"""A Client class using D-Bus
766
dbus_object_path: dbus.ObjectPath
767
bus: dbus.SystemBus()
770
runtime_expansions = (Client.runtime_expansions
771
+ ("dbus_object_path",))
773
# dbus.service.Object doesn't use super(), so we can't either.
775
def __init__(self, bus = None, *args, **kwargs):
776
self._approvals_pending = 0
778
Client.__init__(self, *args, **kwargs)
779
# Only now, when this client is initialized, can it show up on
781
client_object_name = unicode(self.name).translate(
784
self.dbus_object_path = (dbus.ObjectPath
785
("/clients/" + client_object_name))
786
DBusObjectWithProperties.__init__(self, self.bus,
787
self.dbus_object_path)
789
def notifychangeproperty(transform_func,
790
dbus_name, type_func=lambda x: x,
792
""" Modify a variable so that its a property that announce its
794
transform_fun: Function that takes a value and transform it to
796
dbus_name: DBus name of the variable
797
type_func: Function that transform the value before sending it
799
variant_level: DBus variant level. default: 1
802
def setter(self, value):
803
old_value = real_value[0]
804
real_value[0] = value
805
if hasattr(self, "dbus_object_path"):
806
if type_func(old_value) != type_func(real_value[0]):
807
dbus_value = transform_func(type_func(real_value[0]),
809
self.PropertyChanged(dbus.String(dbus_name),
812
return property(lambda self: real_value[0], setter)
815
expires = notifychangeproperty(datetime_to_dbus, "Expires")
816
approvals_pending = notifychangeproperty(dbus.Boolean,
819
enabled = notifychangeproperty(dbus.Boolean, "Enabled")
820
last_enabled = notifychangeproperty(datetime_to_dbus,
822
checker = notifychangeproperty(dbus.Boolean, "CheckerRunning",
823
type_func = lambda checker: checker is not None)
824
last_checked_ok = notifychangeproperty(datetime_to_dbus,
826
last_approval_request = notifychangeproperty(datetime_to_dbus,
827
"LastApprovalRequest")
828
approved_by_default = notifychangeproperty(dbus.Boolean,
830
approval_delay = notifychangeproperty(dbus.UInt16, "ApprovalDelay",
831
type_func = _timedelta_to_milliseconds)
832
approval_duration = notifychangeproperty(dbus.UInt16, "ApprovalDuration",
833
type_func = _timedelta_to_milliseconds)
834
host = notifychangeproperty(dbus.String, "Host")
835
timeout = notifychangeproperty(dbus.UInt16, "Timeout",
836
type_func = _timedelta_to_milliseconds)
837
extended_timeout = notifychangeproperty(dbus.UInt16, "ExtendedTimeout",
838
type_func = _timedelta_to_milliseconds)
839
interval = notifychangeproperty(dbus.UInt16, "Interval",
840
type_func = _timedelta_to_milliseconds)
841
checker_command = notifychangeproperty(dbus.String, "Checker")
843
del notifychangeproperty
845
def __del__(self, *args, **kwargs):
847
self.remove_from_connection()
850
if hasattr(DBusObjectWithProperties, "__del__"):
851
DBusObjectWithProperties.__del__(self, *args, **kwargs)
852
Client.__del__(self, *args, **kwargs)
854
def checker_callback(self, pid, condition, command,
856
self.checker_callback_tag = None
858
if os.WIFEXITED(condition):
859
exitstatus = os.WEXITSTATUS(condition)
861
self.CheckerCompleted(dbus.Int16(exitstatus),
862
dbus.Int64(condition),
863
dbus.String(command))
866
self.CheckerCompleted(dbus.Int16(-1),
867
dbus.Int64(condition),
868
dbus.String(command))
870
return Client.checker_callback(self, pid, condition, command,
873
def start_checker(self, *args, **kwargs):
874
old_checker = self.checker
875
if self.checker is not None:
876
old_checker_pid = self.checker.pid
878
old_checker_pid = None
879
r = Client.start_checker(self, *args, **kwargs)
880
# Only if new checker process was started
881
if (self.checker is not None
882
and old_checker_pid != self.checker.pid):
884
self.CheckerStarted(self.current_checker_command)
887
def _reset_approved(self):
888
self._approved = None
891
def approve(self, value=True):
892
self.send_changedstate()
893
self._approved = value
894
gobject.timeout_add(_timedelta_to_milliseconds
895
(self.approval_duration),
896
self._reset_approved)
899
## D-Bus methods, signals & properties
900
_interface = "se.bsnet.fukt.Mandos.Client"
460
self.PropertyChanged(dbus.String(u"checker_running"),
461
dbus.Boolean(False, variant_level=1))
463
def still_valid(self):
464
"""Has the timeout not yet passed for this client?"""
465
if not getattr(self, "enabled", False):
467
now = datetime.datetime.utcnow()
468
if self.last_checked_ok is None:
469
return now < (self.created + self.timeout)
471
return now < (self.last_checked_ok + self.timeout)
473
## D-Bus methods & signals
474
_interface = u"se.bsnet.fukt.Mandos.Client"
477
CheckedOK = dbus.service.method(_interface)(checked_ok)
478
CheckedOK.__name__ = "CheckedOK"
904
480
# CheckerCompleted - signal
905
481
@dbus.service.signal(_interface, signature="nxs")
973
605
# StopChecker - method
974
@dbus.service.method(_interface)
975
def StopChecker(self):
980
# ApprovalPending - property
981
@dbus_service_property(_interface, signature="b", access="read")
982
def ApprovalPending_dbus_property(self):
983
return dbus.Boolean(bool(self.approvals_pending))
985
# ApprovedByDefault - property
986
@dbus_service_property(_interface, signature="b",
988
def ApprovedByDefault_dbus_property(self, value=None):
989
if value is None: # get
990
return dbus.Boolean(self.approved_by_default)
991
self.approved_by_default = bool(value)
993
# ApprovalDelay - property
994
@dbus_service_property(_interface, signature="t",
996
def ApprovalDelay_dbus_property(self, value=None):
997
if value is None: # get
998
return dbus.UInt64(self.approval_delay_milliseconds())
999
self.approval_delay = datetime.timedelta(0, 0, 0, value)
1001
# ApprovalDuration - property
1002
@dbus_service_property(_interface, signature="t",
1004
def ApprovalDuration_dbus_property(self, value=None):
1005
if value is None: # get
1006
return dbus.UInt64(_timedelta_to_milliseconds(
1007
self.approval_duration))
1008
self.approval_duration = datetime.timedelta(0, 0, 0, value)
1011
@dbus_service_property(_interface, signature="s", access="read")
1012
def Name_dbus_property(self):
1013
return dbus.String(self.name)
1015
# Fingerprint - property
1016
@dbus_service_property(_interface, signature="s", access="read")
1017
def Fingerprint_dbus_property(self):
1018
return dbus.String(self.fingerprint)
1021
@dbus_service_property(_interface, signature="s",
1023
def Host_dbus_property(self, value=None):
1024
if value is None: # get
1025
return dbus.String(self.host)
1028
# Created - property
1029
@dbus_service_property(_interface, signature="s", access="read")
1030
def Created_dbus_property(self):
1031
return dbus.String(datetime_to_dbus(self.created))
1033
# LastEnabled - property
1034
@dbus_service_property(_interface, signature="s", access="read")
1035
def LastEnabled_dbus_property(self):
1036
return datetime_to_dbus(self.last_enabled)
1038
# Enabled - property
1039
@dbus_service_property(_interface, signature="b",
1041
def Enabled_dbus_property(self, value=None):
1042
if value is None: # get
1043
return dbus.Boolean(self.enabled)
1049
# LastCheckedOK - property
1050
@dbus_service_property(_interface, signature="s",
1052
def LastCheckedOK_dbus_property(self, value=None):
1053
if value is not None:
1056
return datetime_to_dbus(self.last_checked_ok)
1058
# Expires - property
1059
@dbus_service_property(_interface, signature="s", access="read")
1060
def Expires_dbus_property(self):
1061
return datetime_to_dbus(self.expires)
1063
# LastApprovalRequest - property
1064
@dbus_service_property(_interface, signature="s", access="read")
1065
def LastApprovalRequest_dbus_property(self):
1066
return datetime_to_dbus(self.last_approval_request)
1068
# Timeout - property
1069
@dbus_service_property(_interface, signature="t",
1071
def Timeout_dbus_property(self, value=None):
1072
if value is None: # get
1073
return dbus.UInt64(self.timeout_milliseconds())
1074
self.timeout = datetime.timedelta(0, 0, 0, value)
1075
if getattr(self, "disable_initiator_tag", None) is None:
1077
# Reschedule timeout
1078
gobject.source_remove(self.disable_initiator_tag)
1079
self.disable_initiator_tag = None
1081
time_to_die = (self.
1082
_timedelta_to_milliseconds((self
1087
if time_to_die <= 0:
1088
# The timeout has passed
1091
self.expires = (datetime.datetime.utcnow()
1092
+ datetime.timedelta(milliseconds = time_to_die))
1093
self.disable_initiator_tag = (gobject.timeout_add
1094
(time_to_die, self.disable))
1096
# ExtendedTimeout - property
1097
@dbus_service_property(_interface, signature="t",
1099
def ExtendedTimeout_dbus_property(self, value=None):
1100
if value is None: # get
1101
return dbus.UInt64(self.extended_timeout_milliseconds())
1102
self.extended_timeout = datetime.timedelta(0, 0, 0, value)
1104
# Interval - property
1105
@dbus_service_property(_interface, signature="t",
1107
def Interval_dbus_property(self, value=None):
1108
if value is None: # get
1109
return dbus.UInt64(self.interval_milliseconds())
1110
self.interval = datetime.timedelta(0, 0, 0, value)
1111
if getattr(self, "checker_initiator_tag", None) is None:
1113
# Reschedule checker run
1114
gobject.source_remove(self.checker_initiator_tag)
1115
self.checker_initiator_tag = (gobject.timeout_add
1116
(value, self.start_checker))
1117
self.start_checker() # Start one now, too
1119
# Checker - property
1120
@dbus_service_property(_interface, signature="s",
1122
def Checker_dbus_property(self, value=None):
1123
if value is None: # get
1124
return dbus.String(self.checker_command)
1125
self.checker_command = value
1127
# CheckerRunning - property
1128
@dbus_service_property(_interface, signature="b",
1130
def CheckerRunning_dbus_property(self, value=None):
1131
if value is None: # get
1132
return dbus.Boolean(self.checker is not None)
1134
self.start_checker()
1138
# ObjectPath - property
1139
@dbus_service_property(_interface, signature="o", access="read")
1140
def ObjectPath_dbus_property(self):
1141
return self.dbus_object_path # is already a dbus.ObjectPath
1144
@dbus_service_property(_interface, signature="ay",
1145
access="write", byte_arrays=True)
1146
def Secret_dbus_property(self, value):
1147
self.secret = str(value)
606
StopChecker = dbus.service.method(_interface)(stop_checker)
607
StopChecker.__name__ = "StopChecker"
1152
class ProxyClient(object):
1153
def __init__(self, child_pipe, fpr, address):
1154
self._pipe = child_pipe
1155
self._pipe.send(('init', fpr, address))
1156
if not self._pipe.recv():
1159
def __getattribute__(self, name):
1160
if(name == '_pipe'):
1161
return super(ProxyClient, self).__getattribute__(name)
1162
self._pipe.send(('getattr', name))
1163
data = self._pipe.recv()
1164
if data[0] == 'data':
1166
if data[0] == 'function':
1167
def func(*args, **kwargs):
1168
self._pipe.send(('funcall', name, args, kwargs))
1169
return self._pipe.recv()[1]
1172
def __setattr__(self, name, value):
1173
if(name == '_pipe'):
1174
return super(ProxyClient, self).__setattr__(name, value)
1175
self._pipe.send(('setattr', name, value))
1178
class ClientHandler(socketserver.BaseRequestHandler, object):
1179
"""A class to handle client connections.
1181
Instantiated once for each connection to handle it.
612
def peer_certificate(session):
613
"Return the peer's OpenPGP certificate as a bytestring"
614
# If not an OpenPGP certificate...
615
if (gnutls.library.functions
616
.gnutls_certificate_type_get(session._c_object)
617
!= gnutls.library.constants.GNUTLS_CRT_OPENPGP):
618
# ...do the normal thing
619
return session.peer_certificate
620
list_size = ctypes.c_uint(1)
621
cert_list = (gnutls.library.functions
622
.gnutls_certificate_get_peers
623
(session._c_object, ctypes.byref(list_size)))
624
if not bool(cert_list) and list_size.value != 0:
625
raise gnutls.errors.GNUTLSError("error getting peer"
627
if list_size.value == 0:
630
return ctypes.string_at(cert.data, cert.size)
633
def fingerprint(openpgp):
634
"Convert an OpenPGP bytestring to a hexdigit fingerprint string"
635
# New GnuTLS "datum" with the OpenPGP public key
636
datum = (gnutls.library.types
637
.gnutls_datum_t(ctypes.cast(ctypes.c_char_p(openpgp),
640
ctypes.c_uint(len(openpgp))))
641
# New empty GnuTLS certificate
642
crt = gnutls.library.types.gnutls_openpgp_crt_t()
643
(gnutls.library.functions
644
.gnutls_openpgp_crt_init(ctypes.byref(crt)))
645
# Import the OpenPGP public key into the certificate
646
(gnutls.library.functions
647
.gnutls_openpgp_crt_import(crt, ctypes.byref(datum),
648
gnutls.library.constants
649
.GNUTLS_OPENPGP_FMT_RAW))
650
# Verify the self signature in the key
651
crtverify = ctypes.c_uint()
652
(gnutls.library.functions
653
.gnutls_openpgp_crt_verify_self(crt, 0, ctypes.byref(crtverify)))
654
if crtverify.value != 0:
655
gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
656
raise gnutls.errors.CertificateSecurityError("Verify failed")
657
# New buffer for the fingerprint
658
buf = ctypes.create_string_buffer(20)
659
buf_len = ctypes.c_size_t()
660
# Get the fingerprint from the certificate into the buffer
661
(gnutls.library.functions
662
.gnutls_openpgp_crt_get_fingerprint(crt, ctypes.byref(buf),
663
ctypes.byref(buf_len)))
664
# Deinit the certificate
665
gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
666
# Convert the buffer to a Python bytestring
667
fpr = ctypes.string_at(buf, buf_len.value)
668
# Convert the bytestring to hexadecimal notation
669
hex_fpr = u''.join(u"%02X" % ord(char) for char in fpr)
673
class TCP_handler(SocketServer.BaseRequestHandler, object):
674
"""A TCP request handler class.
675
Instantiated by IPv6_TCPServer for each request to handle it.
1182
676
Note: This will run in its own forked process."""
1184
678
def handle(self):
1185
with contextlib.closing(self.server.child_pipe) as child_pipe:
1186
logger.info("TCP connection from: %s",
1187
unicode(self.client_address))
1188
logger.debug("Pipe FD: %d",
1189
self.server.child_pipe.fileno())
1191
session = (gnutls.connection
1192
.ClientSession(self.request,
1194
.X509Credentials()))
1196
# Note: gnutls.connection.X509Credentials is really a
1197
# generic GnuTLS certificate credentials object so long as
1198
# no X.509 keys are added to it. Therefore, we can use it
1199
# here despite using OpenPGP certificates.
1201
#priority = ':'.join(("NONE", "+VERS-TLS1.1",
1202
# "+AES-256-CBC", "+SHA1",
1203
# "+COMP-NULL", "+CTYPE-OPENPGP",
1205
# Use a fallback default, since this MUST be set.
1206
priority = self.server.gnutls_priority
1207
if priority is None:
1209
(gnutls.library.functions
1210
.gnutls_priority_set_direct(session._c_object,
1213
# Start communication using the Mandos protocol
1214
# Get protocol number
1215
line = self.request.makefile().readline()
1216
logger.debug("Protocol version: %r", line)
1218
if int(line.strip().split()[0]) > 1:
1220
except (ValueError, IndexError, RuntimeError) as error:
1221
logger.error("Unknown protocol version: %s", error)
1224
# Start GnuTLS connection
1227
except gnutls.errors.GNUTLSError as error:
1228
logger.warning("Handshake failed: %s", error)
1229
# Do not run session.bye() here: the session is not
1230
# established. Just abandon the request.
1232
logger.debug("Handshake succeeded")
1234
approval_required = False
1237
fpr = self.fingerprint(self.peer_certificate
1240
gnutls.errors.GNUTLSError) as error:
1241
logger.warning("Bad certificate: %s", error)
1243
logger.debug("Fingerprint: %s", fpr)
1246
client = ProxyClient(child_pipe, fpr,
1247
self.client_address)
1251
if client.approval_delay:
1252
delay = client.approval_delay
1253
client.approvals_pending += 1
1254
approval_required = True
1257
if not client.enabled:
1258
logger.info("Client %s is disabled",
1260
if self.server.use_dbus:
1262
client.Rejected("Disabled")
1265
if client._approved or not client.approval_delay:
1266
#We are approved or approval is disabled
1268
elif client._approved is None:
1269
logger.info("Client %s needs approval",
1271
if self.server.use_dbus:
1273
client.NeedApproval(
1274
client.approval_delay_milliseconds(),
1275
client.approved_by_default)
1277
logger.warning("Client %s was not approved",
1279
if self.server.use_dbus:
1281
client.Rejected("Denied")
1284
#wait until timeout or approved
1285
#x = float(client._timedelta_to_milliseconds(delay))
1286
time = datetime.datetime.now()
1287
client.changedstate.acquire()
1288
client.changedstate.wait(float(client._timedelta_to_milliseconds(delay) / 1000))
1289
client.changedstate.release()
1290
time2 = datetime.datetime.now()
1291
if (time2 - time) >= delay:
1292
if not client.approved_by_default:
1293
logger.warning("Client %s timed out while"
1294
" waiting for approval",
1296
if self.server.use_dbus:
1298
client.Rejected("Approval timed out")
1303
delay -= time2 - time
1306
while sent_size < len(client.secret):
1308
sent = session.send(client.secret[sent_size:])
1309
except gnutls.errors.GNUTLSError as error:
1310
logger.warning("gnutls send failed")
1312
logger.debug("Sent: %d, remaining: %d",
1313
sent, len(client.secret)
1314
- (sent_size + sent))
1317
logger.info("Sending secret to %s", client.name)
1318
# bump the timeout as if seen
1319
client.checked_ok(client.extended_timeout)
1320
if self.server.use_dbus:
1325
if approval_required:
1326
client.approvals_pending -= 1
1329
except gnutls.errors.GNUTLSError as error:
1330
logger.warning("GnuTLS bye failed")
1333
def peer_certificate(session):
1334
"Return the peer's OpenPGP certificate as a bytestring"
1335
# If not an OpenPGP certificate...
1336
if (gnutls.library.functions
1337
.gnutls_certificate_type_get(session._c_object)
1338
!= gnutls.library.constants.GNUTLS_CRT_OPENPGP):
1339
# ...do the normal thing
1340
return session.peer_certificate
1341
list_size = ctypes.c_uint(1)
1342
cert_list = (gnutls.library.functions
1343
.gnutls_certificate_get_peers
1344
(session._c_object, ctypes.byref(list_size)))
1345
if not bool(cert_list) and list_size.value != 0:
1346
raise gnutls.errors.GNUTLSError("error getting peer"
1348
if list_size.value == 0:
1351
return ctypes.string_at(cert.data, cert.size)
1354
def fingerprint(openpgp):
1355
"Convert an OpenPGP bytestring to a hexdigit fingerprint"
1356
# New GnuTLS "datum" with the OpenPGP public key
1357
datum = (gnutls.library.types
1358
.gnutls_datum_t(ctypes.cast(ctypes.c_char_p(openpgp),
1361
ctypes.c_uint(len(openpgp))))
1362
# New empty GnuTLS certificate
1363
crt = gnutls.library.types.gnutls_openpgp_crt_t()
1364
(gnutls.library.functions
1365
.gnutls_openpgp_crt_init(ctypes.byref(crt)))
1366
# Import the OpenPGP public key into the certificate
1367
(gnutls.library.functions
1368
.gnutls_openpgp_crt_import(crt, ctypes.byref(datum),
1369
gnutls.library.constants
1370
.GNUTLS_OPENPGP_FMT_RAW))
1371
# Verify the self signature in the key
1372
crtverify = ctypes.c_uint()
1373
(gnutls.library.functions
1374
.gnutls_openpgp_crt_verify_self(crt, 0,
1375
ctypes.byref(crtverify)))
1376
if crtverify.value != 0:
1377
gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
1378
raise (gnutls.errors.CertificateSecurityError
1380
# New buffer for the fingerprint
1381
buf = ctypes.create_string_buffer(20)
1382
buf_len = ctypes.c_size_t()
1383
# Get the fingerprint from the certificate into the buffer
1384
(gnutls.library.functions
1385
.gnutls_openpgp_crt_get_fingerprint(crt, ctypes.byref(buf),
1386
ctypes.byref(buf_len)))
1387
# Deinit the certificate
1388
gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
1389
# Convert the buffer to a Python bytestring
1390
fpr = ctypes.string_at(buf, buf_len.value)
1391
# Convert the bytestring to hexadecimal notation
1392
hex_fpr = ''.join("%02X" % ord(char) for char in fpr)
1396
class MultiprocessingMixIn(object):
1397
"""Like socketserver.ThreadingMixIn, but with multiprocessing"""
1398
def sub_process_main(self, request, address):
1400
self.finish_request(request, address)
1402
self.handle_error(request, address)
1403
self.close_request(request)
1405
def process_request(self, request, address):
1406
"""Start a new process to process the request."""
1407
multiprocessing.Process(target = self.sub_process_main,
1408
args = (request, address)).start()
1411
class MultiprocessingMixInWithPipe(MultiprocessingMixIn, object):
1412
""" adds a pipe to the MixIn """
1413
def process_request(self, request, client_address):
1414
"""Overrides and wraps the original process_request().
1416
This function creates a new pipe in self.pipe
1418
parent_pipe, self.child_pipe = multiprocessing.Pipe()
1420
super(MultiprocessingMixInWithPipe,
1421
self).process_request(request, client_address)
1422
self.child_pipe.close()
1423
self.add_pipe(parent_pipe)
1425
def add_pipe(self, parent_pipe):
1426
"""Dummy function; override as necessary"""
1427
raise NotImplementedError
1430
class IPv6_TCPServer(MultiprocessingMixInWithPipe,
1431
socketserver.TCPServer, object):
679
logger.info(u"TCP connection from: %s",
680
unicode(self.client_address))
681
session = (gnutls.connection
682
.ClientSession(self.request,
686
line = self.request.makefile().readline()
687
logger.debug(u"Protocol version: %r", line)
689
if int(line.strip().split()[0]) > 1:
691
except (ValueError, IndexError, RuntimeError), error:
692
logger.error(u"Unknown protocol version: %s", error)
695
# Note: gnutls.connection.X509Credentials is really a generic
696
# GnuTLS certificate credentials object so long as no X.509
697
# keys are added to it. Therefore, we can use it here despite
698
# using OpenPGP certificates.
700
#priority = ':'.join(("NONE", "+VERS-TLS1.1", "+AES-256-CBC",
701
# "+SHA1", "+COMP-NULL", "+CTYPE-OPENPGP",
703
# Use a fallback default, since this MUST be set.
704
priority = self.server.settings.get("priority", "NORMAL")
705
(gnutls.library.functions
706
.gnutls_priority_set_direct(session._c_object,
711
except gnutls.errors.GNUTLSError, error:
712
logger.warning(u"Handshake failed: %s", error)
713
# Do not run session.bye() here: the session is not
714
# established. Just abandon the request.
716
logger.debug(u"Handshake succeeded")
718
fpr = fingerprint(peer_certificate(session))
719
except (TypeError, gnutls.errors.GNUTLSError), error:
720
logger.warning(u"Bad certificate: %s", error)
723
logger.debug(u"Fingerprint: %s", fpr)
725
for c in self.server.clients:
726
if c.fingerprint == fpr:
730
logger.warning(u"Client not found for fingerprint: %s",
734
# Have to check if client.still_valid(), since it is possible
735
# that the client timed out while establishing the GnuTLS
737
if not client.still_valid():
738
logger.warning(u"Client %(name)s is invalid",
742
## This won't work here, since we're in a fork.
743
# client.checked_ok()
745
while sent_size < len(client.secret):
746
sent = session.send(client.secret[sent_size:])
747
logger.debug(u"Sent: %d, remaining: %d",
748
sent, len(client.secret)
749
- (sent_size + sent))
754
class IPv6_TCPServer(SocketServer.ForkingMixIn,
755
SocketServer.TCPServer, object):
1432
756
"""IPv6-capable TCP server. Accepts 'None' as address and/or port
758
settings: Server settings
759
clients: Set() of Client objects
1435
760
enabled: Boolean; whether this server is activated yet
1436
interface: None or a network interface name (string)
1437
use_ipv6: Boolean; to use IPv6 or not
1439
def __init__(self, server_address, RequestHandlerClass,
1440
interface=None, use_ipv6=True):
1441
self.interface = interface
1443
self.address_family = socket.AF_INET6
1444
socketserver.TCPServer.__init__(self, server_address,
1445
RequestHandlerClass)
762
address_family = socket.AF_INET6
763
def __init__(self, *args, **kwargs):
764
if "settings" in kwargs:
765
self.settings = kwargs["settings"]
766
del kwargs["settings"]
767
if "clients" in kwargs:
768
self.clients = kwargs["clients"]
769
del kwargs["clients"]
770
if "use_ipv6" in kwargs:
771
if not kwargs["use_ipv6"]:
772
self.address_family = socket.AF_INET
773
del kwargs["use_ipv6"]
775
super(IPv6_TCPServer, self).__init__(*args, **kwargs)
1446
776
def server_bind(self):
1447
777
"""This overrides the normal server_bind() function
1448
778
to bind to an interface if one was specified, and also NOT to
1449
779
bind to an address or port if they were not specified."""
1450
if self.interface is not None:
1451
if SO_BINDTODEVICE is None:
1452
logger.error("SO_BINDTODEVICE does not exist;"
1453
" cannot bind to interface %s",
1457
self.socket.setsockopt(socket.SOL_SOCKET,
1461
except socket.error as error:
1462
if error[0] == errno.EPERM:
1463
logger.error("No permission to"
1464
" bind to interface %s",
1466
elif error[0] == errno.ENOPROTOOPT:
1467
logger.error("SO_BINDTODEVICE not available;"
1468
" cannot bind to interface %s",
780
if self.settings["interface"]:
781
# 25 is from /usr/include/asm-i486/socket.h
782
SO_BINDTODEVICE = getattr(socket, "SO_BINDTODEVICE", 25)
784
self.socket.setsockopt(socket.SOL_SOCKET,
786
self.settings["interface"])
787
except socket.error, error:
788
if error[0] == errno.EPERM:
789
logger.error(u"No permission to"
790
u" bind to interface %s",
791
self.settings["interface"])
1472
794
# Only bind(2) the socket if we really need to.
1473
795
if self.server_address[0] or self.server_address[1]:
1474
796
if not self.server_address[0]: