/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 at bsnet
  • Date: 2010-08-10 19:08:24 UTC
  • mto: This revision was merged to the branch mainline in revision 419.
  • Revision ID: teddy@fukt.bsnet.se-20100810190824-5yquozxy4kh6py3f
* plugins.d/mandos-client.c: An empty interface name now means to
                             autodetect an interface; to specify no
                             particular interface, use "none".
  (sys_class_net): New global variable for the "/sys/class/net" path.
  (good_interface): New function to determine the suitability of an
                    interface.  Used by a scandir() call in main().
  (main): Changed default value for "interface" to the empty string.
          Moved "connect_to" to be a global variable.  Only take down
          and up interface if its name is not "none".
* plugins.d/mandos-client.xml (OPTIONS): Update documentation for the
                                         "--interface" option.

Show diffs side-by-side

added added

removed removed

Lines of Context:
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
61
import functools
62
 
import cPickle as pickle
63
 
import multiprocessing
64
62
 
65
63
import dbus
66
64
import dbus.service
69
67
from dbus.mainloop.glib import DBusGMainLoop
70
68
import ctypes
71
69
import ctypes.util
72
 
import xml.dom.minidom
73
 
import inspect
74
70
 
75
71
try:
76
72
    SO_BINDTODEVICE = socket.SO_BINDTODEVICE
83
79
 
84
80
version = "1.0.14"
85
81
 
86
 
logger = logging.getLogger(u'mandos')
 
82
logger = logging.Logger(u'mandos')
87
83
syslogger = (logging.handlers.SysLogHandler
88
84
             (facility = logging.handlers.SysLogHandler.LOG_DAEMON,
89
85
              address = "/dev/log"))
98
94
                                       u' %(message)s'))
99
95
logger.addHandler(console)
100
96
 
101
 
multiprocessing_manager = multiprocessing.Manager()
102
 
 
103
97
class AvahiError(Exception):
104
98
    def __init__(self, value, *args, **kwargs):
105
99
        self.value = value
180
174
                                    self.server.EntryGroupNew()),
181
175
                avahi.DBUS_INTERFACE_ENTRY_GROUP)
182
176
            self.group.connect_to_signal('StateChanged',
183
 
                                         self
184
 
                                         .entry_group_state_changed)
 
177
                                         self.entry_group_state_changed)
185
178
        logger.debug(u"Adding Zeroconf service '%s' of type '%s' ...",
186
179
                     self.name, self.type)
