/mandos/trunk

To get this branch, use:
bzr branch http://bzr.recompile.se/loggerhead/mandos/trunk

« back to all changes in this revision

Viewing changes to mandos

  • Committer: Teddy Hogeborn
  • Date: 2009-04-16 06:47:28 UTC
  • Revision ID: teddy@fukt.bsnet.se-20090416064728-c3d36mvgxo5q9aoh
* mandos: Import "SocketServer" as "socketserver" and "ConfigParser"
          as "configparser".  All users changed.

Show diffs side-by-side

added added

removed removed

Lines of Context:
6
6
# This program is partly derived from an example program for an Avahi
7
7
# service publisher, downloaded from
8
8
# <http://avahi.org/wiki/PythonPublishExample>.  This includes the
9
 
# methods "add", "remove", "server_state_changed",
10
 
# "entry_group_state_changed", "cleanup", and "activate" in the
11
 
# "AvahiService" class, and some lines in "main".
 
9
# methods "add" and "remove" in the "AvahiService" class, the
 
10
# "server_state_changed" and "entry_group_state_changed" functions,
 
11
# and some lines in "main".
12
12
13
13
# Everything else is
14
14
# Copyright © 2008,2009 Teddy Hogeborn
55
55
import logging
56
56
import logging.handlers
57
57
import pwd
58
 
import contextlib
 
58
from contextlib import closing
59
59
import struct
60
60
import fcntl
61
 
import functools
62
 
import cPickle as pickle
63
61
 
64
62
import dbus
65
63
import dbus.service
68
66
from dbus.mainloop.glib import DBusGMainLoop
69
67
import ctypes
70
68
import ctypes.util
71
 
import xml.dom.minidom
72
 
import inspect
73
69
 
74
70
try:
75
71
    SO_BINDTODEVICE = socket.SO_BINDTODEVICE
77
73
    try:
78
74
        from IN import SO_BINDTODEVICE
79
75
    except ImportError:
80
 
        SO_BINDTODEVICE = None
81
 
 
82
 
 
83
 
version = "1.0.14"
 
76
        # From /usr/include/asm/socket.h
 
77
        SO_BINDTODEVICE = 25
 
78
 
 
79
 
 
80
version = "1.0.8"
84
81
 