187
180
        self.group.AddService(
246
239
    enabled:    bool()
247
240
    last_checked_ok: datetime.datetime(); (UTC) or None
248
241
    timeout:    datetime.timedelta(); How long from last_checked_ok
249
 
                                      until this client is disabled
 
242
                                      until this client is invalid
250
243
    interval:   datetime.timedelta(); How often to start a new checker
251
244
    disable_hook:  If set, called by disable() as disable_hook(self)
252
245
    checker:    subprocess.Popen(); a running checker process used
253
246
                                    to see if the client lives.
254
247
                                    'None' if no process is running.
255
248
    checker_initiator_tag: a gobject event source tag, or None
256
 
    disable_initiator_tag: - '' -
 
249
    disable_initiator_tag:    - '' -
257
250
    checker_callback_tag:  - '' -
258
251
    checker_command: string; External command which is run to check if
259
252
                     client lives.  %() expansions are done at
260
253
                     runtime with vars(self) as dict, so that for
261
254
                     instance %(name)s can be used in the command.
262
255
    current_checker_command: string; current running checker_command
263
 
    approved_delay: datetime.timedelta(); Time to wait for approval
264
 
    _approved:   bool(); 'None' if not yet approved/disapproved
265
 
    approved_duration: datetime.timedelta(); Duration of one approval
266
256
    """
267
257
    
268
258
    @staticmethod
269
 
    def _timedelta_to_milliseconds(td):
270
 
        "Convert a datetime.timedelta() to milliseconds"
271
 
        return ((td.days * 24 * 60 * 60 * 1000)
272
 
                + (td.seconds * 1000)
273
 
                + (td.microseconds // 1000))
 
259
    def _datetime_to_milliseconds(dt):
 
260
        "Convert a datetime.datetime() to milliseconds"
 
261
        return ((dt.days * 24 * 60 * 60 * 1000)
 
262
                + (dt.seconds * 1000)
 
263
                + (dt.microseconds // 1000))
274
264
    
275
265
    def timeout_milliseconds(self):
276
266
        "Return the 'timeout' attribute in milliseconds"
277
 
        return self._timedelta_to_milliseconds(self.timeout)
 
267
        return self._datetime_to_milliseconds(self.timeout)
278
268
    
279
269
    def interval_milliseconds(self):
280
270
        "Return the 'interval' attribute in milliseconds"
281
 
        return self._timedelta_to_milliseconds(self.interval)
282
 
 
283
 
    def approved_delay_milliseconds(self):
284
 
        return self._timedelta_to_milliseconds(self.approved_delay)
 
271
        return self._datetime_to_milliseconds(self.interval)
285
272
    
286
273
    def __init__(self, name = None, disable_hook=None, config=None):
287
274
        """Note: the 'checker' key in 'config' sets the
300
287
        if u"secret" in config:
301
288
            self.secret = config[u"secret"].decode(u"base64")
302
289
        elif u"secfile" in config:
303
 
            with open(os.path.expanduser(os.path.expandvars
304
 
                                         (config[u"secfile"])),
305
 
                      "rb") as secfile:
 
290
            with closing(open(os.path.expanduser
 
291
                              (os.path.expandvars
 
292
                               (config[u"secfile"])))) as secfile:
306
293
                self.secret = secfile.read()
307
294
        else:
308
 
            #XXX Need to allow secret on demand!
309
295
            raise TypeError(u"No secret or secfile for client %s"
310
296
                            % self.name)
311
297
        self.host = config.get(u"host", u"")
323
309
        self.checker_command = config[u"checker"]
324
310
        self.current_checker_command = None
325
311
        self.last_connect = None
326
 
        self.approvals_pending = 0
327
 
        self._approved = None
328
 
        self.approved_by_default = config.get(u"approved_by_default",
329
 
                                              True)
330
 
        self.approved_delay = string_to_delta(
331
 
            config[u"approved_delay"])
332
 
        self.approved_duration = string_to_delta(
333
 
            config[u"approved_duration"])
334
 
        self.changedstate = multiprocessing_manager.Condition(multiprocessing_manager.Lock())
335
312
    
336
 
    def send_changedstate(self):
337
 
        self.changedstate.acquire()
338
 
        self.changedstate.notify_all()
339
 
        self.changedstate.release()
340
 
        
341
313
    def enable(self):
342
314
        """Start this client's checker and timeout hooks"""
343
315
        if getattr(self, u"enabled", False):
344
316
            # Already enabled
345
317
            return
346
 
        self.send_changedstate()
347
318
        self.last_enabled = datetime.datetime.utcnow()
348
319
        # Schedule a new checker to be started an 'interval' from now,
349
320
        # and every interval from then on.
350
321
        self.checker_initiator_tag = (gobject.timeout_add
351
322
                                      (self.interval_milliseconds(),
352
323
                                       self.start_checker))
 
324
        # Also start a new checker *right now*.
 
325
        self.start_checker()
353
326
        # Schedule a disable() when 'timeout' has passed
354
327
        self.disable_initiator_tag = (gobject.timeout_add
355
328
                                   (self.timeout_milliseconds(),
356
329
                                    self.disable))
357
330
        self.enabled = True
358
 
        # Also start a new checker *right now*.
359
 
        self.start_checker()
360
331
    
361
 
    def disable(self, quiet=True):
 
332
    def disable(self):
362
333
        """Disable this client."""
363
334
        if not getattr(self, "enabled", False):
364
335
            return False
365
 
        if not quiet:
366
 
            self.send_changedstate()
367
 
        if not quiet:
368
 
            logger.info(u"Disabling client %s", self.name)
 
336
        logger.info(u"Disabling client %s", self.name)
369
337
        if getattr(self, u"disable_initiator_tag", False):
370
338
            gobject.source_remove(self.disable_initiator_tag)
371
339
            self.disable_initiator_tag = None
423
391
        # client would inevitably timeout, since no checker would get
424
392
        # a chance to run to completion.  If we instead leave running
425
393
        # checkers alone, the checker would have to take more time
426
 
        # than 'timeout' for the client to be disabled, which is as it
427
 
        # should be.
 
394
        # than 'timeout' for the client to be declared invalid, which
 
395
        # is as it should be.
428
396
        
429
397
        # If a checker exists, make sure it is not a zombie
430
 
        try:
 
398
        if self.checker is not None:
431
399
            pid, status = os.waitpid(self.checker.pid, os.WNOHANG)
432
 
        except (AttributeError, OSError), error:
433
 
            if (isinstance(error, OSError)
434
 
                and error.errno != errno.ECHILD):
435
 
                raise error
436
 
        else:
437
400
            if pid:
438
401
                logger.warning(u"Checker was a zombie")
439
402
                gobject.source_remove(self.checker_callback_tag)
495
458
        logger.debug(u"Stopping checker for %(name)s", vars(self))
496
459
        try:
497
460
            os.kill(self.checker.pid, signal.SIGTERM)
498
 
            #time.sleep(0.5)
 
461
            #os.sleep(0.5)
499
462
            #if self.checker.poll() is None:
500
463
            #    os.kill(self.checker.pid, signal.SIGKILL)
501
464
        except OSError, error:
502
465
            if error.errno != errno.ESRCH: # No such process
503
466
                raise
504
467
        self.checker = None
505
 
 
506
 
def dbus_service_property(dbus_interface, signature=u"v",
507
 
                          access=u"readwrite", byte_arrays=False):
508
 
    """Decorators for marking methods of a DBusObjectWithProperties to
509
 
    become properties on the D-Bus.
510
 
    
511
 
    The decorated method will be called with no arguments by "Get"
512
 
    and with one argument by "Set".
513
 
    
514
 
    The parameters, where they are supported, are the same as
515
 
    dbus.service.method, except there is only "signature", since the
516
 
    type from Get() and the type sent to Set() is the same.
517
 
    """
518
 
    # Encoding deeply encoded byte arrays is not supported yet by the
519
 
    # "Set" method, so we fail early here:
520
 
    if byte_arrays and signature != u"ay":
521
 
        raise ValueError(u"Byte arrays not supported for non-'ay'"
522
 
                         u" signature %r" % signature)
523
 
    def decorator(func):
524
 
        func._dbus_is_property = True
525
 
        func._dbus_interface = dbus_interface
526
 
        func._dbus_signature = signature
527
 
        func._dbus_access = access
528
 
        func._dbus_name = func.__name__
529
 
        if func._dbus_name.endswith(u"_dbus_property"):
530
 
            func._dbus_name = func._dbus_name[:-14]
531
 
        func._dbus_get_args_options = {u'byte_arrays': byte_arrays }
532
 
        return func
533
 
    return decorator
534
 
 
535
 
 
536
 
class DBusPropertyException(dbus.exceptions.DBusException):
537
 
    """A base class for D-Bus property-related exceptions
538
 
    """
539
 
    def __unicode__(self):
540
 
        return unicode(str(self))
541
 
 
542
 
 
543
 
class DBusPropertyAccessException(DBusPropertyException):
544
 
    """A property's access permissions disallows an operation.
545
 
    """
546
 
    pass
547
 
 
548
 
 
549
 
class DBusPropertyNotFound(DBusPropertyException):
550
 
    """An attempt was made to access a non-existing property.
551
 
    """
552
 
    pass
553
 
 
554
 
 
555
 
class DBusObjectWithProperties(dbus.service.Object):
556
 
    """A D-Bus object with properties.
557
 
 
558
 
    Classes inheriting from this can use the dbus_service_property
559
 
    decorator to expose methods as D-Bus properties.  It exposes the
560
 
    standard Get(), Set(), and GetAll() methods on the D-Bus.
561
 
    """
562
 
    
563
 
    @staticmethod
564
 
    def _is_dbus_property(obj):
565
 
        return getattr(obj, u"_dbus_is_property", False)
566
 
    
567
 
    def _get_all_dbus_properties(self):
568
 
        """Returns a generator of (name, attribute) pairs
569
 
        """
570
 
        return ((prop._dbus_name, prop)
571
 
                for name, prop in
572
 
                inspect.getmembers(self, self._is_dbus_property))
573
 
    
574
 
    def _get_dbus_property(self, interface_name, property_name):
575
 
        """Returns a bound method if one exists which is a D-Bus
576
 
        property with the specified name and interface.
577
 
        """
578
 
        for name in (property_name,
579
 
                     property_name + u"_dbus_property"):
580
 
            prop = getattr(self, name, None)
581
 
            if (prop is None
582
 
                or not self._is_dbus_property(prop)
583
 
                or prop._dbus_name != property_name
584
 
                or (interface_name and prop._dbus_interface
585
 
                    and interface_name != prop._dbus_interface)):
586
 
                continue
587
 
            return prop
588
 
        # No such property
589
 
        raise DBusPropertyNotFound(self.dbus_object_path + u":"
590
 
                                   + interface_name + u"."
591
 
                                   + property_name)
592
 
    
593
 
    @dbus.service.method(dbus.PROPERTIES_IFACE, in_signature=u"ss",
594
 
                         out_signature=u"v")
595
 
    def Get(self, interface_name, property_name):
596
 
        """Standard D-Bus property Get() method, see D-Bus standard.
597
 
        """
598
 
        prop = self._get_dbus_property(interface_name, property_name)
599
 
        if prop._dbus_access == u"write":
600
 
            raise DBusPropertyAccessException(property_name)
601
 
        value = prop()
602
 
        if not hasattr(value, u"variant_level"):
603
 
            return value
604
 
        return type(value)(value, variant_level=value.variant_level+1)
605
 
    
606
 
    @dbus.service.method(dbus.PROPERTIES_IFACE, in_signature=u"ssv")
607
 
    def Set(self, interface_name, property_name, value):
608
 
        """Standard D-Bus property Set() method, see D-Bus standard.
609
 
        """
610
 
        prop = self._get_dbus_property(interface_name, property_name)
611
 
        if prop._dbus_access == u"read":
612
 
            raise DBusPropertyAccessException(property_name)
613
 
        if prop._dbus_get_args_options[u"byte_arrays"]:
614
 
            # The byte_arrays option is not supported yet on
615
 
            # signatures other than "ay".
616
 
            if prop._dbus_signature != u"ay":
617
 
                raise ValueError
618
 
            value = dbus.ByteArray(''.join(unichr(byte)
619
 
                                           for byte in value))
620
 
        prop(value)
621
 
    
622
 
    @dbus.service.method(dbus.PROPERTIES_IFACE, in_signature=u"s",
623
 
                         out_signature=u"a{sv}")
624
 
    def GetAll(self, interface_name):
625
 
        """Standard D-Bus property GetAll() method, see D-Bus
626
 
        standard.
627
 
 
628
 
        Note: Will not include properties with access="write".
629
 
        """
630
 
        all = {}
631
 
        for name, prop in self._get_all_dbus_properties():
632
 
            if (interface_name
633
 
                and interface_name != prop._dbus_interface):
634
 
                # Interface non-empty but did not match
635
 
                continue
636
 
            # Ignore write-only properties
637
 
            if prop._dbus_access == u"write":
638
 
                continue
639
 
            value = prop()
640
 
            if not hasattr(value, u"variant_level"):
641
 
                all[name] = value
642
 
                continue
643
 
            all[name] = type(value)(value, variant_level=
644
 
                                    value.variant_level+1)
645
 
        return dbus.Dictionary(all, signature=u"sv")
646
 
    
647
 
    @dbus.service.method(dbus.INTROSPECTABLE_IFACE,
648
 
                         out_signature=u"s",
649
 
                         path_keyword='object_path',
650
 
                         connection_keyword='connection')
651
 
    def Introspect(self, object_path, connection):
652
 
        """Standard D-Bus method, overloaded to insert property tags.
653
 
        """
654
 
        xmlstring = dbus.service.Object.Introspect(self, object_path,
655
 
                                                   connection)
656
 
        try:
657
 
            document = xml.dom.minidom.parseString(xmlstring)
658
 
            def make_tag(document, name, prop):
659
 
                e = document.createElement(u"property")
660
 
                e.setAttribute(u"name", name)
661
 
                e.setAttribute(u"type", prop._dbus_signature)
662
 
                e.setAttribute(u"access", prop._dbus_access)
663
 
                return e
664
 
            for if_tag in document.getElementsByTagName(u"interface"):
665
 
                for tag in (make_tag(document, name, prop)
666
 
                            for name, prop
667
 
                            in self._get_all_dbus_properties()
668
 
                            if prop._dbus_interface
669
 
                            == if_tag.getAttribute(u"name")):
670
 
                    if_tag.appendChild(tag)
671
 
                # Add the names to the return values for the
672
 
                # "org.freedesktop.DBus.Properties" methods
673
 
                if (if_tag.getAttribute(u"name")
674
 
                    == u"org.freedesktop.DBus.Properties"):
675
 
                    for cn in if_tag.getElementsByTagName(u"method"):
676
 
                        if cn.getAttribute(u"name") == u"Get":
677
 
                            for arg in cn.getElementsByTagName(u"arg"):
678
 
                                if (arg.getAttribute(u"direction")
679
 
                                    == u"out"):
680
 
                                    arg.setAttribute(u"name", u"value")
681
 
                        elif cn.getAttribute(u"name") == u"GetAll":
682
 
                            for arg in cn.getElementsByTagName(u"arg"):
683
 
                                if (arg.getAttribute(u"direction")
684
 
                                    == u"out"):
685
 
                                    arg.setAttribute(u"name", u"props")
686
 
            xmlstring = document.toxml(u"utf-8")
687
 
            document.unlink()
688
 
        except (AttributeError, xml.dom.DOMException,
689
 
                xml.parsers.expat.ExpatError), error:
690
 
            logger.error(u"Failed to override Introspection method",
691
 
                         error)
692
 
        return xmlstring
693
 
 
694
 
 
695
 
class ClientDBus(Client, DBusObjectWithProperties):
 
468
    
 
469
    def still_valid(self):
 
470
        """Has the timeout not yet passed for this client?"""
 
471
        if not getattr(self, u"enabled", False):
 
472
            return False
 
473
        now = datetime.datetime.utcnow()
 
474
        if self.last_checked_ok is None:
 
475
            return now < (self.created + self.timeout)
 
476
        else:
 
477
            return now < (self.last_checked_ok + self.timeout)
 
478
 
 
479
 
 
480
class ClientDBus(Client, dbus.service.Object):
696
481
    """A Client class using D-Bus
697
482
    
698
483
    Attributes:
702
487
    # dbus.service.Object doesn't use super(), so we can't either.
703
488
    
704
489
    def __init__(self, bus = None, *args, **kwargs):
705
 
        self._approvals_pending = 0
706
490
        self.bus = bus
707
491
        Client.__init__(self, *args, **kwargs)
708
492
        # Only now, when this client is initialized, can it show up on
710
494
        self.dbus_object_path = (dbus.ObjectPath
711
495
                                 (u"/clients/"
712
496
                                  + self.name.replace(u".", u"_")))
713
 
        DBusObjectWithProperties.__init__(self, self.bus,
714
 
                                          self.dbus_object_path)
715
 
    
716
 
    def _get_approvals_pending(value):
717
 
        return self._approvals_pending
718
 
    def _set_approvals_pending(value):
719
 
        old_value = self._approvals_pending
720
 
        self._approvals_pending = value
721
 
        bval = bool(value)
722
 
        if bval is bool(old_value):
723
 
            dbus_bool = dbus.Boolean(bval, variant_level=1)
724
 
            self.PropertyChanged(dbus.String(u"approved_pending"),
725
 
                                 dbus_bool)
726
 
        return value
727
 
    approvals_pending = property(_get_approvals_pending,
728
 
                                 _set_approvals_pending)
729
 
    del _get_approvals_pending, _set_approvals_pending
 
497
        dbus.service.Object.__init__(self, self.bus,
 
498
                                     self.dbus_object_path)
730
499
    
731
500
    @staticmethod
732
501
    def _datetime_to_dbus(dt, variant_level=0):
747
516
                                       variant_level=1))
748
517
        return r
749
518
    
750
 
    def disable(self, quiet = False):
 
519
    def disable(self, signal = True):
751
520
        oldstate = getattr(self, u"enabled", False)
752
 
        r = Client.disable(self, quiet=quiet)
753
 
        if not quiet and oldstate != self.enabled:
 
521
        r = Client.disable(self)
 
522
        if signal and oldstate != self.enabled:
754
523
            # Emit D-Bus signal
755
524
            self.PropertyChanged(dbus.String(u"enabled"),
756
525
                                 dbus.Boolean(False, variant_level=1))
761
530
            self.remove_from_connection()
762
531
        except LookupError:
763
532
            pass
764
 
        if hasattr(DBusObjectWithProperties, u"__del__"):
765
 
            DBusObjectWithProperties.__del__(self, *args, **kwargs)
 
533
        if hasattr(dbus.service.Object, u"__del__"):
 
534
            dbus.service.Object.__del__(self, *args, **kwargs)
766
535
        Client.__del__(self, *args, **kwargs)
767
536
    
768
537
    def checker_callback(self, pid, condition, command,
821
590
            self.PropertyChanged(dbus.String(u"checker_running"),
822
591
                                 dbus.Boolean(False, variant_level=1))
823
592
        return r
824
 
 
825
 
    def _reset_approved(self):
826
 
        self._approved = None
827
 
        return False
828
 
    
829
 
    def approve(self, value=True):
830
 
        self._approved = value
831
 
        gobject.timeout_add(self._timedelta_to_milliseconds(self.approved_duration, self._reset_approved))
832
 
    
833
 
    
834
 
    ## D-Bus methods, signals & properties
 
593
    
 
594
    ## D-Bus methods & signals
835
595
    _interface = u"se.bsnet.fukt.Mandos.Client"
836
596
    
837
 
    ## Signals
 
597
    # CheckedOK - method
 
598
    @dbus.service.method(_interface)
 
599
    def CheckedOK(self):
 
600
        return self.checked_ok()
838
601
    
839
602
    # CheckerCompleted - signal
840
603
    @dbus.service.signal(_interface, signature=u"nxs")
848
611
        "D-Bus signal"
849
612
        pass
850
613
    
 
614
    # GetAllProperties - method
 
615
    @dbus.service.method(_interface, out_signature=u"a{sv}")
 
616
    def GetAllProperties(self):
 
617
        "D-Bus method"
 
618
        return dbus.Dictionary({
 
619
                dbus.String(u"name"):
 
620
                    dbus.String(self.name, variant_level=1),
 
621
                dbus.String(u"fingerprint"):
 
622
                    dbus.String(self.fingerprint, variant_level=1),
 
623
                dbus.String(u"host"):
 
624
                    dbus.String(self.host, variant_level=1),
 
625
                dbus.String(u"created"):
 
626
                    self._datetime_to_dbus(self.created,
 
627
                                           variant_level=1),
 
628
                dbus.String(u"last_enabled"):
 
629
                    (self._datetime_to_dbus(self.last_enabled,
 
630
                                            variant_level=1)
 
631
                     if self.last_enabled is not None
 
632
                     else dbus.Boolean(False, variant_level=1)),
 
633
                dbus.String(u"enabled"):
 
634
                    dbus.Boolean(self.enabled, variant_level=1),
 
635
                dbus.String(u"last_checked_ok"):
 
636
                    (self._datetime_to_dbus(self.last_checked_ok,
 
637
                                            variant_level=1)
 
638
                     if self.last_checked_ok is not None
 
639
                     else dbus.Boolean (False, variant_level=1)),
 
640
                dbus.String(u"timeout"):
 
641
                    dbus.UInt64(self.timeout_milliseconds(),
 
642
                                variant_level=1),
 
643
                dbus.String(u"interval"):
 
644
                    dbus.UInt64(self.interval_milliseconds(),
 
645
                                variant_level=1),
 
646
                dbus.String(u"checker"):
 
647
                    dbus.String(self.checker_command,
 
648
                                variant_level=1),
 
649
                dbus.String(u"checker_running"):
 
650
                    dbus.Boolean(self.checker is not None,
 
651
                                 variant_level=1),
 
652
                dbus.String(u"object_path"):
 
653
                    dbus.ObjectPath(self.dbus_object_path,
 
654
                                    variant_level=1)
 
655
                }, signature=u"sv")
 
656
    
 
657
    # IsStillValid - method
 
658
    @dbus.service.method(_interface, out_signature=u"b")
 
659
    def IsStillValid(self):
 
660
        return self.still_valid()
 
661
    
851
662
    # PropertyChanged - signal
852
663
    @dbus.service.signal(_interface, signature=u"sv")
853
664
    def PropertyChanged(self, property, value):
854
665
        "D-Bus signal"
855
666
        pass
856
667
    
857
 
    # GotSecret - signal
 
668
    # ReceivedSecret - signal
858
669
    @dbus.service.signal(_interface)
859
 
    def GotSecret(self):
 
670
    def ReceivedSecret(self):
860
671
        "D-Bus signal"
861
672
        pass
862
673
    
863
674
    # Rejected - signal
864
 
    @dbus.service.signal(_interface, signature=u"s")
865
 
    def Rejected(self, reason):
866
 
        "D-Bus signal"
867
 
        pass
868
 
    
869
 
    # NeedApproval - signal
870
 
    @dbus.service.signal(_interface, signature=u"db")
871
 
    def NeedApproval(self, timeout, default):
872
 
        "D-Bus signal"
873
 
        pass
874
 
    
875
 
    ## Methods
876
 
 
877
 
    # Approve - method
878
 
    @dbus.service.method(_interface, in_signature=u"b")
879
 
    def Approve(self, value):
880
 
        self.approve(value)
881
 
 
882
 
    # CheckedOK - method
883
 
    @dbus.service.method(_interface)
884
 
    def CheckedOK(self):
885
 
        return self.checked_ok()
 
675
    @dbus.service.signal(_interface)
 
676
    def Rejected(self):
 
677
        "D-Bus signal"
 
678
        pass
 
679
    
 
680
    # SetChecker - method
 
681
    @dbus.service.method(_interface, in_signature=u"s")
 
682
    def SetChecker(self, checker):
 
683
        "D-Bus setter method"
 
684
        self.checker_command = checker
 
685
        # Emit D-Bus signal
 
686
        self.PropertyChanged(dbus.String(u"checker"),
 
687
                             dbus.String(self.checker_command,
 
688
                                         variant_level=1))
 
689
    
 
690
    # SetHost - method
 
691
    @dbus.service.method(_interface, in_signature=u"s")
 
692
    def SetHost(self, host):
 
693
        "D-Bus setter method"
 
694
        self.host = host
 
695
        # Emit D-Bus signal
 
696
        self.PropertyChanged(dbus.String(u"host"),
 
697
                             dbus.String(self.host, variant_level=1))
 
698
    
 
699
    # SetInterval - method
 
700
    @dbus.service.method(_interface, in_signature=u"t")
 
701
    def SetInterval(self, milliseconds):
 
702
        self.interval = datetime.timedelta(0, 0, 0, milliseconds)
 
703
        # Emit D-Bus signal
 
704
        self.PropertyChanged(dbus.String(u"interval"),
 
705
                             (dbus.UInt64(self.interval_milliseconds(),
 
706
                                          variant_level=1)))
 
707
    
 
708
    # SetSecret - method
 
709
    @dbus.service.method(_interface, in_signature=u"ay",
 
710
                         byte_arrays=True)
 
711
    def SetSecret(self, secret):
 
712
        "D-Bus setter method"
 
713
        self.secret = str(secret)
 
714
    
 
715
    # SetTimeout - method
 
716
    @dbus.service.method(_interface, in_signature=u"t")
 
717
    def SetTimeout(self, milliseconds):
 
718
        self.timeout = datetime.timedelta(0, 0, 0, milliseconds)
 
719
        # Emit D-Bus signal
 
720
        self.PropertyChanged(dbus.String(u"timeout"),
 
721
                             (dbus.UInt64(self.timeout_milliseconds(),
 
722
                                          variant_level=1)))
886
723
    
887
724
    # Enable - method
888
725
    @dbus.service.method(_interface)
907
744
    def StopChecker(self):
908
745
        self.stop_checker()
909
746
    
910
 
    ## Properties
911
 
    
912
 
    # approved_pending - property
913
 
    @dbus_service_property(_interface, signature=u"b", access=u"read")
914
 
    def approved_pending_dbus_property(self):
915
 
        return dbus.Boolean(bool(self.approvals_pending))
916
 
    
917
 
    # approved_by_default - property
918
 
    @dbus_service_property(_interface, signature=u"b",
919
 
                           access=u"readwrite")
920
 
    def approved_by_default_dbus_property(self):
921
 
        return dbus.Boolean(self.approved_by_default)
922
 
    
923
 
    # approved_delay - property
924
 
    @dbus_service_property(_interface, signature=u"t",
925
 
                           access=u"readwrite")
926
 
    def approved_delay_dbus_property(self):
927
 
        return dbus.UInt64(self.approved_delay_milliseconds())
928
 
    
929
 
    # approved_duration - property
930
 
    @dbus_service_property(_interface, signature=u"t",
931
 
                           access=u"readwrite")
932
 
    def approved_duration_dbus_property(self):
933
 
        return dbus.UInt64(self._timedelta_to_milliseconds(
934
 
                self.approved_duration))
935
 
    
936
 
    # name - property
937
 
    @dbus_service_property(_interface, signature=u"s", access=u"read")
938
 
    def name_dbus_property(self):
939
 
        return dbus.String(self.name)
940
 
    
941
 
    # fingerprint - property
942
 
    @dbus_service_property(_interface, signature=u"s", access=u"read")
943
 
    def fingerprint_dbus_property(self):
944
 
        return dbus.String(self.fingerprint)
945
 
    
946
 
    # host - property
947
 
    @dbus_service_property(_interface, signature=u"s",
948
 
                           access=u"readwrite")
949
 
    def host_dbus_property(self, value=None):
950
 
        if value is None:       # get
951
 
            return dbus.String(self.host)
952
 
        self.host = value
953
 
        # Emit D-Bus signal
954
 
        self.PropertyChanged(dbus.String(u"host"),
955
 
                             dbus.String(value, variant_level=1))
956
 
    
957
 
    # created - property
958
 
    @dbus_service_property(_interface, signature=u"s", access=u"read")
959
 
    def created_dbus_property(self):
960
 
        return dbus.String(self._datetime_to_dbus(self.created))
961
 
    
962
 
    # last_enabled - property
963
 
    @dbus_service_property(_interface, signature=u"s", access=u"read")
964
 
    def last_enabled_dbus_property(self):
965
 
        if self.last_enabled is None:
966
 
            return dbus.String(u"")
967
 
        return dbus.String(self._datetime_to_dbus(self.last_enabled))
968
 
    
969
 
    # enabled - property
970
 
    @dbus_service_property(_interface, signature=u"b",
971
 
                           access=u"readwrite")
972
 
    def enabled_dbus_property(self, value=None):
973
 
        if value is None:       # get
974
 
            return dbus.Boolean(self.enabled)
975
 
        if value:
976
 
            self.enable()
977
 
        else:
978
 
            self.disable()
979
 
    
980
 
    # last_checked_ok - property
981
 
    @dbus_service_property(_interface, signature=u"s",
982
 
                           access=u"readwrite")
983
 
    def last_checked_ok_dbus_property(self, value=None):
984
 
        if value is not None:
985
 
            self.checked_ok()
986
 
            return
987
 
        if self.last_checked_ok is None:
988
 
            return dbus.String(u"")
989
 
        return dbus.String(self._datetime_to_dbus(self
990
 
                                                  .last_checked_ok))
991
 
    
992
 
    # timeout - property
993
 
    @dbus_service_property(_interface, signature=u"t",
994
 
                           access=u"readwrite")
995
 
    def timeout_dbus_property(self, value=None):
996
 
        if value is None:       # get
997
 
            return dbus.UInt64(self.timeout_milliseconds())
998
 
        self.timeout = datetime.timedelta(0, 0, 0, value)
999
 
        # Emit D-Bus signal
1000
 
        self.PropertyChanged(dbus.String(u"timeout"),
1001
 
                             dbus.UInt64(value, variant_level=1))
1002
 
        if getattr(self, u"disable_initiator_tag", None) is None:
1003
 
            return
1004
 
        # Reschedule timeout
1005
 
        gobject.source_remove(self.disable_initiator_tag)
1006
 
        self.disable_initiator_tag = None
1007
 
        time_to_die = (self.
1008
 
                       _timedelta_to_milliseconds((self
1009
 
                                                   .last_checked_ok
1010
 
                                                   + self.timeout)
1011
 
                                                  - datetime.datetime
1012
 
                                                  .utcnow()))
1013
 
        if time_to_die <= 0:
1014
 
            # The timeout has passed
1015
 
            self.disable()
1016
 
        else:
1017
 
            self.disable_initiator_tag = (gobject.timeout_add
1018
 
                                          (time_to_die, self.disable))
1019
 
    
1020
 
    # interval - property
1021
 
    @dbus_service_property(_interface, signature=u"t",
1022
 
                           access=u"readwrite")
1023
 
    def interval_dbus_property(self, value=None):
1024
 
        if value is None:       # get
1025
 
            return dbus.UInt64(self.interval_milliseconds())
1026
 
        self.interval = datetime.timedelta(0, 0, 0, value)
1027
 
        # Emit D-Bus signal
1028
 
        self.PropertyChanged(dbus.String(u"interval"),
1029
 
                             dbus.UInt64(value, variant_level=1))
1030
 
        if getattr(self, u"checker_initiator_tag", None) is None:
1031
 
            return
1032
 
        # Reschedule checker run
1033
 
        gobject.source_remove(self.checker_initiator_tag)
1034
 
        self.checker_initiator_tag = (gobject.timeout_add
1035
 
                                      (value, self.start_checker))
1036
 
        self.start_checker()    # Start one now, too
1037
 
 
1038
 
    # checker - property
1039
 
    @dbus_service_property(_interface, signature=u"s",
1040
 
                           access=u"readwrite")
1041
 
    def checker_dbus_property(self, value=None):
1042
 
        if value is None:       # get
1043
 
            return dbus.String(self.checker_command)
1044
 
        self.checker_command = value
1045
 
        # Emit D-Bus signal
1046
 
        self.PropertyChanged(dbus.String(u"checker"),
1047
 
                             dbus.String(self.checker_command,
1048
 
                                         variant_level=1))
1049
 
    
1050
 
    # checker_running - property
1051
 
    @dbus_service_property(_interface, signature=u"b",
1052
 
                           access=u"readwrite")
1053
 
    def checker_running_dbus_property(self, value=None):
1054
 
        if value is None:       # get
1055
 
            return dbus.Boolean(self.checker is not None)
1056
 
        if value:
1057
 
            self.start_checker()
1058
 
        else:
1059
 
            self.stop_checker()
1060
 
    
1061
 
    # object_path - property
1062
 
    @dbus_service_property(_interface, signature=u"o", access=u"read")
1063
 
    def object_path_dbus_property(self):
1064
 
        return self.dbus_object_path # is already a dbus.ObjectPath
1065
 
    
1066
 
    # secret = property
1067
 
    @dbus_service_property(_interface, signature=u"ay",
1068
 
                           access=u"write", byte_arrays=True)
1069
 
    def secret_dbus_property(self, value):
1070
 
        self.secret = str(value)
1071
 
    
1072
747
    del _interface
1073
748
 
1074
749
 
1075
 
class ProxyClient(object):
1076
 
    def __init__(self, child_pipe, fpr, address):
1077
 
        self._pipe = child_pipe
1078
 
        self._pipe.send(('init', fpr, address))
1079
 
        if not self._pipe.recv():
1080
 
            raise KeyError()
1081
 
 
1082
 
    def __getattribute__(self, name):
1083
 
        if(name == '_pipe'):
1084
 
            return super(ProxyClient, self).__getattribute__(name)
1085
 
        self._pipe.send(('getattr', name))
1086
 
        data = self._pipe.recv()
1087
 
        if data[0] == 'data':
1088
 
            return data[1]
1089
 
        if data[0] == 'function':
1090
 
            def func(*args, **kwargs):
1091
 
                self._pipe.send(('funcall', name, args, kwargs))
1092
 
                return self._pipe.recv()[1]
1093
 
            return func
1094
 
 
1095
 
    def __setattr__(self, name, value):
1096
 
        if(name == '_pipe'):
1097
 
            return super(ProxyClient, self).__setattr__(name, value)
1098
 
        self._pipe.send(('setattr', name, value))
1099
 
 
1100
 
 
1101
750
class ClientHandler(socketserver.BaseRequestHandler, object):
1102
751
    """A class to handle client connections.
1103
752
    
1105
754
    Note: This will run in its own forked process."""
1106
755
    
1107
756
    def handle(self):
1108
 
        with contextlib.closing(self.server.child_pipe) as child_pipe:
1109
 
            logger.info(u"TCP connection from: %s",
1110
 
                        unicode(self.client_address))
1111
 
            logger.debug(u"Pipe FD: %d",
1112
 
                         self.server.child_pipe.fileno())
1113
 
 
 
757
        logger.info(u"TCP connection from: %s",
 
758
                    unicode(self.client_address))
 
759
        logger.debug(u"IPC Pipe FD: %d", self.server.pipe[1])
 
760
        # Open IPC pipe to parent process
 
761
        with closing(os.fdopen(self.server.pipe[1], u"w", 1)) as ipc:
1114
762
            session = (gnutls.connection
1115
763
                       .ClientSession(self.request,
1116
764
                                      gnutls.connection
1117
765
                                      .X509Credentials()))
1118
 
 
 
766
            
 
767
            line = self.request.makefile().readline()
 
768
            logger.debug(u"Protocol version: %r", line)
 
769
            try:
 
770
                if int(line.strip().split()[0]) > 1:
 
771
                    raise RuntimeError
 
772
            except (ValueError, IndexError, RuntimeError), error:
 
773
                logger.error(u"Unknown protocol version: %s", error)
 
774
                return
 
775
            
1119
776
            # Note: gnutls.connection.X509Credentials is really a
1120
777
            # generic GnuTLS certificate credentials object so long as
1121
778
            # no X.509 keys are added to it.  Therefore, we can use it
1122
779
            # here despite using OpenPGP certificates.
1123
 
 
 
780
            
1124
781
            #priority = u':'.join((u"NONE", u"+VERS-TLS1.1",
1125
782
            #                      u"+AES-256-CBC", u"+SHA1",
1126
783
            #                      u"+COMP-NULL", u"+CTYPE-OPENPGP",
1132
789
            (gnutls.library.functions
1133
790
             .gnutls_priority_set_direct(session._c_object,
1134
791
                                         priority, None))
1135
 
 
1136
 
            # Start communication using the Mandos protocol
1137
 
            # Get protocol number
1138
 
            line = self.request.makefile().readline()
1139
 
            logger.debug(u"Protocol version: %r", line)
1140
 
            try:
1141
 
                if int(line.strip().split()[0]) > 1:
1142
 
                    raise RuntimeError
1143
 
            except (ValueError, IndexError, RuntimeError), error:
1144
 
                logger.error(u"Unknown protocol version: %s", error)
1145
 
                return
1146
 
 
1147
 
            # Start GnuTLS connection
 
792
            
1148
793
            try:
1149
794
                session.handshake()
1150
795
            except gnutls.errors.GNUTLSError, error:
1153
798
                # established.  Just abandon the request.
1154
799
                return
1155
800
            logger.debug(u"Handshake succeeded")
1156
 
 
1157
 
            approval_required = False
1158
801
            try:
1159
 
                try:
1160
 
                    fpr = self.fingerprint(self.peer_certificate
1161
 
                                           (session))
1162
 
                except (TypeError, gnutls.errors.GNUTLSError), error:
1163
 
                    logger.warning(u"Bad certificate: %s", error)
1164
 
                    return
1165
 
                logger.debug(u"Fingerprint: %s", fpr)
1166
 
 
1167
 
                try:
1168
 
                    client = ProxyClient(child_pipe, fpr,
1169
 
                                         self.client_address)
1170
 
                except KeyError:
1171
 
                    return
1172
 
                
1173
 
                if client.approved_delay:
1174
 
                    delay = client.approved_delay
1175
 
                    client.approvals_pending += 1
1176
 
                    approval_required = True
1177
 
                
1178
 
                while True:
1179
 
                    if not client.enabled:
1180
 
                        logger.warning(u"Client %s is disabled",
1181
 
                                       client.name)
1182
 
                        if self.server.use_dbus:
1183
 
                            # Emit D-Bus signal
1184
 
                            client.Rejected("Disabled")                    
1185
 
                        return
1186
 
                    
1187
 
                    if client._approved or not client.approved_delay:
1188
 
                        #We are approved or approval is disabled
1189
 
                        break
1190
 
                    elif client._approved is None:
1191
 
                        logger.info(u"Client %s need approval",
1192
 
                                    client.name)
1193
 
                        if self.server.use_dbus:
1194
 
                            # Emit D-Bus signal
1195
 
                            client.NeedApproval(
1196
 
                                client.approved_delay_milliseconds(),
1197
 
                                client.approved_by_default)
1198
 
                    else:
1199
 
                        logger.warning(u"Client %s was not approved",
1200
 
                                       client.name)
1201
 
                        if self.server.use_dbus:
1202
 
                            # Emit D-Bus signal
1203
 
                            client.Rejected("Disapproved")
1204
 
                        return
1205
 
                    
1206
 
                    #wait until timeout or approved
1207
 
                    #x = float(client._timedelta_to_milliseconds(delay))
1208
 
                    time = datetime.datetime.now()
1209
 
                    client.changedstate.acquire()
1210
 
                    client.changedstate.wait(float(client._timedelta_to_milliseconds(delay) / 1000))
1211
 
                    client.changedstate.release()
1212
 
                    time2 = datetime.datetime.now()
1213
 
                    if (time2 - time) >= delay:
1214
 
                        if not client.approved_by_default:
1215
 
                            logger.warning("Client %s timed out while"
1216
 
                                           " waiting for approval",
1217
 
                                           client.name)
1218
 
                            if self.server.use_dbus:
1219
 
                                # Emit D-Bus signal
1220
 
                                client.Rejected("Time out")
1221
 
                            return
1222
 
                        else:
1223
 
                            break
1224
 
                    else:
1225
 
                        delay -= time2 - time
1226
 
                
1227
 
                sent_size = 0
1228
 
                while sent_size < len(client.secret):
1229
 
                    # XXX handle session exception
1230
 
                    sent = session.send(client.secret[sent_size:])
1231
 
                    logger.debug(u"Sent: %d, remaining: %d",
1232
 
                                 sent, len(client.secret)
1233
 
                                 - (sent_size + sent))
1234
 
                    sent_size += sent
1235
 
 
1236
 
                logger.info(u"Sending secret to %s", client.name)
1237
 
                # bump the timeout as if seen
1238
 
                client.checked_ok()
1239
 
                if self.server.use_dbus:
1240
 
                    # Emit D-Bus signal
1241
 
                    client.GotSecret()
 
802
                fpr = self.fingerprint(self.peer_certificate(session))
 
803
            except (TypeError, gnutls.errors.GNUTLSError), error:
 
804
                logger.warning(u"Bad certificate: %s", error)
 
805
                session.bye()
 
806
                return
 
807
            logger.debug(u"Fingerprint: %s", fpr)
1242
808
            
1243
 
            finally:
1244
 
                if approval_required:
1245
 
                    client.approvals_pending -= 1
1246
 
                session.bye()
 
809
            for c in self.server.clients:
 
810
                if c.fingerprint == fpr:
 
811
                    client = c
 
812
                    break
 
813
            else:
 
814
                ipc.write(u"NOTFOUND %s %s\n"
 
815
                          % (fpr, unicode(self.client_address)))
 
816
                session.bye()
 
817
                return
 
818
            # Have to check if client.still_valid(), since it is
 
819
            # possible that the client timed out while establishing
 
820
            # the GnuTLS session.
 
821
            if not client.still_valid():
 
822
                ipc.write(u"INVALID %s\n" % client.name)
 
823
                session.bye()
 
824
                return
 
825
            ipc.write(u"SENDING %s\n" % client.name)
 
826
            sent_size = 0
 
827
            while sent_size < len(client.secret):
 
828
                sent = session.send(client.secret[sent_size:])
 
829
                logger.debug(u"Sent: %d, remaining: %d",
 
830
                             sent, len(client.secret)
 
831
                             - (sent_size + sent))
 
832
                sent_size += sent
 
833
            session.bye()
1247
834
    
1248
835
    @staticmethod
1249
836
    def peer_certificate(session):
1309
896
        return hex_fpr
1310
897
 
1311
898
 
1312
 
class MultiprocessingMixIn(object):
1313
 
    """Like socketserver.ThreadingMixIn, but with multiprocessing"""
1314
 
    def sub_process_main(self, request, address):
1315
 
        try:
1316
 
            self.finish_request(request, address)
1317
 
        except:
1318
 
            self.handle_error(request, address)
1319
 
        self.close_request(request)
1320
 
            
1321
 
    def process_request(self, request, address):
1322
 
        """Start a new process to process the request."""
1323
 
        multiprocessing.Process(target = self.sub_process_main,
1324
 
                                args = (request, address)).start()
1325
 
 
1326
 
class MultiprocessingMixInWithPipe(MultiprocessingMixIn, object):
1327
 
    """ adds a pipe to the MixIn """
 
899
class ForkingMixInWithPipe(socketserver.ForkingMixIn, object):
 
900
    """Like socketserver.ForkingMixIn, but also pass a pipe."""
1328
901
    def process_request(self, request, client_address):
1329
902
        """Overrides and wraps the original process_request().
1330
903
        
1331
904
        This function creates a new pipe in self.pipe
1332
905
        """
1333
 
        parent_pipe, self.child_pipe = multiprocessing.Pipe()
1334
 
 
1335
 
        super(MultiprocessingMixInWithPipe,
 
906
        self.pipe = os.pipe()
 
907
        super(ForkingMixInWithPipe,
1336
908
              self).process_request(request, client_address)
1337
 
        self.add_pipe(parent_pipe)
1338
 
    def add_pipe(self, parent_pipe):
 
909
        os.close(self.pipe[1])  # close write end
 
910
        self.add_pipe(self.pipe[0])
 
911
    def add_pipe(self, pipe):
1339
912
        """Dummy function; override as necessary"""
1340
 
        pass
1341
 
 
1342
 
class IPv6_TCPServer(MultiprocessingMixInWithPipe,
 
913
        os.close(pipe)
 
914
 
 
915
 
 
916
class IPv6_TCPServer(ForkingMixInWithPipe,
1343
917
                     socketserver.TCPServer, object):
1344
918
    """IPv6-capable TCP server.  Accepts 'None' as address and/or port
1345
919
    
1409
983
        clients:        set of Client objects
1410
984
        gnutls_priority GnuTLS priority string
1411
985
        use_dbus:       Boolean; to emit D-Bus signals or not
 
986
        clients:        set of Client objects
 
987
        gnutls_priority GnuTLS priority string
 
988
        use_dbus:       Boolean; to emit D-Bus signals or not
1412
989
    
1413
990
    Assumes a gobject.MainLoop event loop.
1414
991
    """
1430
1007
            return socketserver.TCPServer.server_activate(self)
1431
1008
    def enable(self):
1432
1009
        self.enabled = True
1433
 
    def add_pipe(self, parent_pipe):
 
1010
    def add_pipe(self, pipe):
1434
1011
        # Call "handle_ipc" for both data and EOF events
1435
 
        gobject.io_add_watch(parent_pipe.fileno(),
1436
 
                             gobject.IO_IN | gobject.IO_HUP,
1437
 
                             functools.partial(self.handle_ipc,
1438
 
                                               parent_pipe = parent_pipe))
1439
 
        
1440
 
    def handle_ipc(self, source, condition, parent_pipe=None,
1441
 
                   client_object=None):
 
1012
        gobject.io_add_watch(pipe, gobject.IO_IN | gobject.IO_HUP,
 
1013
                             self.handle_ipc)
 
1014
    def handle_ipc(self, source, condition, file_objects={}):
1442
1015
        condition_names = {
1443
1016
            gobject.IO_IN: u"IN",   # There is data to read.
1444
1017
            gobject.IO_OUT: u"OUT", # Data can be written (without
1456
1029
        logger.debug(u"Handling IPC: FD = %d, condition = %s", source,
1457
1030
                     conditions_string)
1458
1031
        
1459
 
        # Read a request from the child
1460
 
        request = parent_pipe.recv()
1461
 
        command = request[0]
 
1032
        # Turn the pipe file descriptor into a Python file object
 
1033
        if source not in file_objects:
 
1034
            file_objects[source] = os.fdopen(source, u"r", 1)
1462
1035
        
1463
 
        if command == 'init':
1464
 
            fpr = request[1]
1465
 
            address = request[2]
1466
 
            
1467
 
            for c in self.clients:
1468
 
                if c.fingerprint == fpr:
1469
 
                    client = c
1470
 
                    break
1471
 
            else:
1472
 
                logger.warning(u"Client not found for fingerprint: %s, ad"
1473
 
                               u"dress: %s", fpr, address)
1474
 
                if self.use_dbus:
1475
 
                    # Emit D-Bus signal
1476
 
                    mandos_dbus_service.ClientNotFound(fpr, address)
1477
 
                parent_pipe.send(False)
1478
 
                return False
1479
 
            
1480
 
            gobject.io_add_watch(parent_pipe.fileno(),
1481
 
                                 gobject.IO_IN | gobject.IO_HUP,
1482
 
                                 functools.partial(self.handle_ipc,
1483
 
                                                   parent_pipe = parent_pipe,
1484
 
                                                   client_object = client))
1485
 
            parent_pipe.send(True)
1486
 
            # remove the old hook in favor of the new above hook on same fileno
 
1036
        # Read a line from the file object
 
1037
        cmdline = file_objects[source].readline()
 
1038
        if not cmdline:             # Empty line means end of file
 
1039
            # close the IPC pipe
 
1040
            file_objects[source].close()
 
1041
            del file_objects[source]
 
1042
            
 
1043
            # Stop calling this function
1487
1044
            return False
1488
 
        if command == 'funcall':
1489
 
            funcname = request[1]
1490
 
            args = request[2]
1491
 
            kwargs = request[3]
1492
 
            
1493
 
            parent_pipe.send(('data', getattr(client_object, funcname)(*args, **kwargs)))
1494
 
 
1495
 
        if command == 'getattr':
1496
 
            attrname = request[1]
1497
 
            if callable(client_object.__getattribute__(attrname)):
1498
 
                parent_pipe.send(('function',))
1499
 
            else:
1500
 
                parent_pipe.send(('data', client_object.__getattribute__(attrname)))
1501
 
        
1502
 
        if command == 'setattr':
1503
 
            attrname = request[1]
1504
 
            value = request[2]
1505
 
            setattr(client_object, attrname, value)
1506
 
        
 
1045
        
 
1046
        logger.debug(u"IPC command: %r", cmdline)
 
1047
        
 
1048
        # Parse and act on command
 
1049
        cmd, args = cmdline.rstrip(u"\r\n").split(None, 1)
 
1050
        
 
1051
        if cmd == u"NOTFOUND":
 
1052
            logger.warning(u"Client not found for fingerprint: %s",
 
1053
                           args)
 
1054
            if self.use_dbus:
 
1055
                # Emit D-Bus signal
 
1056
                mandos_dbus_service.ClientNotFound(args)
 
1057
        elif cmd == u"INVALID":
 
1058
            for client in self.clients:
 
1059
                if client.name == args:
 
1060
                    logger.warning(u"Client %s is invalid", args)
 
1061
                    if self.use_dbus:
 
1062
                        # Emit D-Bus signal
 
1063
                        client.Rejected()
 
1064
                    break
 
1065
            else:
 
1066
                logger.error(u"Unknown client %s is invalid", args)
 
1067
        elif cmd == u"SENDING":
 
1068
            for client in self.clients:
 
1069
                if client.name == args:
 
1070
                    logger.info(u"Sending secret to %s", client.name)
 
1071
                    client.checked_ok()
 
1072
                    if self.use_dbus:
 
1073
                        # Emit D-Bus signal
 
1074
                        client.ReceivedSecret()
 
1075
                    break
 
1076
            else:
 
1077
                logger.error(u"Sending secret to unknown client %s",
 
1078
                             args)
 
1079
        else:
 
1080
            logger.error(u"Unknown IPC command: %r", cmdline)
 
1081
        
 
1082
        # Keep calling this function
1507
1083
        return True
1508
1084
 
1509
1085
 
1539
1115
            elif suffix == u"w":
1540
1116
                delta = datetime.timedelta(0, 0, 0, 0, 0, 0, value)
1541
1117
            else:
1542
 
                raise ValueError(u"Unknown suffix %r" % suffix)
1543
 
        except (ValueError, IndexError), e:
1544
 
            raise ValueError(e.message)
 
1118
                raise ValueError
 
1119
        except (ValueError, IndexError):
 
1120
            raise ValueError
1545
1121
        timevalue += delta
1546
1122
    return timevalue
1547
1123
 
1560
1136
        def if_nametoindex(interface):
1561
1137
            "Get an interface index the hard way, i.e. using fcntl()"
1562
1138
            SIOCGIFINDEX = 0x8933  # From /usr/include/linux/sockios.h
1563
 
            with contextlib.closing(socket.socket()) as s:
 
1139
            with closing(socket.socket()) as s:
1564
1140
                ifreq = fcntl.ioctl(s, SIOCGIFINDEX,
1565
1141
                                    struct.pack(str(u"16s16x"),
1566
1142
                                                interface))
1586
1162
        null = os.open(os.path.devnull, os.O_NOCTTY | os.O_RDWR)
1587
1163
        if not stat.S_ISCHR(os.fstat(null).st_mode):
1588
1164
            raise OSError(errno.ENODEV,
1589
 
                          u"%s not a character device"
1590
 
                          % os.path.devnull)
 
1165
                          u"/dev/null not a character device")
1591
1166
        os.dup2(null, sys.stdin.fileno())
1592
1167
        os.dup2(null, sys.stdout.fileno())
1593
1168
        os.dup2(null, sys.stderr.fileno())
1597
1172
 
1598
1173
def main():
1599
1174
    
1600
 
    ##################################################################
 
1175
    ######################################################################
1601
1176
    # Parsing of options, both command line and config file
1602
1177
    
1603
1178
    parser = optparse.OptionParser(version = "%%prog %s" % version)
1621
1196
                      help=u"Directory to search for configuration"
1622
1197
                      u" files")
1623
1198
    parser.add_option("--no-dbus", action=u"store_false",
1624
 
                      dest=u"use_dbus", help=u"Do not provide D-Bus"
1625
 
                      u" system bus interface")
 
1199
                      dest=u"use_dbus",
 
1200
                      help=optparse.SUPPRESS_HELP) # XXX: Not done yet
1626
1201
    parser.add_option("--no-ipv6", action=u"store_false",
1627
1202
                      dest=u"use_ipv6", help=u"Do not use IPv6")
1628
1203
    options = parser.parse_args()[0]
1680
1255
    # For convenience
1681
1256
    debug = server_settings[u"debug"]
1682
1257
    use_dbus = server_settings[u"use_dbus"]
 
1258
    use_dbus = False            # XXX: Not done yet
1683
1259
    use_ipv6 = server_settings[u"use_ipv6"]
1684
1260
    
1685
1261
    if not debug:
1697
1273
                        u"interval": u"5m",
1698
1274
                        u"checker": u"fping -q -- %%(host)s",
1699
1275
                        u"host": u"",
1700
 
                        u"approved_delay": u"0s",
1701
 
                        u"approved_duration": u"1s",
1702
1276
                        }
1703
1277
    client_config = configparser.SafeConfigParser(client_defaults)
1704
1278
    client_config.read(os.path.join(server_settings[u"configdir"],
1762
1336
    bus = dbus.SystemBus()
1763
1337
    # End of Avahi example code
1764
1338
    if use_dbus:
1765
 
        try:
1766
 
            bus_name = dbus.service.BusName(u"se.bsnet.fukt.Mandos",
1767
 
                                            bus, do_not_queue=True)
1768
 
        except dbus.exceptions.NameExistsException, e:
1769
 
            logger.error(unicode(e) + u", disabling D-Bus")
1770
 
            use_dbus = False
1771
 
            server_settings[u"use_dbus"] = False
1772
 
            tcp_server.use_dbus = False
 
1339
        bus_name = dbus.service.BusName(u"se.bsnet.fukt.Mandos", bus)
1773
1340
    protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
1774
1341
    service = AvahiService(name = server_settings[u"servicename"],
1775
1342
                           servicetype = u"_mandos._tcp",
1781
1348
    client_class = Client
1782
1349
    if use_dbus:
1783
1350
        client_class = functools.partial(ClientDBus, bus = bus)
1784
 
    def client_config_items(config, section):
1785
 
        special_settings = {
1786
 
            "approved_by_default":
1787
 
                lambda: config.getboolean(section,
1788
 
                                          "approved_by_default"),
1789
 
            }
1790
 
        for name, value in config.items(section):
1791
 
            try:
1792
 
                yield (name, special_settings[name]())
1793
 
            except KeyError:
1794
 
                yield (name, value)
1795
 
    
1796
1351
    tcp_server.clients.update(set(
1797
1352
            client_class(name = section,
1798
 
                         config= dict(client_config_items(
1799
 
                        client_config, section)))
 
1353
                         config= dict(client_config.items(section)))
1800
1354
            for section in client_config.sections()))
1801
1355
    if not tcp_server.clients:
1802
1356
        logger.warning(u"No clients defined")
1814
1368
        daemon()
1815
1369
    
1816
1370
    try:
1817
 
        with pidfile:
 
1371
        with closing(pidfile):
1818
1372
            pid = os.getpid()
1819
1373
            pidfile.write(str(pid) + "\n")
1820
1374
        del pidfile
1826
1380
        pass
1827
1381
    del pidfilename
1828
1382
    
 
1383
    def cleanup():
 
1384
        "Cleanup function; run on exit"
 
1385
        service.cleanup()
 
1386
        
 
1387
        while tcp_server.clients:
 
1388
            client = tcp_server.clients.pop()
 
1389
            client.disable_hook = None
 
1390
            client.disable()
 
1391
    
 
1392
    atexit.register(cleanup)
 
1393
    
1829
1394
    if not debug:
1830
1395
        signal.signal(signal.SIGINT, signal.SIG_IGN)
1831
1396
    signal.signal(signal.SIGHUP, lambda signum, frame: sys.exit())
1838
1403
                dbus.service.Object.__init__(self, bus, u"/")
1839
1404
            _interface = u"se.bsnet.fukt.Mandos"
1840
1405
            
1841
 
            @dbus.service.signal(_interface, signature=u"o")
1842
 
            def ClientAdded(self, objpath):
 
1406
            @dbus.service.signal(_interface, signature=u"oa{sv}")
 
1407
            def ClientAdded(self, objpath, properties):
1843
1408
                "D-Bus signal"
1844
1409
                pass
1845
1410
            
1846
 
            @dbus.service.signal(_interface, signature=u"ss")
1847
 
            def ClientNotFound(self, fingerprint, address):
 
1411
            @dbus.service.signal(_interface, signature=u"s")
 
1412
            def ClientNotFound(self, fingerprint):
1848
1413
                "D-Bus signal"
1849
1414
                pass
1850
1415
            
1864
1429
            def GetAllClientsWithProperties(self):
1865
1430
                "D-Bus method"
1866
1431
                return dbus.Dictionary(
1867
 
                    ((c.dbus_object_path, c.GetAll(u""))
 
1432
                    ((c.dbus_object_path, c.GetAllProperties())
1868
1433
                     for c in tcp_server.clients),
1869
1434
                    signature=u"oa{sv}")
1870
1435
            
1876
1441
                        tcp_server.clients.remove(c)
1877
1442
                        c.remove_from_connection()
1878
1443
                        # Don't signal anything except ClientRemoved
1879
 
                        c.disable(quiet=True)
 
1444
                        c.disable(signal=False)
1880
1445
                        # Emit D-Bus signal
1881
1446
                        self.ClientRemoved(object_path, c.name)
1882
1447
                        return
1883
 
                raise KeyError(object_path)
 
1448
                raise KeyError
1884
1449
            
1885
1450
            del _interface
1886
1451
        
1887
1452
        mandos_dbus_service = MandosDBusService()
1888
1453
    
1889
 
    def cleanup():
1890
 
        "Cleanup function; run on exit"
1891
 
        service.cleanup()
1892
 
        
1893
 
        while tcp_server.clients:
1894
 
            client = tcp_server.clients.pop()
1895
 
            if use_dbus:
1896
 
                client.remove_from_connection()
1897
 
            client.disable_hook = None
1898
 
            # Don't signal anything except ClientRemoved
1899
 
            client.disable(quiet=True)
1900
 
            if use_dbus:
1901
 
                # Emit D-Bus signal
1902
 
                mandos_dbus_service.ClientRemoved(client.dbus_object_path,
1903
 
                                                  client.name)
1904
 
    
1905
 
    atexit.register(cleanup)
1906
 
    
1907
1454
    for client in tcp_server.clients:
1908
1455
        if use_dbus:
1909
1456
            # Emit D-Bus signal
1910
 
            mandos_dbus_service.ClientAdded(client.dbus_object_path)
 
1457
            mandos_dbus_service.ClientAdded(client.dbus_object_path,
 
1458
                                            client.GetAllProperties())
1911
1459
        client.enable()
1912
1460
    
1913
1461
    tcp_server.enable()
1931
1479
            service.activate()
1932
1480
        except dbus.exceptions.DBusException, error:
1933
1481
            logger.critical(u"DBusException: %s", error)
1934
 
            cleanup()
1935
1482
            sys.exit(1)
1936
1483
        # End of Avahi example code
1937
1484
        
1944
1491
        main_loop.run()
1945
1492
    except AvahiError, error:
1946
1493
        logger.critical(u"AvahiError: %s", error)
1947
 
        cleanup()
1948
1494
        sys.exit(1)
1949
1495
    except KeyboardInterrupt:
1950
1496
        if debug:
1951
1497
            print >> sys.stderr
1952
1498
        logger.debug(u"Server received KeyboardInterrupt")
1953
1499
    logger.debug(u"Server exiting")
1954
 
    # Must run before the D-Bus bus name gets deregistered
1955
 
    cleanup()
1956
1500
 
1957
1501
if __name__ == '__main__':
1958
1502
    main()