85
82
logger = logging.Logger(u'mandos')
86
83
syslogger = (logging.handlers.SysLogHandler
127
124
    max_renames: integer; maximum number of renames
128
125
    rename_count: integer; counter so we only rename after collisions
129
126
                  a sensible number of times
130
 
    group: D-Bus Entry Group
131
 
    server: D-Bus Server
132
 
    bus: dbus.SystemBus()
133
127
    """
134
128
    def __init__(self, interface = avahi.IF_UNSPEC, name = None,
135
129
                 servicetype = None, port = None, TXT = None,
136
130
                 domain = u"", host = u"", max_renames = 32768,
137
 
                 protocol = avahi.PROTO_UNSPEC, bus = None):
 
131
                 protocol = avahi.PROTO_UNSPEC):
138
132
        self.interface = interface
139
133
        self.name = name
140
134
        self.type = servicetype
145
139
        self.rename_count = 0
146
140
        self.max_renames = max_renames
147
141
        self.protocol = protocol
148
 
        self.group = None       # our entry group
149
 
        self.server = None
150
 
        self.bus = bus
151
142
    def rename(self):
152
143
        """Derived from the Avahi example code"""
153
144
        if self.rename_count >= self.max_renames:
155
146
                            u" after %i retries, exiting.",
156
147
                            self.rename_count)
157
148
            raise AvahiServiceError(u"Too many renames")
158
 
        self.name = self.server.GetAlternativeServiceName(self.name)
 
149
        self.name = server.GetAlternativeServiceName(self.name)
159
150
        logger.info(u"Changing Zeroconf service name to %r ...",
160
 
                    unicode(self.name))
 
151
                    self.name)
161
152
        syslogger.setFormatter(logging.Formatter
162
153
                               (u'Mandos (%s) [%%(process)d]:'
163
154
                                u' %%(levelname)s: %%(message)s'
167
158
        self.rename_count += 1
168
159
    def remove(self):
169
160
        """Derived from the Avahi example code"""
170
 
        if self.group is not None:
171
 
            self.group.Reset()
 
161
        if group is not None:
 
162
            group.Reset()
172
163
    def add(self):
173
164
        """Derived from the Avahi example code"""
174
 
        if self.group is None:
175
 
            self.group = dbus.Interface(
176
 
                self.bus.get_object(avahi.DBUS_NAME,
177
 
                                    self.server.EntryGroupNew()),
178
 
                avahi.DBUS_INTERFACE_ENTRY_GROUP)
179
 
            self.group.connect_to_signal('StateChanged',
180
 
                                         self
181
 
                                         .entry_group_state_changed)
 
165
        global group
 
166
        if group is None:
 
167
            group = dbus.Interface(bus.get_object
 
168
                                   (avahi.DBUS_NAME,
 
169
                                    server.EntryGroupNew()),
 
170
                                   avahi.DBUS_INTERFACE_ENTRY_GROUP)
 
171
            group.connect_to_signal('StateChanged',
 
172
                                    entry_group_state_changed)
182
173
        logger.debug(u"Adding Zeroconf service '%s' of type '%s' ...",
183
 
                     self.name, self.type)
184
 
        self.group.AddService(
185
 
            self.interface,
186
 
            self.protocol,
187
 
            dbus.UInt32(0),     # flags
188
 
            self.name, self.type,
189
 
            self.domain, self.host,
190
 
            dbus.UInt16(self.port),
191
 
            avahi.string_array_to_txt_array(self.TXT))
192
 
        self.group.Commit()
193
 
    def entry_group_state_changed(self, state, error):
194
 
        """Derived from the Avahi example code"""
195
 
        logger.debug(u"Avahi state change: %i", state)
196
 
        
197
 
        if state == avahi.ENTRY_GROUP_ESTABLISHED:
198
 
            logger.debug(u"Zeroconf service established.")
199
 
        elif state == avahi.ENTRY_GROUP_COLLISION:
200
 
            logger.warning(u"Zeroconf service name collision.")
201
 
            self.rename()
202
 
        elif state == avahi.ENTRY_GROUP_FAILURE:
203
 
            logger.critical(u"Avahi: Error in group state changed %s",
204
 
                            unicode(error))
205
 
            raise AvahiGroupError(u"State changed: %s"
206
 
                                  % unicode(error))
207
 
    def cleanup(self):
208
 
        """Derived from the Avahi example code"""
209
 
        if self.group is not None:
210
 
            self.group.Free()
211
 
            self.group = None
212
 
    def server_state_changed(self, state):
213
 
        """Derived from the Avahi example code"""
214
 
        if state == avahi.SERVER_COLLISION:
215
 
            logger.error(u"Zeroconf server name collision")
216
 
            self.remove()
217
 
        elif state == avahi.SERVER_RUNNING:
218
 
            self.add()
219
 
    def activate(self):
220
 
        """Derived from the Avahi example code"""
221
 
        if self.server is None:
222
 
            self.server = dbus.Interface(
223
 
                self.bus.get_object(avahi.DBUS_NAME,
224
 
                                    avahi.DBUS_PATH_SERVER),
225
 
                avahi.DBUS_INTERFACE_SERVER)
226
 
        self.server.connect_to_signal(u"StateChanged",
227
 
                                 self.server_state_changed)
228
 
        self.server_state_changed(self.server.GetState())
 
174
                     service.name, service.type)
 
175
        group.AddService(
 
176
                self.interface,         # interface
 
177
                self.protocol,          # protocol
 
178
                dbus.UInt32(0),         # flags
 
179
                self.name, self.type,
 
180
                self.domain, self.host,
 
181
                dbus.UInt16(self.port),
 
182
                avahi.string_array_to_txt_array(self.TXT))
 
183
        group.Commit()
 
184
 
 
185
# From the Avahi example code:
 
186
group = None                            # our entry group
 
187
# End of Avahi example code
 
188
 
 
189
 
 
190
def _datetime_to_dbus(dt, variant_level=0):
 
191
    """Convert a UTC datetime.datetime() to a D-Bus type."""
 
192
    return dbus.String(dt.isoformat(), variant_level=variant_level)
229
193
 
230
194
 
231
195
class Client(object):
243
207
    enabled:    bool()
244
208
    last_checked_ok: datetime.datetime(); (UTC) or None
245
209
    timeout:    datetime.timedelta(); How long from last_checked_ok
246
 
                                      until this client is disabled
 
210
                                      until this client is invalid
247
211
    interval:   datetime.timedelta(); How often to start a new checker
248
212
    disable_hook:  If set, called by disable() as disable_hook(self)
249
213
    checker:    subprocess.Popen(); a running checker process used
250
214
                                    to see if the client lives.
251
215
                                    'None' if no process is running.
252
216
    checker_initiator_tag: a gobject event source tag, or None
253
 
    disable_initiator_tag: - '' -
 
217
    disable_initiator_tag:    - '' -
254
218
    checker_callback_tag:  - '' -
255
219
    checker_command: string; External command which is run to check if
256
220
                     client lives.  %() expansions are done at
260
224
    """
261
225
    
262
226
    @staticmethod
263
 
    def _timedelta_to_milliseconds(td):
264
 
        "Convert a datetime.timedelta() to milliseconds"
265
 
        return ((td.days * 24 * 60 * 60 * 1000)
266
 
                + (td.seconds * 1000)
267
 
                + (td.microseconds // 1000))
 
227
    def _datetime_to_milliseconds(dt):
 
228
        "Convert a datetime.datetime() to milliseconds"
 
229
        return ((dt.days * 24 * 60 * 60 * 1000)
 
230
                + (dt.seconds * 1000)
 
231
                + (dt.microseconds // 1000))
268
232
    
269
233
    def timeout_milliseconds(self):
270
234
        "Return the 'timeout' attribute in milliseconds"
271
 
        return self._timedelta_to_milliseconds(self.timeout)
 
235
        return self._datetime_to_milliseconds(self.timeout)
272
236
    
273
237
    def interval_milliseconds(self):
274
238
        "Return the 'interval' attribute in milliseconds"
275
 
        return self._timedelta_to_milliseconds(self.interval)
 
239
        return self._datetime_to_milliseconds(self.interval)
276
240
    
277
241
    def __init__(self, name = None, disable_hook=None, config=None):
278
242
        """Note: the 'checker' key in 'config' sets the
291
255
        if u"secret" in config:
292
256
            self.secret = config[u"secret"].decode(u"base64")
293
257
        elif u"secfile" in config:
294
 
            with open(os.path.expanduser(os.path.expandvars
295
 
                                         (config[u"secfile"])),
296
 
                      "rb") as secfile:
 
258
            with closing(open(os.path.expanduser
 
259
                              (os.path.expandvars
 
260
                               (config[u"secfile"])))) as secfile:
297
261
                self.secret = secfile.read()
298
262
        else:
299
263
            raise TypeError(u"No secret or secfile for client %s"
316
280
    
317
281
    def enable(self):
318
282
        """Start this client's checker and timeout hooks"""
319
 
        if getattr(self, u"enabled", False):
320
 
            # Already enabled
321
 
            return
322
283
        self.last_enabled = datetime.datetime.utcnow()
323
284
        # Schedule a new checker to be started an 'interval' from now,
324
285
        # and every interval from then on.
325
286
        self.checker_initiator_tag = (gobject.timeout_add
326
287
                                      (self.interval_milliseconds(),
327
288
                                       self.start_checker))
 
289
        # Also start a new checker *right now*.
 
290
        self.start_checker()
328
291
        # Schedule a disable() when 'timeout' has passed
329
292
        self.disable_initiator_tag = (gobject.timeout_add
330
293
                                   (self.timeout_milliseconds(),
331
294
                                    self.disable))
332
295
        self.enabled = True
333
 
        # Also start a new checker *right now*.
334
 
        self.start_checker()
335
296
    
336
 
    def disable(self, quiet=True):
 
297
    def disable(self):
337
298
        """Disable this client."""
338
299
        if not getattr(self, "enabled", False):
339
300
            return False
340
 
        if not quiet:
341
 
            logger.info(u"Disabling client %s", self.name)
 
301
        logger.info(u"Disabling client %s", self.name)
342
302
        if getattr(self, u"disable_initiator_tag", False):
343
303
            gobject.source_remove(self.disable_initiator_tag)
344
304
            self.disable_initiator_tag = None
396
356
        # client would inevitably timeout, since no checker would get
397
357
        # a chance to run to completion.  If we instead leave running
398
358
        # checkers alone, the checker would have to take more time
399
 
        # than 'timeout' for the client to be disabled, which is as it
400
 
        # should be.
 
359
        # than 'timeout' for the client to be declared invalid, which
 
360
        # is as it should be.
401
361
        
402
362
        # If a checker exists, make sure it is not a zombie
403
 
        try:
 
363
        if self.checker is not None:
404
364
            pid, status = os.waitpid(self.checker.pid, os.WNOHANG)
405
 
        except (AttributeError, OSError), error:
406
 
            if (isinstance(error, OSError)
407
 
                and error.errno != errno.ECHILD):
408
 
                raise error
409
 
        else:
410
365
            if pid:
411
366
                logger.warning(u"Checker was a zombie")
412
367
                gobject.source_remove(self.checker_callback_tag)
468
423
        logger.debug(u"Stopping checker for %(name)s", vars(self))
469
424
        try:
470
425
            os.kill(self.checker.pid, signal.SIGTERM)
471
 
            #time.sleep(0.5)
 
426
            #os.sleep(0.5)
472
427
            #if self.checker.poll() is None:
473
428
            #    os.kill(self.checker.pid, signal.SIGKILL)
474
429
        except OSError, error:
475
430
            if error.errno != errno.ESRCH: # No such process
476
431
                raise
477
432
        self.checker = None
478
 
 
479
 
 
480
 
def dbus_service_property(dbus_interface, signature=u"v",
481
 
                          access=u"readwrite", byte_arrays=False):
482
 
    """Decorators for marking methods of a DBusObjectWithProperties to
483
 
    become properties on the D-Bus.
484
 
    
485
 
    The decorated method will be called with no arguments by "Get"
486
 
    and with one argument by "Set".
487
 
    
488
 
    The parameters, where they are supported, are the same as
489
 
    dbus.service.method, except there is only "signature", since the
490
 
    type from Get() and the type sent to Set() is the same.
491
 
    """
492
 
    # Encoding deeply encoded byte arrays is not supported yet by the
493
 
    # "Set" method, so we fail early here:
494
 
    if byte_arrays and signature != u"ay":
495
 
        raise ValueError(u"Byte arrays not supported for non-'ay'"
496
 
                         u" signature %r" % signature)
497
 
    def decorator(func):
498
 
        func._dbus_is_property = True
499
 
        func._dbus_interface = dbus_interface
500
 
        func._dbus_signature = signature
501
 
        func._dbus_access = access
502
 
        func._dbus_name = func.__name__
503
 
        if func._dbus_name.endswith(u"_dbus_property"):
504
 
            func._dbus_name = func._dbus_name[:-14]
505
 
        func._dbus_get_args_options = {u'byte_arrays': byte_arrays }
506
 
        return func
507
 
    return decorator
508
 
 
509
 
 
510
 
class DBusPropertyException(dbus.exceptions.DBusException):
511
 
    """A base class for D-Bus property-related exceptions
512
 
    """
513
 
    def __unicode__(self):
514
 
        return unicode(str(self))
515
 
 
516
 
 
517
 
class DBusPropertyAccessException(DBusPropertyException):
518
 
    """A property's access permissions disallows an operation.
519
 
    """
520
 
    pass
521
 
 
522
 
 
523
 
class DBusPropertyNotFound(DBusPropertyException):
524
 
    """An attempt was made to access a non-existing property.
525
 
    """
526
 
    pass
527
 
 
528
 
 
529
 
class DBusObjectWithProperties(dbus.service.Object):
530
 
    """A D-Bus object with properties.
531
 
 
532
 
    Classes inheriting from this can use the dbus_service_property
533
 
    decorator to expose methods as D-Bus properties.  It exposes the
534
 
    standard Get(), Set(), and GetAll() methods on the D-Bus.
535
 
    """
536
 
    
537
 
    @staticmethod
538
 
    def _is_dbus_property(obj):
539
 
        return getattr(obj, u"_dbus_is_property", False)
540
 
    
541
 
    def _get_all_dbus_properties(self):
542
 
        """Returns a generator of (name, attribute) pairs
543
 
        """
544
 
        return ((prop._dbus_name, prop)
545
 
                for name, prop in
546
 
                inspect.getmembers(self, self._is_dbus_property))
547
 
    
548
 
    def _get_dbus_property(self, interface_name, property_name):
549
 
        """Returns a bound method if one exists which is a D-Bus
550
 
        property with the specified name and interface.
551
 
        """
552
 
        for name in (property_name,
553
 
                     property_name + u"_dbus_property"):
554
 
            prop = getattr(self, name, None)
555
 
            if (prop is None
556
 
                or not self._is_dbus_property(prop)
557
 
                or prop._dbus_name != property_name
558
 
                or (interface_name and prop._dbus_interface
559
 
                    and interface_name != prop._dbus_interface)):
560
 
                continue
561
 
            return prop
562
 
        # No such property
563
 
        raise DBusPropertyNotFound(self.dbus_object_path + u":"
564
 
                                   + interface_name + u"."
565
 
                                   + property_name)
566
 
    
567
 
    @dbus.service.method(dbus.PROPERTIES_IFACE, in_signature=u"ss",
568
 
                         out_signature=u"v")
569
 
    def Get(self, interface_name, property_name):
570
 
        """Standard D-Bus property Get() method, see D-Bus standard.
571
 
        """
572
 
        prop = self._get_dbus_property(interface_name, property_name)
573
 
        if prop._dbus_access == u"write":
574
 
            raise DBusPropertyAccessException(property_name)
575
 
        value = prop()
576
 
        if not hasattr(value, u"variant_level"):
577
 
            return value
578
 
        return type(value)(value, variant_level=value.variant_level+1)
579
 
    
580
 
    @dbus.service.method(dbus.PROPERTIES_IFACE, in_signature=u"ssv")
581
 
    def Set(self, interface_name, property_name, value):
582
 
        """Standard D-Bus property Set() method, see D-Bus standard.
583
 
        """
584
 
        prop = self._get_dbus_property(interface_name, property_name)
585
 
        if prop._dbus_access == u"read":
586
 
            raise DBusPropertyAccessException(property_name)
587
 
        if prop._dbus_get_args_options[u"byte_arrays"]:
588
 
            # The byte_arrays option is not supported yet on
589
 
            # signatures other than "ay".
590
 
            if prop._dbus_signature != u"ay":
591
 
                raise ValueError
592
 
            value = dbus.ByteArray(''.join(unichr(byte)
593
 
                                           for byte in value))
594
 
        prop(value)
595
 
    
596
 
    @dbus.service.method(dbus.PROPERTIES_IFACE, in_signature=u"s",
597
 
                         out_signature=u"a{sv}")
598
 
    def GetAll(self, interface_name):
599
 
        """Standard D-Bus property GetAll() method, see D-Bus
600
 
        standard.
601
 
 
602
 
        Note: Will not include properties with access="write".
603
 
        """
604
 
        all = {}
605
 
        for name, prop in self._get_all_dbus_properties():
606
 
            if (interface_name
607
 
                and interface_name != prop._dbus_interface):
608
 
                # Interface non-empty but did not match
609
 
                continue
610
 
            # Ignore write-only properties
611
 
            if prop._dbus_access == u"write":
612
 
                continue
613
 
            value = prop()
614
 
            if not hasattr(value, u"variant_level"):
615
 
                all[name] = value
616
 
                continue
617
 
            all[name] = type(value)(value, variant_level=
618
 
                                    value.variant_level+1)
619
 
        return dbus.Dictionary(all, signature=u"sv")
620
 
    
621
 
    @dbus.service.method(dbus.INTROSPECTABLE_IFACE,
622
 
                         out_signature=u"s",
623
 
                         path_keyword='object_path',
624
 
                         connection_keyword='connection')
625
 
    def Introspect(self, object_path, connection):
626
 
        """Standard D-Bus method, overloaded to insert property tags.
627
 
        """
628
 
        xmlstring = dbus.service.Object.Introspect(self, object_path,
629
 
                                                   connection)
630
 
        try:
631
 
            document = xml.dom.minidom.parseString(xmlstring)
632
 
            def make_tag(document, name, prop):
633
 
                e = document.createElement(u"property")
634
 
                e.setAttribute(u"name", name)
635
 
                e.setAttribute(u"type", prop._dbus_signature)
636
 
                e.setAttribute(u"access", prop._dbus_access)
637
 
                return e
638
 
            for if_tag in document.getElementsByTagName(u"interface"):
639
 
                for tag in (make_tag(document, name, prop)
640
 
                            for name, prop
641
 
                            in self._get_all_dbus_properties()
642
 
                            if prop._dbus_interface
643
 
                            == if_tag.getAttribute(u"name")):
644
 
                    if_tag.appendChild(tag)
645
 
                # Add the names to the return values for the
646
 
                # "org.freedesktop.DBus.Properties" methods
647
 
                if (if_tag.getAttribute(u"name")
648
 
                    == u"org.freedesktop.DBus.Properties"):
649
 
                    for cn in if_tag.getElementsByTagName(u"method"):
650
 
                        if cn.getAttribute(u"name") == u"Get":
651
 
                            for arg in cn.getElementsByTagName(u"arg"):
652
 
                                if (arg.getAttribute(u"direction")
653
 
                                    == u"out"):
654
 
                                    arg.setAttribute(u"name", u"value")
655
 
                        elif cn.getAttribute(u"name") == u"GetAll":
656
 
                            for arg in cn.getElementsByTagName(u"arg"):
657
 
                                if (arg.getAttribute(u"direction")
658
 
                                    == u"out"):
659
 
                                    arg.setAttribute(u"name", u"props")
660
 
            xmlstring = document.toxml(u"utf-8")
661
 
            document.unlink()
662
 
        except (AttributeError, xml.dom.DOMException,
663
 
                xml.parsers.expat.ExpatError), error:
664
 
            logger.error(u"Failed to override Introspection method",
665
 
                         error)
666
 
        return xmlstring
667
 
 
668
 
 
669
 
class ClientDBus(Client, DBusObjectWithProperties):
 
433
    
 
434
    def still_valid(self):
 
435
        """Has the timeout not yet passed for this client?"""
 
436
        if not getattr(self, u"enabled", False):
 
437
            return False
 
438
        now = datetime.datetime.utcnow()
 
439
        if self.last_checked_ok is None:
 
440
            return now < (self.created + self.timeout)
 
441
        else:
 
442
            return now < (self.last_checked_ok + self.timeout)
 
443
 
 
444
 
 
445
class ClientDBus(Client, dbus.service.Object):
670
446
    """A Client class using D-Bus
671
447
    
672
448
    Attributes:
673
 
    dbus_object_path: dbus.ObjectPath
674
 
    bus: dbus.SystemBus()
 
449
    dbus_object_path: dbus.ObjectPath ; only set if self.use_dbus
675
450
    """
676
451
    # dbus.service.Object doesn't use super(), so we can't either.
677
452
    
678
 
    def __init__(self, bus = None, *args, **kwargs):
679
 
        self.bus = bus
 
453
    def __init__(self, *args, **kwargs):
680
454
        Client.__init__(self, *args, **kwargs)
681
455
        # Only now, when this client is initialized, can it show up on
682
456
        # the D-Bus
683
457
        self.dbus_object_path = (dbus.ObjectPath
684
458
                                 (u"/clients/"
685
459
                                  + self.name.replace(u".", u"_")))
686
 
        DBusObjectWithProperties.__init__(self, self.bus,
687
 
                                          self.dbus_object_path)
688
 
    
689
 
    @staticmethod
690
 
    def _datetime_to_dbus(dt, variant_level=0):
691
 
        """Convert a UTC datetime.datetime() to a D-Bus type."""
692
 
        return dbus.String(dt.isoformat(),
693
 
                           variant_level=variant_level)
694
 
    
 
460
        dbus.service.Object.__init__(self, bus,
 
461
                                     self.dbus_object_path)
695
462
    def enable(self):
696
463
        oldstate = getattr(self, u"enabled", False)
697
464
        r = Client.enable(self)
699
466
            # Emit D-Bus signals
700
467
            self.PropertyChanged(dbus.String(u"enabled"),
701
468
                                 dbus.Boolean(True, variant_level=1))
702
 
            self.PropertyChanged(
703
 
                dbus.String(u"last_enabled"),
704
 
                self._datetime_to_dbus(self.last_enabled,
705
 
                                       variant_level=1))
 
469
            self.PropertyChanged(dbus.String(u"last_enabled"),
 
470
                                 (_datetime_to_dbus(self.last_enabled,
 
471
                                                    variant_level=1)))
706
472
        return r
707
473
    
708
 
    def disable(self, quiet = False):
 
474
    def disable(self, signal = True):
709
475
        oldstate = getattr(self, u"enabled", False)
710
 
        r = Client.disable(self, quiet=quiet)
711
 
        if not quiet and oldstate != self.enabled:
 
476
        r = Client.disable(self)
 
477
        if signal and oldstate != self.enabled:
712
478
            # Emit D-Bus signal
713
479
            self.PropertyChanged(dbus.String(u"enabled"),
714
480
                                 dbus.Boolean(False, variant_level=1))
719
485
            self.remove_from_connection()
720
486
        except LookupError:
721
487
            pass
722
 
        if hasattr(DBusObjectWithProperties, u"__del__"):
723
 
            DBusObjectWithProperties.__del__(self, *args, **kwargs)
 
488
        if hasattr(dbus.service.Object, u"__del__"):
 
489
            dbus.service.Object.__del__(self, *args, **kwargs)
724
490
        Client.__del__(self, *args, **kwargs)
725
491
    
726
492
    def checker_callback(self, pid, condition, command,
750
516
        # Emit D-Bus signal
751
517
        self.PropertyChanged(
752
518
            dbus.String(u"last_checked_ok"),
753
 
            (self._datetime_to_dbus(self.last_checked_ok,
754
 
                                    variant_level=1)))
 
519
            (_datetime_to_dbus(self.last_checked_ok,
 
520
                               variant_level=1)))
755
521
        return r
756
522
    
757
523
    def start_checker(self, *args, **kwargs):
780
546
                                 dbus.Boolean(False, variant_level=1))
781
547
        return r
782
548
    
783
 
    ## D-Bus methods, signals & properties
 
549
    ## D-Bus methods & signals
784
550
    _interface = u"se.bsnet.fukt.Mandos.Client"
785
551
    
786
 
    ## Signals
 
552
    # CheckedOK - method
 
553
    @dbus.service.method(_interface)
 
554
    def CheckedOK(self):
 
555
        return self.checked_ok()
787
556
    
788
557
    # CheckerCompleted - signal
789
558
    @dbus.service.signal(_interface, signature=u"nxs")
797
566
        "D-Bus signal"
798
567
        pass
799
568
    
 
569
    # GetAllProperties - method
 
570
    @dbus.service.method(_interface, out_signature=u"a{sv}")
 
571
    def GetAllProperties(self):
 
572
        "D-Bus method"
 
573
        return dbus.Dictionary({
 
574
                dbus.String(u"name"):
 
575
                    dbus.String(self.name, variant_level=1),
 
576
                dbus.String(u"fingerprint"):
 
577
                    dbus.String(self.fingerprint, variant_level=1),
 
578
                dbus.String(u"host"):
 
579
                    dbus.String(self.host, variant_level=1),
 
580
                dbus.String(u"created"):
 
581
                    _datetime_to_dbus(self.created, variant_level=1),
 
582
                dbus.String(u"last_enabled"):
 
583
                    (_datetime_to_dbus(self.last_enabled,
 
584
                                       variant_level=1)
 
585
                     if self.last_enabled is not None
 
586
                     else dbus.Boolean(False, variant_level=1)),
 
587
                dbus.String(u"enabled"):
 
588
                    dbus.Boolean(self.enabled, variant_level=1),
 
589
                dbus.String(u"last_checked_ok"):
 
590
                    (_datetime_to_dbus(self.last_checked_ok,
 
591
                                       variant_level=1)
 
592
                     if self.last_checked_ok is not None
 
593
                     else dbus.Boolean (False, variant_level=1)),
 
594
                dbus.String(u"timeout"):
 
595
                    dbus.UInt64(self.timeout_milliseconds(),
 
596
                                variant_level=1),
 
597
                dbus.String(u"interval"):
 
598
                    dbus.UInt64(self.interval_milliseconds(),
 
599
                                variant_level=1),
 
600
                dbus.String(u"checker"):
 
601
                    dbus.String(self.checker_command,
 
602
                                variant_level=1),
 
603
                dbus.String(u"checker_running"):
 
604
                    dbus.Boolean(self.checker is not None,
 
605
                                 variant_level=1),
 
606
                dbus.String(u"object_path"):
 
607
                    dbus.ObjectPath(self.dbus_object_path,
 
608
                                    variant_level=1)
 
609
                }, signature=u"sv")
 
610
    
 
611
    # IsStillValid - method
 
612
    @dbus.service.method(_interface, out_signature=u"b")
 
613
    def IsStillValid(self):
 
614
        return self.still_valid()
 
615
    
800
616
    # PropertyChanged - signal
801
617
    @dbus.service.signal(_interface, signature=u"sv")
802
618
    def PropertyChanged(self, property, value):
803
619
        "D-Bus signal"
804
620
        pass
805
621
    
806
 
    # GotSecret - signal
 
622
    # ReceivedSecret - signal
807
623
    @dbus.service.signal(_interface)
808
 
    def GotSecret(self):
 
624
    def ReceivedSecret(self):
809
625
        "D-Bus signal"
810
626
        pass
811
627
    
815
631
        "D-Bus signal"
816
632
        pass
817
633
    
818
 
    ## Methods
819
 
    
820
 
    # CheckedOK - method
821
 
    @dbus.service.method(_interface)
822
 
    def CheckedOK(self):
823
 
        return self.checked_ok()
 
634
    # SetChecker - method
 
635
    @dbus.service.method(_interface, in_signature=u"s")
 
636
    def SetChecker(self, checker):
 
637
        "D-Bus setter method"
 
638
        self.checker_command = checker
 
639
        # Emit D-Bus signal
 
640
        self.PropertyChanged(dbus.String(u"checker"),
 
641
                             dbus.String(self.checker_command,
 
642
                                         variant_level=1))
 
643
    
 
644
    # SetHost - method
 
645
    @dbus.service.method(_interface, in_signature=u"s")
 
646
    def SetHost(self, host):
 
647
        "D-Bus setter method"
 
648
        self.host = host
 
649
        # Emit D-Bus signal
 
650
        self.PropertyChanged(dbus.String(u"host"),
 
651
                             dbus.String(self.host, variant_level=1))
 
652
    
 
653
    # SetInterval - method
 
654
    @dbus.service.method(_interface, in_signature=u"t")
 
655
    def SetInterval(self, milliseconds):
 
656
        self.interval = datetime.timedelta(0, 0, 0, milliseconds)
 
657
        # Emit D-Bus signal
 
658
        self.PropertyChanged(dbus.String(u"interval"),
 
659
                             (dbus.UInt64(self.interval_milliseconds(),
 
660
                                          variant_level=1)))
 
661
    
 
662
    # SetSecret - method
 
663
    @dbus.service.method(_interface, in_signature=u"ay",
 
664
                         byte_arrays=True)
 
665
    def SetSecret(self, secret):
 
666
        "D-Bus setter method"
 
667
        self.secret = str(secret)
 
668
    
 
669
    # SetTimeout - method
 
670
    @dbus.service.method(_interface, in_signature=u"t")
 
671
    def SetTimeout(self, milliseconds):
 
672
        self.timeout = datetime.timedelta(0, 0, 0, milliseconds)
 
673
        # Emit D-Bus signal
 
674
        self.PropertyChanged(dbus.String(u"timeout"),
 
675
                             (dbus.UInt64(self.timeout_milliseconds(),
 
676
                                          variant_level=1)))
824
677
    
825
678
    # Enable - method
826
679
    @dbus.service.method(_interface)
845
698
    def StopChecker(self):
846
699
        self.stop_checker()
847
700
    
848
 
    ## Properties
849
 
    
850
 
    # name - property
851
 
    @dbus_service_property(_interface, signature=u"s", access=u"read")
852
 
    def name_dbus_property(self):
853
 
        return dbus.String(self.name)
854
 
    
855
 
    # fingerprint - property
856
 
    @dbus_service_property(_interface, signature=u"s", access=u"read")
857
 
    def fingerprint_dbus_property(self):
858
 
        return dbus.String(self.fingerprint)
859
 
    
860
 
    # host - property
861
 
    @dbus_service_property(_interface, signature=u"s",
862
 
                           access=u"readwrite")
863
 
    def host_dbus_property(self, value=None):
864
 
        if value is None:       # get
865
 
            return dbus.String(self.host)
866
 
        self.host = value
867
 
        # Emit D-Bus signal
868
 
        self.PropertyChanged(dbus.String(u"host"),
869
 
                             dbus.String(value, variant_level=1))
870
 
    
871
 
    # created - property
872
 
    @dbus_service_property(_interface, signature=u"s", access=u"read")
873
 
    def created_dbus_property(self):
874
 
        return dbus.String(self._datetime_to_dbus(self.created))
875
 
    
876
 
    # last_enabled - property
877
 
    @dbus_service_property(_interface, signature=u"s", access=u"read")
878
 
    def last_enabled_dbus_property(self):
879
 
        if self.last_enabled is None:
880
 
            return dbus.String(u"")
881
 
        return dbus.String(self._datetime_to_dbus(self.last_enabled))
882
 
    
883
 
    # enabled - property
884
 
    @dbus_service_property(_interface, signature=u"b",
885
 
                           access=u"readwrite")
886
 
    def enabled_dbus_property(self, value=None):
887
 
        if value is None:       # get
888
 
            return dbus.Boolean(self.enabled)
889
 
        if value:
890
 
            self.enable()
891
 
        else:
892
 
            self.disable()
893
 
    
894
 
    # last_checked_ok - property
895
 
    @dbus_service_property(_interface, signature=u"s",
896
 
                           access=u"readwrite")
897
 
    def last_checked_ok_dbus_property(self, value=None):
898
 
        if value is not None:
899
 
            self.checked_ok()
900
 
            return
901
 
        if self.last_checked_ok is None:
902
 
            return dbus.String(u"")
903
 
        return dbus.String(self._datetime_to_dbus(self
904
 
                                                  .last_checked_ok))
905
 
    
906
 
    # timeout - property
907
 
    @dbus_service_property(_interface, signature=u"t",
908
 
                           access=u"readwrite")
909
 
    def timeout_dbus_property(self, value=None):
910
 
        if value is None:       # get
911
 
            return dbus.UInt64(self.timeout_milliseconds())
912
 
        self.timeout = datetime.timedelta(0, 0, 0, value)
913
 
        # Emit D-Bus signal
914
 
        self.PropertyChanged(dbus.String(u"timeout"),
915
 
                             dbus.UInt64(value, variant_level=1))
916
 
        if getattr(self, u"disable_initiator_tag", None) is None:
917
 
            return
918
 
        # Reschedule timeout
919
 
        gobject.source_remove(self.disable_initiator_tag)
920
 
        self.disable_initiator_tag = None
921
 
        time_to_die = (self.
922
 
                       _timedelta_to_milliseconds((self
923
 
                                                   .last_checked_ok
924
 
                                                   + self.timeout)
925
 
                                                  - datetime.datetime
926
 
                                                  .utcnow()))
927
 
        if time_to_die <= 0:
928
 
            # The timeout has passed
929
 
            self.disable()
930
 
        else:
931
 
            self.disable_initiator_tag = (gobject.timeout_add
932
 
                                          (time_to_die, self.disable))
933
 
    
934
 
    # interval - property
935
 
    @dbus_service_property(_interface, signature=u"t",
936
 
                           access=u"readwrite")
937
 
    def interval_dbus_property(self, value=None):
938
 
        if value is None:       # get
939
 
            return dbus.UInt64(self.interval_milliseconds())
940
 
        self.interval = datetime.timedelta(0, 0, 0, value)
941
 
        # Emit D-Bus signal
942
 
        self.PropertyChanged(dbus.String(u"interval"),
943
 
                             dbus.UInt64(value, variant_level=1))
944
 
        if getattr(self, u"checker_initiator_tag", None) is None:
945
 
            return
946
 
        # Reschedule checker run
947
 
        gobject.source_remove(self.checker_initiator_tag)
948
 
        self.checker_initiator_tag = (gobject.timeout_add
949
 
                                      (value, self.start_checker))
950
 
        self.start_checker()    # Start one now, too
951
 
 
952
 
    # checker - property
953
 
    @dbus_service_property(_interface, signature=u"s",
954
 
                           access=u"readwrite")
955
 
    def checker_dbus_property(self, value=None):
956
 
        if value is None:       # get
957
 
            return dbus.String(self.checker_command)
958
 
        self.checker_command = value
959
 
        # Emit D-Bus signal
960
 
        self.PropertyChanged(dbus.String(u"checker"),
961
 
                             dbus.String(self.checker_command,
962
 
                                         variant_level=1))
963
 
    
964
 
    # checker_running - property
965
 
    @dbus_service_property(_interface, signature=u"b",
966
 
                           access=u"readwrite")
967
 
    def checker_running_dbus_property(self, value=None):
968
 
        if value is None:       # get
969
 
            return dbus.Boolean(self.checker is not None)
970
 
        if value:
971
 
            self.start_checker()
972
 
        else:
973
 
            self.stop_checker()
974
 
    
975
 
    # object_path - property
976
 
    @dbus_service_property(_interface, signature=u"o", access=u"read")
977
 
    def object_path_dbus_property(self):
978
 
        return self.dbus_object_path # is already a dbus.ObjectPath
979
 
    
980
 
    # secret = property
981
 
    @dbus_service_property(_interface, signature=u"ay",
982
 
                           access=u"write", byte_arrays=True)
983
 
    def secret_dbus_property(self, value):
984
 
        self.secret = str(value)
985
 
    
986
701
    del _interface
987
702
 
988
703
 
995
710
    def handle(self):
996
711
        logger.info(u"TCP connection from: %s",
997
712
                    unicode(self.client_address))
998
 
        logger.debug(u"IPC Pipe FD: %d",
999
 
                     self.server.child_pipe[1].fileno())
 
713
        logger.debug(u"IPC Pipe FD: %d", self.server.pipe[1])
1000
714
        # Open IPC pipe to parent process
1001
 
        with contextlib.nested(self.server.child_pipe[1],
1002
 
                               self.server.parent_pipe[0]
1003
 
                               ) as (ipc, ipc_return):
 
715
        with closing(os.fdopen(self.server.pipe[1], u"w", 1)) as ipc:
1004
716
            session = (gnutls.connection
1005
717
                       .ClientSession(self.request,
1006
718
                                      gnutls.connection
1041
753
                return
1042
754
            logger.debug(u"Handshake succeeded")
1043
755
            try:
1044
 
                try:
1045
 
                    fpr = self.fingerprint(self.peer_certificate
1046
 
                                           (session))
1047
 
                except (TypeError, gnutls.errors.GNUTLSError), error:
1048
 
                    logger.warning(u"Bad certificate: %s", error)
1049
 
                    return
1050
 
                logger.debug(u"Fingerprint: %s", fpr)
1051
 
 
1052
 
                for c in self.server.clients:
1053
 
                    if c.fingerprint == fpr:
1054
 
                        client = c
1055
 
                        break
1056
 
                else:
1057
 
                    ipc.write(u"NOTFOUND %s %s\n"
1058
 
                              % (fpr, unicode(self.client_address)))
1059
 
                    return
1060
 
                # Have to check if client.enabled, since it is
1061
 
                # possible that the client was disabled since the
1062
 
                # GnuTLS session was established.
1063
 
                ipc.write(u"GETATTR enabled %s\n" % fpr)
1064
 
                enabled = pickle.load(ipc_return)
1065
 
                if not enabled:
1066
 
                    ipc.write(u"DISABLED %s\n" % client.name)
1067
 
                    return
1068
 
                ipc.write(u"SENDING %s\n" % client.name)
1069
 
                sent_size = 0
1070
 
                while sent_size < len(client.secret):
1071
 
                    sent = session.send(client.secret[sent_size:])
1072
 
                    logger.debug(u"Sent: %d, remaining: %d",
1073
 
                                 sent, len(client.secret)
1074
 
                                 - (sent_size + sent))
1075
 
                    sent_size += sent
1076
 
            finally:
1077
 
                session.bye()
 
756
                fpr = self.fingerprint(self.peer_certificate(session))
 
757
            except (TypeError, gnutls.errors.GNUTLSError), error:
 
758
                logger.warning(u"Bad certificate: %s", error)
 
759
                session.bye()
 
760
                return
 
761
            logger.debug(u"Fingerprint: %s", fpr)
 
762
            
 
763
            for c in self.server.clients:
 
764
                if c.fingerprint == fpr:
 
765
                    client = c
 
766
                    break
 
767
            else:
 
768
                ipc.write(u"NOTFOUND %s\n" % fpr)
 
769
                session.bye()
 
770
                return
 
771
            # Have to check if client.still_valid(), since it is
 
772
            # possible that the client timed out while establishing
 
773
            # the GnuTLS session.
 
774
            if not client.still_valid():
 
775
                ipc.write(u"INVALID %s\n" % client.name)
 
776
                session.bye()
 
777
                return
 
778
            ipc.write(u"SENDING %s\n" % client.name)
 
779
            sent_size = 0
 
780
            while sent_size < len(client.secret):
 
781
                sent = session.send(client.secret[sent_size:])
 
782
                logger.debug(u"Sent: %d, remaining: %d",
 
783
                             sent, len(client.secret)
 
784
                             - (sent_size + sent))
 
785
                sent_size += sent
 
786
            session.bye()
1078
787
    
1079
788
    @staticmethod
1080
789
    def peer_certificate(session):
1140
849
        return hex_fpr
1141
850
 
1142
851
 
1143
 
class ForkingMixInWithPipes(socketserver.ForkingMixIn, object):
1144
 
    """Like socketserver.ForkingMixIn, but also pass a pipe pair."""
 
852
class ForkingMixInWithPipe(socketserver.ForkingMixIn, object):
 
853
    """Like socketserver.ForkingMixIn, but also pass a pipe.
 
854
    
 
855
    Assumes a gobject.MainLoop event loop.
 
856
    """
1145
857
    def process_request(self, request, client_address):
1146
858
        """Overrides and wraps the original process_request().
1147
859
        
1148
 
        This function creates a new pipe in self.pipe
 
860
        This function creates a new pipe in self.pipe 
1149
861
        """
1150
 
        # Child writes to child_pipe
1151
 
        self.child_pipe = map(os.fdopen, os.pipe(), u"rw", (1, 0))
1152
 
        # Parent writes to parent_pipe
1153
 
        self.parent_pipe = map(os.fdopen, os.pipe(), u"rw", (1, 0))
1154
 
        super(ForkingMixInWithPipes,
 
862
        self.pipe = os.pipe()
 
863
        super(ForkingMixInWithPipe,
1155
864
              self).process_request(request, client_address)
1156
 
        # Close unused ends for parent
1157
 
        self.parent_pipe[0].close() # close read end
1158
 
        self.child_pipe[1].close()  # close write end
1159
 
        self.add_pipe_fds(self.child_pipe[0], self.parent_pipe[1])
1160
 
    def add_pipe_fds(self, child_pipe_fd, parent_pipe_fd):
 
865
        os.close(self.pipe[1])  # close write end
 
866
        # Call "handle_ipc" for both data and EOF events
 
867
        gobject.io_add_watch(self.pipe[0],
 
868
                             gobject.IO_IN | gobject.IO_HUP,
 
869
                             self.handle_ipc)
 
870
    def handle_ipc(source, condition):
1161
871
        """Dummy function; override as necessary"""
1162
 
        child_pipe_fd.close()
1163
 
        parent_pipe_fd.close()
1164
 
 
1165
 
 
1166
 
class IPv6_TCPServer(ForkingMixInWithPipes,
 
872
        os.close(source)
 
873
        return False
 
874
 
 
875
 
 
876
class IPv6_TCPServer(ForkingMixInWithPipe,
1167
877
                     socketserver.TCPServer, object):
1168
878
    """IPv6-capable TCP server.  Accepts 'None' as address and/or port
1169
879
    
1171
881
        enabled:        Boolean; whether this server is activated yet
1172
882
        interface:      None or a network interface name (string)
1173
883
        use_ipv6:       Boolean; to use IPv6 or not
 
884
        ----
 
885
        clients:        set of Client objects
 
886
        gnutls_priority GnuTLS priority string
 
887
        use_dbus:       Boolean; to emit D-Bus signals or not
1174
888
    """
1175
889
    def __init__(self, server_address, RequestHandlerClass,
1176
 
                 interface=None, use_ipv6=True):
 
890
                 interface=None, use_ipv6=True, clients=None,
 
891
                 gnutls_priority=None, use_dbus=True):
 
892
        self.enabled = False
1177
893
        self.interface = interface
1178
894
        if use_ipv6:
1179
895
            self.address_family = socket.AF_INET6
 
896
        self.clients = clients
 
897
        self.use_dbus = use_dbus
 
898
        self.gnutls_priority = gnutls_priority
1180
899
        socketserver.TCPServer.__init__(self, server_address,
1181
900
                                        RequestHandlerClass)
1182
901
    def server_bind(self):
1184
903
        to bind to an interface if one was specified, and also NOT to
1185
904
        bind to an address or port if they were not specified."""
1186
905
        if self.interface is not None:
1187
 
            if SO_BINDTODEVICE is None:
1188
 
                logger.error(u"SO_BINDTODEVICE does not exist;"
1189
 
                             u" cannot bind to interface %s",
1190
 
                             self.interface)
1191
 
            else:
1192
 
                try:
1193
 
                    self.socket.setsockopt(socket.SOL_SOCKET,
1194
 
                                           SO_BINDTODEVICE,
1195
 
                                           str(self.interface
1196
 
                                               + u'\0'))
1197
 
                except socket.error, error:
1198
 
                    if error[0] == errno.EPERM:
1199
 
                        logger.error(u"No permission to"
1200
 
                                     u" bind to interface %s",
1201
 
                                     self.interface)
1202
 
                    elif error[0] == errno.ENOPROTOOPT:
1203
 
                        logger.error(u"SO_BINDTODEVICE not available;"
1204
 
                                     u" cannot bind to interface %s",
1205
 
                                     self.interface)
1206
 
                    else:
1207
 
                        raise
 
906
            try:
 
907
                self.socket.setsockopt(socket.SOL_SOCKET,
 
908
                                       SO_BINDTODEVICE,
 
909
                                       str(self.interface + u'\0'))
 
910
            except socket.error, error:
 
911
                if error[0] == errno.EPERM:
 
912
                    logger.error(u"No permission to"
 
913
                                 u" bind to interface %s",
 
914
                                 self.interface)
 
915
                else:
 
916
                    raise
1208
917
        # Only bind(2) the socket if we really need to.
1209
918
        if self.server_address[0] or self.server_address[1]:
1210
919
            if not self.server_address[0]:
1224
933
#                                            if_nametoindex
1225
934
#                                            (self.interface))
1226
935
            return socketserver.TCPServer.server_bind(self)
1227
 
 
1228
 
 
1229
 
class MandosServer(IPv6_TCPServer):
1230
 
    """Mandos server.
1231
 
    
1232
 
    Attributes:
1233
 
        clients:        set of Client objects
1234
 
        gnutls_priority GnuTLS priority string
1235
 
        use_dbus:       Boolean; to emit D-Bus signals or not
1236
 
    
1237
 
    Assumes a gobject.MainLoop event loop.
1238
 
    """
1239
 
    def __init__(self, server_address, RequestHandlerClass,
1240
 
                 interface=None, use_ipv6=True, clients=None,
1241
 
                 gnutls_priority=None, use_dbus=True):
1242
 
        self.enabled = False
1243
 
        self.clients = clients
1244
 
        if self.clients is None:
1245
 
            self.clients = set()
1246
 
        self.use_dbus = use_dbus
1247
 
        self.gnutls_priority = gnutls_priority
1248
 
        IPv6_TCPServer.__init__(self, server_address,
1249
 
                                RequestHandlerClass,
1250
 
                                interface = interface,
1251
 
                                use_ipv6 = use_ipv6)
1252
936
    def server_activate(self):
1253
937
        if self.enabled:
1254
938
            return socketserver.TCPServer.server_activate(self)
1255
939
    def enable(self):
1256
940
        self.enabled = True
1257
 
    def add_pipe_fds(self, child_pipe_fd, parent_pipe_fd):
1258
 
        # Call "handle_ipc" for both data and EOF events
1259
 
        gobject.io_add_watch(child_pipe_fd.fileno(),
1260
 
                             gobject.IO_IN | gobject.IO_HUP,
1261
 
                             functools.partial(self.handle_ipc,
1262
 
                                               reply = parent_pipe_fd,
1263
 
                                               sender= child_pipe_fd))
1264
 
    def handle_ipc(self, source, condition, reply=None, sender=None):
 
941
    def handle_ipc(self, source, condition, file_objects={}):
1265
942
        condition_names = {
1266
943
            gobject.IO_IN: u"IN",   # There is data to read.
1267
944
            gobject.IO_OUT: u"OUT", # Data can be written (without
1279
956
        logger.debug(u"Handling IPC: FD = %d, condition = %s", source,
1280
957
                     conditions_string)
1281
958
        
 
959
        # Turn the pipe file descriptor into a Python file object
 
960
        if source not in file_objects:
 
961
            file_objects[source] = os.fdopen(source, u"r", 1)
 
962
        
1282
963
        # Read a line from the file object
1283
 
        cmdline = sender.readline()
 
964
        cmdline = file_objects[source].readline()
1284
965
        if not cmdline:             # Empty line means end of file
1285
 
            # close the IPC pipes
1286
 
            sender.close()
1287
 
            reply.close()
 
966
            # close the IPC pipe
 
967
            file_objects[source].close()
 
968
            del file_objects[source]
1288
969
            
1289
970
            # Stop calling this function
1290
971
            return False
1295
976
        cmd, args = cmdline.rstrip(u"\r\n").split(None, 1)
1296
977
        
1297
978
        if cmd == u"NOTFOUND":
1298
 
            fpr, address = args.split(None, 1)
1299
 
            logger.warning(u"Client not found for fingerprint: %s, ad"
1300
 
                           u"dress: %s", fpr, address)
 
979
            logger.warning(u"Client not found for fingerprint: %s",
 
980
                           args)
1301
981
            if self.use_dbus:
1302
982
                # Emit D-Bus signal
1303
 
                mandos_dbus_service.ClientNotFound(fpr, address)
1304
 
        elif cmd == u"DISABLED":
 
983
                mandos_dbus_service.ClientNotFound(args)
 
984
        elif cmd == u"INVALID":
1305
985
            for client in self.clients:
1306
986
                if client.name == args:
1307
 
                    logger.warning(u"Client %s is disabled", args)
 
987
                    logger.warning(u"Client %s is invalid", args)
1308
988
                    if self.use_dbus:
1309
989
                        # Emit D-Bus signal
1310
990
                        client.Rejected()
1311
991
                    break
1312
992
            else:
1313
 
                logger.error(u"Unknown client %s is disabled", args)
 
993
                logger.error(u"Unknown client %s is invalid", args)
1314
994
        elif cmd == u"SENDING":
1315
995
            for client in self.clients:
1316
996
                if client.name == args:
1318
998
                    client.checked_ok()
1319
999
                    if self.use_dbus:
1320
1000
                        # Emit D-Bus signal
1321
 
                        client.GotSecret()
 
1001
                        client.ReceivedSecret()
1322
1002
                    break
1323
1003
            else:
1324
1004
                logger.error(u"Sending secret to unknown client %s",
1325
1005
                             args)
1326
 
        elif cmd == u"GETATTR":
1327
 
            attr_name, fpr = args.split(None, 1)
1328
 
            for client in self.clients:
1329
 
                if client.fingerprint == fpr:
1330
 
                    attr_value = getattr(client, attr_name, None)
1331
 
                    logger.debug("IPC reply: %r", attr_value)
1332
 
                    pickle.dump(attr_value, reply)
1333
 
                    break
1334
 
            else:
1335
 
                logger.error(u"Client %s on address %s requesting "
1336
 
                             u"attribute %s not found", fpr, address,
1337
 
                             attr_name)
1338
 
                pickle.dump(None, reply)
1339
1006
        else:
1340
1007
            logger.error(u"Unknown IPC command: %r", cmdline)
1341
1008
        
1375
1042
            elif suffix == u"w":
1376
1043
                delta = datetime.timedelta(0, 0, 0, 0, 0, 0, value)
1377
1044
            else:
1378
 
                raise ValueError(u"Unknown suffix %r" % suffix)
1379
 
        except (ValueError, IndexError), e:
1380
 
            raise ValueError(e.message)
 
1045
                raise ValueError
 
1046
        except (ValueError, IndexError):
 
1047
            raise ValueError
1381
1048
        timevalue += delta
1382
1049
    return timevalue
1383
1050
 
1384
1051
 
 
1052
def server_state_changed(state):
 
1053
    """Derived from the Avahi example code"""
 
1054
    if state == avahi.SERVER_COLLISION:
 
1055
        logger.error(u"Zeroconf server name collision")
 
1056
        service.remove()
 
1057
    elif state == avahi.SERVER_RUNNING:
 
1058
        service.add()
 
1059
 
 
1060
 
 
1061
def entry_group_state_changed(state, error):
 
1062
    """Derived from the Avahi example code"""
 
1063
    logger.debug(u"Avahi state change: %i", state)
 
1064
    
 
1065
    if state == avahi.ENTRY_GROUP_ESTABLISHED:
 
1066
        logger.debug(u"Zeroconf service established.")
 
1067
    elif state == avahi.ENTRY_GROUP_COLLISION:
 
1068
        logger.warning(u"Zeroconf service name collision.")
 
1069
        service.rename()
 
1070
    elif state == avahi.ENTRY_GROUP_FAILURE:
 
1071
        logger.critical(u"Avahi: Error in group state changed %s",
 
1072
                        unicode(error))
 
1073
        raise AvahiGroupError(u"State changed: %s" % unicode(error))
 
1074
 
1385
1075
def if_nametoindex(interface):
1386
1076
    """Call the C function if_nametoindex(), or equivalent
1387
1077
    
1396
1086
        def if_nametoindex(interface):
1397
1087
            "Get an interface index the hard way, i.e. using fcntl()"
1398
1088
            SIOCGIFINDEX = 0x8933  # From /usr/include/linux/sockios.h
1399
 
            with contextlib.closing(socket.socket()) as s:
 
1089
            with closing(socket.socket()) as s:
1400
1090
                ifreq = fcntl.ioctl(s, SIOCGIFINDEX,
1401
1091
                                    struct.pack(str(u"16s16x"),
1402
1092
                                                interface))
1422
1112
        null = os.open(os.path.devnull, os.O_NOCTTY | os.O_RDWR)
1423
1113
        if not stat.S_ISCHR(os.fstat(null).st_mode):
1424
1114
            raise OSError(errno.ENODEV,
1425
 
                          u"%s not a character device"
1426
 
                          % os.path.devnull)
 
1115
                          u"/dev/null not a character device")
1427
1116
        os.dup2(null, sys.stdin.fileno())
1428
1117
        os.dup2(null, sys.stdout.fileno())
1429
1118
        os.dup2(null, sys.stderr.fileno())
1433
1122
 
1434
1123
def main():
1435
1124
    
1436
 
    ##################################################################
 
1125
    ######################################################################
1437
1126
    # Parsing of options, both command line and config file
1438
1127
    
1439
1128
    parser = optparse.OptionParser(version = "%%prog %s" % version)
1541
1230
    global mandos_dbus_service
1542
1231
    mandos_dbus_service = None
1543
1232
    
1544
 
    tcp_server = MandosServer((server_settings[u"address"],
1545
 
                               server_settings[u"port"]),
1546
 
                              ClientHandler,
1547
 
                              interface=server_settings[u"interface"],
1548
 
                              use_ipv6=use_ipv6,
1549
 
                              gnutls_priority=
1550
 
                              server_settings[u"priority"],
1551
 
                              use_dbus=use_dbus)
 
1233
    clients = set()
 
1234
    tcp_server = IPv6_TCPServer((server_settings[u"address"],
 
1235
                                 server_settings[u"port"]),
 
1236
                                ClientHandler,
 
1237
                                interface=
 
1238
                                server_settings[u"interface"],
 
1239
                                use_ipv6=use_ipv6,
 
1240
                                clients=clients,
 
1241
                                gnutls_priority=
 
1242
                                server_settings[u"priority"],
 
1243
                                use_dbus=use_dbus)
1552
1244
    pidfilename = u"/var/run/mandos.pid"
1553
1245
    try:
1554
1246
        pidfile = open(pidfilename, u"w")
1589
1281
        (gnutls.library.functions
1590
1282
         .gnutls_global_set_log_function(debug_gnutls))
1591
1283
    
 
1284
    global service
 
1285
    protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
 
1286
    service = AvahiService(name = server_settings[u"servicename"],
 
1287
                           servicetype = u"_mandos._tcp",
 
1288
                           protocol = protocol)
 
1289
    if server_settings["interface"]:
 
1290
        service.interface = (if_nametoindex
 
1291
                             (str(server_settings[u"interface"])))
 
1292
    
1592
1293
    global main_loop
 
1294
    global bus
 
1295
    global server
1593
1296
    # From the Avahi example code
1594
1297
    DBusGMainLoop(set_as_default=True )
1595
1298
    main_loop = gobject.MainLoop()
1596
1299
    bus = dbus.SystemBus()
 
1300
    server = dbus.Interface(bus.get_object(avahi.DBUS_NAME,
 
1301
                                           avahi.DBUS_PATH_SERVER),
 
1302
                            avahi.DBUS_INTERFACE_SERVER)
1597
1303
    # End of Avahi example code
1598
1304
    if use_dbus:
1599
 
        try:
1600
 
            bus_name = dbus.service.BusName(u"se.bsnet.fukt.Mandos",
1601
 
                                            bus, do_not_queue=True)
1602
 
        except dbus.exceptions.NameExistsException, e:
1603
 
            logger.error(unicode(e) + u", disabling D-Bus")
1604
 
            use_dbus = False
1605
 
            server_settings[u"use_dbus"] = False
1606
 
            tcp_server.use_dbus = False
1607
 
    protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
1608
 
    service = AvahiService(name = server_settings[u"servicename"],
1609
 
                           servicetype = u"_mandos._tcp",
1610
 
                           protocol = protocol, bus = bus)
1611
 
    if server_settings["interface"]:
1612
 
        service.interface = (if_nametoindex
1613
 
                             (str(server_settings[u"interface"])))
 
1305
        bus_name = dbus.service.BusName(u"se.bsnet.fukt.Mandos", bus)
1614
1306
    
1615
1307
    client_class = Client
1616
1308
    if use_dbus:
1617
 
        client_class = functools.partial(ClientDBus, bus = bus)
1618
 
    tcp_server.clients.update(set(
 
1309
        client_class = ClientDBus
 
1310
    clients.update(set(
1619
1311
            client_class(name = section,
1620
1312
                         config= dict(client_config.items(section)))
1621
1313
            for section in client_config.sections()))
1622
 
    if not tcp_server.clients:
 
1314
    if not clients:
1623
1315
        logger.warning(u"No clients defined")
1624
1316
    
1625
1317
    if debug:
1635
1327
        daemon()
1636
1328
    
1637
1329
    try:
1638
 
        with pidfile:
 
1330
        with closing(pidfile):
1639
1331
            pid = os.getpid()
1640
1332
            pidfile.write(str(pid) + "\n")
1641
1333
        del pidfile
1647
1339
        pass
1648
1340
    del pidfilename
1649
1341
    
 
1342
    def cleanup():
 
1343
        "Cleanup function; run on exit"
 
1344
        global group
 
1345
        # From the Avahi example code
 
1346
        if not group is None:
 
1347
            group.Free()
 
1348
            group = None
 
1349
        # End of Avahi example code
 
1350
        
 
1351
        while clients:
 
1352
            client = clients.pop()
 
1353
            client.disable_hook = None
 
1354
            client.disable()
 
1355
    
 
1356
    atexit.register(cleanup)
 
1357
    
1650
1358
    if not debug:
1651
1359
        signal.signal(signal.SIGINT, signal.SIG_IGN)
1652
1360
    signal.signal(signal.SIGHUP, lambda signum, frame: sys.exit())
1659
1367
                dbus.service.Object.__init__(self, bus, u"/")
1660
1368
            _interface = u"se.bsnet.fukt.Mandos"
1661
1369
            
1662
 
            @dbus.service.signal(_interface, signature=u"o")
1663
 
            def ClientAdded(self, objpath):
 
1370
            @dbus.service.signal(_interface, signature=u"oa{sv}")
 
1371
            def ClientAdded(self, objpath, properties):
1664
1372
                "D-Bus signal"
1665
1373
                pass
1666
1374
            
1667
 
            @dbus.service.signal(_interface, signature=u"ss")
1668
 
            def ClientNotFound(self, fingerprint, address):
 
1375
            @dbus.service.signal(_interface, signature=u"s")
 
1376
            def ClientNotFound(self, fingerprint):
1669
1377
                "D-Bus signal"
1670
1378
                pass
1671
1379
            
1677
1385
            @dbus.service.method(_interface, out_signature=u"ao")
1678
1386
            def GetAllClients(self):
1679
1387
                "D-Bus method"
1680
 
                return dbus.Array(c.dbus_object_path
1681
 
                                  for c in tcp_server.clients)
 
1388
                return dbus.Array(c.dbus_object_path for c in clients)
1682
1389
            
1683
1390
            @dbus.service.method(_interface,
1684
1391
                                 out_signature=u"a{oa{sv}}")
1685
1392
            def GetAllClientsWithProperties(self):
1686
1393
                "D-Bus method"
1687
1394
                return dbus.Dictionary(
1688
 
                    ((c.dbus_object_path, c.GetAll(u""))
1689
 
                     for c in tcp_server.clients),
 
1395
                    ((c.dbus_object_path, c.GetAllProperties())
 
1396
                     for c in clients),
1690
1397
                    signature=u"oa{sv}")
1691
1398
            
1692
1399
            @dbus.service.method(_interface, in_signature=u"o")
1693
1400
            def RemoveClient(self, object_path):
1694
1401
                "D-Bus method"
1695
 
                for c in tcp_server.clients:
 
1402
                for c in clients:
1696
1403
                    if c.dbus_object_path == object_path:
1697
 
                        tcp_server.clients.remove(c)
 
1404
                        clients.remove(c)
1698
1405
                        c.remove_from_connection()
1699
1406
                        # Don't signal anything except ClientRemoved
1700
 
                        c.disable(quiet=True)
 
1407
                        c.disable(signal=False)
1701
1408
                        # Emit D-Bus signal
1702
1409
                        self.ClientRemoved(object_path, c.name)
1703
1410
                        return
1704
 
                raise KeyError(object_path)
 
1411
                raise KeyError
1705
1412
            
1706
1413
            del _interface
1707
1414
        
1708
1415
        mandos_dbus_service = MandosDBusService()
1709
1416
    
1710
 
    def cleanup():
1711
 
        "Cleanup function; run on exit"
1712
 
        service.cleanup()
1713
 
        
1714
 
        while tcp_server.clients:
1715
 
            client = tcp_server.clients.pop()
1716
 
            if use_dbus:
1717
 
                client.remove_from_connection()
1718
 
            client.disable_hook = None
1719
 
            # Don't signal anything except ClientRemoved
1720
 
            client.disable(quiet=True)
1721
 
            if use_dbus:
1722
 
                # Emit D-Bus signal
1723
 
                mandos_dbus_service.ClientRemoved(client.dbus_object_path,
1724
 
                                                  client.name)
1725
 
    
1726
 
    atexit.register(cleanup)
1727
 
    
1728
 
    for client in tcp_server.clients:
 
1417
    for client in clients:
1729
1418
        if use_dbus:
1730
1419
            # Emit D-Bus signal
1731
 
            mandos_dbus_service.ClientAdded(client.dbus_object_path)
 
1420
            mandos_dbus_service.ClientAdded(client.dbus_object_path,
 
1421
                                            client.GetAllProperties())
1732
1422
        client.enable()
1733
1423
    
1734
1424
    tcp_server.enable()
1748
1438
    
1749
1439
    try:
1750
1440
        # From the Avahi example code
 
1441
        server.connect_to_signal(u"StateChanged", server_state_changed)
1751
1442
        try:
1752
 
            service.activate()
 
1443
            server_state_changed(server.GetState())
1753
1444
        except dbus.exceptions.DBusException, error:
1754
1445
            logger.critical(u"DBusException: %s", error)
1755
 
            cleanup()
1756
1446
            sys.exit(1)
1757
1447
        # End of Avahi example code
1758
1448
        
1765
1455
        main_loop.run()
1766
1456
    except AvahiError, error:
1767
1457
        logger.critical(u"AvahiError: %s", error)
1768
 
        cleanup()
1769
1458
        sys.exit(1)
1770
1459
    except KeyboardInterrupt:
1771
1460
        if debug:
1772
1461
            print >> sys.stderr
1773
1462
        logger.debug(u"Server received KeyboardInterrupt")
1774
1463
    logger.debug(u"Server exiting")
1775
 
    # Must run before the D-Bus bus name gets deregistered
1776
 
    cleanup()
1777
1464
 
1778
1465
if __name__ == '__main__':
1779
1466
    main()