/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: 2011-10-02 13:47:52 UTC
  • Revision ID: teddy@fukt.bsnet.se-20111002134752-c5g5ibcga4biz7ob
* plugins.d/plymouth.c (plymouth_pid): Changed to
                                       "/run/initramfs/plymouth.pid".
  (plymouth_old_pid): New; set to "/dev/.initramfs/plymouth.pid".
  (get_pid): Try both 'plymouth_pid' and 'plymouth_old_pid'.

Show diffs side-by-side

added added

removed removed

Lines of Context:
36
36
 
37
37
import SocketServer as socketserver
38
38
import socket
39
 
import optparse
 
39
import argparse
40
40
import datetime
41
41
import errno
42
42
import gnutls.crypto
82
82
        SO_BINDTODEVICE = None
83
83
 
84
84
 
85
 
version = "1.3.0"
 
85
version = "1.3.1"
86
86
 
87
87
#logger = logging.getLogger('mandos')
88
88
logger = logging.Logger('mandos')
151
151
        self.group = None       # our entry group
152
152
        self.server = None
153
153
        self.bus = bus
 
154
        self.entry_group_state_changed_match = None
154
155
    def rename(self):
155
156
        """Derived from the Avahi example code"""
156
157
        if self.rename_count >= self.max_renames:
168
169
        self.remove()
169
170
        try:
170
171
            self.add()
171
 
        except dbus.exceptions.DBusException, error:
 
172
        except dbus.exceptions.DBusException as error:
172
173
            logger.critical("DBusException: %s", error)
173
174
            self.cleanup()
174
175
            os._exit(1)
175
176
        self.rename_count += 1
176
177
    def remove(self):
177
178
        """Derived from the Avahi example code"""
 
179
        if self.entry_group_state_changed_match is not None:
 
180
            self.entry_group_state_changed_match.remove()
 
181
            self.entry_group_state_changed_match = None
178
182
        if self.group is not None:
179
183
            self.group.Reset()
180
184
    def add(self):
181
185
        """Derived from the Avahi example code"""
 
186
        self.remove()
182
187
        if self.group is None:
183
188
            self.group = dbus.Interface(
184
189
                self.bus.get_object(avahi.DBUS_NAME,
185
190
                                    self.server.EntryGroupNew()),
186
191
                avahi.DBUS_INTERFACE_ENTRY_GROUP)
187
 
            self.group.connect_to_signal('StateChanged',
188
 
                                         self
189
 
                                         .entry_group_state_changed)
 
192
        self.entry_group_state_changed_match = (
 
193
            self.group.connect_to_signal(
 
194
                'StateChanged', self .entry_group_state_changed))
190
195
        logger.debug("Adding Zeroconf service '%s' of type '%s' ...",
191
196
                     self.name, self.type)
192
197
        self.group.AddService(
215
220
    def cleanup(self):
216
221
        """Derived from the Avahi example code"""
217
222
        if self.group is not None:
218
 
            self.group.Free()
 
223
            try:
 
224
                self.group.Free()
 
225
            except (dbus.exceptions.UnknownMethodException,
 
226
                    dbus.exceptions.DBusException) as e:
 
227
                pass
219
228
            self.group = None
220
 
    def server_state_changed(self, state):
 
229
        self.remove()
 
230
    def server_state_changed(self, state, error=None):
221
231
        """Derived from the Avahi example code"""
222
232
        logger.debug("Avahi server state change: %i", state)
223
 
        if state == avahi.SERVER_COLLISION:
224
 
            logger.error("Zeroconf server name collision")
225
 
            self.remove()
 
233
        bad_states = { avahi.SERVER_INVALID:
 
234
                           "Zeroconf server invalid",
 
235
                       avahi.SERVER_REGISTERING: None,
 
236
                       avahi.SERVER_COLLISION:
 
237
                           "Zeroconf server name collision",
 
238
                       avahi.SERVER_FAILURE:
 
239
                           "Zeroconf server failure" }
 
240
        if state in bad_states:
 
241
            if bad_states[state] is not None:
 
242
                if error is None:
 
243
                    logger.error(bad_states[state])
 
244
                else:
 
245
                    logger.error(bad_states[state] + ": %r", error)
 
246
            self.cleanup()
226
247
        elif state == avahi.SERVER_RUNNING:
227
248
            self.add()
 
249
        else:
 
250
            if error is None:
 
251
                logger.debug("Unknown state: %r", state)
 
252
            else:
 
253
                logger.debug("Unknown state: %r: %r", state, error)
228
254
    def activate(self):
229
255
        """Derived from the Avahi example code"""
230
256
        if self.server is None:
231
257
            self.server = dbus.Interface(
232
258
                self.bus.get_object(avahi.DBUS_NAME,
233
 
                                    avahi.DBUS_PATH_SERVER),
 
259
                                    avahi.DBUS_PATH_SERVER,
 
260
                                    follow_name_owner_changes=True),
234
261
                avahi.DBUS_INTERFACE_SERVER)
235
262
        self.server.connect_to_signal("StateChanged",
236
263
                                 self.server_state_changed)
237
264
        self.server_state_changed(self.server.GetState())
238
265
 
239
266
 
 
267
def _timedelta_to_milliseconds(td):
 
268
    "Convert a datetime.timedelta() to milliseconds"
 
269
    return ((td.days * 24 * 60 * 60 * 1000)
 
270
            + (td.seconds * 1000)
 
271
            + (td.microseconds // 1000))
 
272
        
240
273
class Client(object):
241
274
    """A representation of a client host served by this server.
242
275
    
270
303
    secret:     bytestring; sent verbatim (over TLS) to client
271
304
    timeout:    datetime.timedelta(); How long from last_checked_ok
272
305
                                      until this client is disabled
 
306
    extended_timeout:   extra long timeout when password has been sent
273
307
    runtime_expansions: Allowed attributes for runtime expansion.
 
308
    expires:    datetime.datetime(); time (UTC) when a client will be
 
309
                disabled, or None
274
310
    """
275
311
    
276
312
    runtime_expansions = ("approval_delay", "approval_duration",
278
314
                          "host", "interval", "last_checked_ok",
279
315
                          "last_enabled", "name", "timeout")
280
316
    
281
 
    @staticmethod
282
 
    def _timedelta_to_milliseconds(td):
283
 
        "Convert a datetime.timedelta() to milliseconds"
284
 
        return ((td.days * 24 * 60 * 60 * 1000)
285
 
                + (td.seconds * 1000)
286
 
                + (td.microseconds // 1000))
287
 
    
288
317
    def timeout_milliseconds(self):
289
318
        "Return the 'timeout' attribute in milliseconds"
290
 
        return self._timedelta_to_milliseconds(self.timeout)
 
319
        return _timedelta_to_milliseconds(self.timeout)
 
320
    
 
321
    def extended_timeout_milliseconds(self):
 
322
        "Return the 'extended_timeout' attribute in milliseconds"
 
323
        return _timedelta_to_milliseconds(self.extended_timeout)    
291
324
    
292
325
    def interval_milliseconds(self):
293
326
        "Return the 'interval' attribute in milliseconds"
294
 
        return self._timedelta_to_milliseconds(self.interval)
295
 
 
 
327
        return _timedelta_to_milliseconds(self.interval)
 
328
    
296
329
    def approval_delay_milliseconds(self):
297
 
        return self._timedelta_to_milliseconds(self.approval_delay)
 
330
        return _timedelta_to_milliseconds(self.approval_delay)
298
331
    
299
332
    def __init__(self, name = None, disable_hook=None, config=None):
300
333
        """Note: the 'checker' key in 'config' sets the
327
360
        self.last_enabled = None
328
361
        self.last_checked_ok = None
329
362
        self.timeout = string_to_delta(config["timeout"])
 
363
        self.extended_timeout = string_to_delta(config["extended_timeout"])
330
364
        self.interval = string_to_delta(config["interval"])
331
365
        self.disable_hook = disable_hook
332
366
        self.checker = None
333
367
        self.checker_initiator_tag = None
334
368
        self.disable_initiator_tag = None
 
369
        self.expires = None
335
370
        self.checker_callback_tag = None
336
371
        self.checker_command = config["checker"]
337
372
        self.current_checker_command = None
357
392
            # Already enabled
358
393
            return
359
394
        self.send_changedstate()
360
 
        self.last_enabled = datetime.datetime.utcnow()
361
395
        # Schedule a new checker to be started an 'interval' from now,
362
396
        # and every interval from then on.
363
397
        self.checker_initiator_tag = (gobject.timeout_add
364
398
                                      (self.interval_milliseconds(),
365
399
                                       self.start_checker))
366
400
        # Schedule a disable() when 'timeout' has passed
 
401
        self.expires = datetime.datetime.utcnow() + self.timeout
367
402
        self.disable_initiator_tag = (gobject.timeout_add
368
403
                                   (self.timeout_milliseconds(),
369
404
                                    self.disable))
370
405
        self.enabled = True
 
406
        self.last_enabled = datetime.datetime.utcnow()
371
407
        # Also start a new checker *right now*.
372
408
        self.start_checker()
373
409
    
382
418
        if getattr(self, "disable_initiator_tag", False):
383
419
            gobject.source_remove(self.disable_initiator_tag)
384
420
            self.disable_initiator_tag = None
 
421
        self.expires = None
385
422
        if getattr(self, "checker_initiator_tag", False):
386
423
            gobject.source_remove(self.checker_initiator_tag)
387
424
            self.checker_initiator_tag = None
413
450
            logger.warning("Checker for %(name)s crashed?",
414
451
                           vars(self))
415
452
    
416
 
    def checked_ok(self):
 
453
    def checked_ok(self, timeout=None):
417
454
        """Bump up the timeout for this client.
418
455
        
419
456
        This should only be called when the client has been seen,
420
457
        alive and well.
421
458
        """
 
459
        if timeout is None:
 
460
            timeout = self.timeout
422
461
        self.last_checked_ok = datetime.datetime.utcnow()
423
462
        gobject.source_remove(self.disable_initiator_tag)
 
463
        self.expires = datetime.datetime.utcnow() + timeout
424
464
        self.disable_initiator_tag = (gobject.timeout_add
425
 
                                      (self.timeout_milliseconds(),
 
465
                                      (_timedelta_to_milliseconds(timeout),
426
466
                                       self.disable))
427
467
    
428
468
    def need_approval(self):
445
485
        # If a checker exists, make sure it is not a zombie
446
486
        try:
447
487
            pid, status = os.waitpid(self.checker.pid, os.WNOHANG)
448
 
        except (AttributeError, OSError), error:
 
488
        except (AttributeError, OSError) as error:
449
489
            if (isinstance(error, OSError)
450
490
                and error.errno != errno.ECHILD):
451
491
                raise error
469
509
                                       'replace')))
470
510
                    for attr in
471
511
                    self.runtime_expansions)
472
 
 
 
512
                
473
513
                try:
474
514
                    command = self.checker_command % escaped_attrs
475
 
                except TypeError, error:
 
515
                except TypeError as error:
476
516
                    logger.error('Could not format string "%s":'
477
517
                                 ' %s', self.checker_command, error)
478
518
                    return True # Try again later
497
537
                if pid:
498
538
                    gobject.source_remove(self.checker_callback_tag)
499
539
                    self.checker_callback(pid, status, command)
500
 
            except OSError, error:
 
540
            except OSError as error:
501
541
                logger.error("Failed to start subprocess: %s",
502
542
                             error)
503
543
        # Re-run this periodically if run by gobject.timeout_add
516
556
            #time.sleep(0.5)
517
557
            #if self.checker.poll() is None:
518
558
            #    os.kill(self.checker.pid, signal.SIGKILL)
519
 
        except OSError, error:
 
559
        except OSError as error:
520
560
            if error.errno != errno.ESRCH: # No such process
521
561
                raise
522
562
        self.checker = None
523
563
 
 
564
 
524
565
def dbus_service_property(dbus_interface, signature="v",
525
566
                          access="readwrite", byte_arrays=False):
526
567
    """Decorators for marking methods of a DBusObjectWithProperties to
572
613
 
573
614
class DBusObjectWithProperties(dbus.service.Object):
574
615
    """A D-Bus object with properties.
575
 
 
 
616
    
576
617
    Classes inheriting from this can use the dbus_service_property
577
618
    decorator to expose methods as D-Bus properties.  It exposes the
578
619
    standard Get(), Set(), and GetAll() methods on the D-Bus.
642
683
    def GetAll(self, interface_name):
643
684
        """Standard D-Bus property GetAll() method, see D-Bus
644
685
        standard.
645
 
 
 
686
        
646
687
        Note: Will not include properties with access="write".
647
688
        """
648
689
        all = {}
704
745
            xmlstring = document.toxml("utf-8")
705
746
            document.unlink()
706
747
        except (AttributeError, xml.dom.DOMException,
707
 
                xml.parsers.expat.ExpatError), error:
 
748
                xml.parsers.expat.ExpatError) as error:
708
749
            logger.error("Failed to override Introspection method",
709
750
                         error)
710
751
        return xmlstring
711
752
 
712
753
 
 
754
def datetime_to_dbus (dt, variant_level=0):
 
755
    """Convert a UTC datetime.datetime() to a D-Bus type."""
 
756
    if dt is None:
 
757
        return dbus.String("", variant_level = variant_level)
 
758
    return dbus.String(dt.isoformat(),
 
759
                       variant_level=variant_level)
 
760
 
 
761
 
713
762
class ClientDBus(Client, DBusObjectWithProperties):
714
763
    """A Client class using D-Bus
715
764
    
737
786
        DBusObjectWithProperties.__init__(self, self.bus,
738
787
                                          self.dbus_object_path)
739
788
        
740
 
    def _get_approvals_pending(self):
741
 
        return self._approvals_pending
742
 
    def _set_approvals_pending(self, value):
743
 
        old_value = self._approvals_pending
744
 
        self._approvals_pending = value
745
 
        bval = bool(value)
746
 
        if (hasattr(self, "dbus_object_path")
747
 
            and bval is not bool(old_value)):
748
 
            dbus_bool = dbus.Boolean(bval, variant_level=1)
749
 
            self.PropertyChanged(dbus.String("ApprovalPending"),
750
 
                                 dbus_bool)
751
 
 
752
 
    approvals_pending = property(_get_approvals_pending,
753
 
                                 _set_approvals_pending)
754
 
    del _get_approvals_pending, _set_approvals_pending
755
 
    
756
 
    @staticmethod
757
 
    def _datetime_to_dbus(dt, variant_level=0):
758
 
        """Convert a UTC datetime.datetime() to a D-Bus type."""
759
 
        return dbus.String(dt.isoformat(),
760
 
                           variant_level=variant_level)
761
 
    
762
 
    def enable(self):
763
 
        oldstate = getattr(self, "enabled", False)
764
 
        r = Client.enable(self)
765
 
        if oldstate != self.enabled:
766
 
            # Emit D-Bus signals
767
 
            self.PropertyChanged(dbus.String("Enabled"),
768
 
                                 dbus.Boolean(True, variant_level=1))
769
 
            self.PropertyChanged(
770
 
                dbus.String("LastEnabled"),
771
 
                self._datetime_to_dbus(self.last_enabled,
772
 
                                       variant_level=1))
773
 
        return r
774
 
    
775
 
    def disable(self, quiet = False):
776
 
        oldstate = getattr(self, "enabled", False)
777
 
        r = Client.disable(self, quiet=quiet)
778
 
        if not quiet and oldstate != self.enabled:
779
 
            # Emit D-Bus signal
780
 
            self.PropertyChanged(dbus.String("Enabled"),
781
 
                                 dbus.Boolean(False, variant_level=1))
782
 
        return r
 
789
    def notifychangeproperty(transform_func,
 
790
                             dbus_name, type_func=lambda x: x,
 
791
                             variant_level=1):
 
792
        """ Modify a variable so that its a property that announce its
 
793
        changes to DBus.
 
794
        transform_fun: Function that takes a value and transform it to
 
795
                       DBus type.
 
796
        dbus_name: DBus name of the variable
 
797
        type_func: Function that transform the value before sending it
 
798
                   to DBus
 
799
        variant_level: DBus variant level. default: 1
 
800
        """
 
801
        real_value = [None,]
 
802
        def setter(self, value):
 
803
            old_value = real_value[0]
 
804
            real_value[0] = value
 
805
            if hasattr(self, "dbus_object_path"):
 
806
                if type_func(old_value) != type_func(real_value[0]):
 
807
                    dbus_value = transform_func(type_func(real_value[0]),
 
808
                                                variant_level)
 
809
                    self.PropertyChanged(dbus.String(dbus_name),
 
810
                                         dbus_value)
 
811
        
 
812
        return property(lambda self: real_value[0], setter)
 
813
    
 
814
    
 
815
    expires = notifychangeproperty(datetime_to_dbus, "Expires")
 
816
    approvals_pending = notifychangeproperty(dbus.Boolean,
 
817
                                             "ApprovalPending",
 
818
                                             type_func = bool)
 
819
    enabled = notifychangeproperty(dbus.Boolean, "Enabled")
 
820
    last_enabled = notifychangeproperty(datetime_to_dbus,
 
821
                                        "LastEnabled")
 
822
    checker = notifychangeproperty(dbus.Boolean, "CheckerRunning",
 
823
                                   type_func = lambda checker: checker is not None)
 
824
    last_checked_ok = notifychangeproperty(datetime_to_dbus,
 
825
                                           "LastCheckedOK")
 
826
    last_approval_request = notifychangeproperty(datetime_to_dbus,
 
827
                                                 "LastApprovalRequest")
 
828
    approved_by_default = notifychangeproperty(dbus.Boolean,
 
829
                                               "ApprovedByDefault")
 
830
    approval_delay = notifychangeproperty(dbus.UInt16, "ApprovalDelay",
 
831
                                          type_func = _timedelta_to_milliseconds)
 
832
    approval_duration = notifychangeproperty(dbus.UInt16, "ApprovalDuration",
 
833
                                             type_func = _timedelta_to_milliseconds)
 
834
    host = notifychangeproperty(dbus.String, "Host")
 
835
    timeout = notifychangeproperty(dbus.UInt16, "Timeout",
 
836
                                   type_func = _timedelta_to_milliseconds)
 
837
    extended_timeout = notifychangeproperty(dbus.UInt16, "ExtendedTimeout",
 
838
                                            type_func = _timedelta_to_milliseconds)
 
839
    interval = notifychangeproperty(dbus.UInt16, "Interval",
 
840
                                    type_func = _timedelta_to_milliseconds)
 
841
    checker_command = notifychangeproperty(dbus.String, "Checker")
 
842
    
 
843
    del notifychangeproperty
783
844
    
784
845
    def __del__(self, *args, **kwargs):
785
846
        try:
794
855
                         *args, **kwargs):
795
856
        self.checker_callback_tag = None
796
857
        self.checker = None
797
 
        # Emit D-Bus signal
798
 
        self.PropertyChanged(dbus.String("CheckerRunning"),
799
 
                             dbus.Boolean(False, variant_level=1))
800
858
        if os.WIFEXITED(condition):
801
859
            exitstatus = os.WEXITSTATUS(condition)
802
860
            # Emit D-Bus signal
812
870
        return Client.checker_callback(self, pid, condition, command,
813
871
                                       *args, **kwargs)
814
872
    
815
 
    def checked_ok(self, *args, **kwargs):
816
 
        r = Client.checked_ok(self, *args, **kwargs)
817
 
        # Emit D-Bus signal
818
 
        self.PropertyChanged(
819
 
            dbus.String("LastCheckedOK"),
820
 
            (self._datetime_to_dbus(self.last_checked_ok,
821
 
                                    variant_level=1)))
822
 
        return r
823
 
    
824
 
    def need_approval(self, *args, **kwargs):
825
 
        r = Client.need_approval(self, *args, **kwargs)
826
 
        # Emit D-Bus signal
827
 
        self.PropertyChanged(
828
 
            dbus.String("LastApprovalRequest"),
829
 
            (self._datetime_to_dbus(self.last_approval_request,
830
 
                                    variant_level=1)))
831
 
        return r
832
 
    
833
873
    def start_checker(self, *args, **kwargs):
834
874
        old_checker = self.checker
835
875
        if self.checker is not None:
842
882
            and old_checker_pid != self.checker.pid):
843
883
            # Emit D-Bus signal
844
884
            self.CheckerStarted(self.current_checker_command)
845
 
            self.PropertyChanged(
846
 
                dbus.String("CheckerRunning"),
847
 
                dbus.Boolean(True, variant_level=1))
848
885
        return r
849
886
    
850
 
    def stop_checker(self, *args, **kwargs):
851
 
        old_checker = getattr(self, "checker", None)
852
 
        r = Client.stop_checker(self, *args, **kwargs)
853
 
        if (old_checker is not None
854
 
            and getattr(self, "checker", None) is None):
855
 
            self.PropertyChanged(dbus.String("CheckerRunning"),
856
 
                                 dbus.Boolean(False, variant_level=1))
857
 
        return r
858
 
 
859
887
    def _reset_approved(self):
860
888
        self._approved = None
861
889
        return False
863
891
    def approve(self, value=True):
864
892
        self.send_changedstate()
865
893
        self._approved = value
866
 
        gobject.timeout_add(self._timedelta_to_milliseconds
 
894
        gobject.timeout_add(_timedelta_to_milliseconds
867
895
                            (self.approval_duration),
868
896
                            self._reset_approved)
869
897
    
922
950
    # CheckedOK - method
923
951
    @dbus.service.method(_interface)
924
952
    def CheckedOK(self):
925
 
        return self.checked_ok()
 
953
        self.checked_ok()
926
954
    
927
955
    # Enable - method
928
956
    @dbus.service.method(_interface)
961
989
        if value is None:       # get
962
990
            return dbus.Boolean(self.approved_by_default)
963
991
        self.approved_by_default = bool(value)
964
 
        # Emit D-Bus signal
965
 
        self.PropertyChanged(dbus.String("ApprovedByDefault"),
966
 
                             dbus.Boolean(value, variant_level=1))
967
992
    
968
993
    # ApprovalDelay - property
969
994
    @dbus_service_property(_interface, signature="t",
972
997
        if value is None:       # get
973
998
            return dbus.UInt64(self.approval_delay_milliseconds())
974
999
        self.approval_delay = datetime.timedelta(0, 0, 0, value)
975
 
        # Emit D-Bus signal
976
 
        self.PropertyChanged(dbus.String("ApprovalDelay"),
977
 
                             dbus.UInt64(value, variant_level=1))
978
1000
    
979
1001
    # ApprovalDuration - property
980
1002
    @dbus_service_property(_interface, signature="t",
981
1003
                           access="readwrite")
982
1004
    def ApprovalDuration_dbus_property(self, value=None):
983
1005
        if value is None:       # get
984
 
            return dbus.UInt64(self._timedelta_to_milliseconds(
 
1006
            return dbus.UInt64(_timedelta_to_milliseconds(
985
1007
                    self.approval_duration))
986
1008
        self.approval_duration = datetime.timedelta(0, 0, 0, value)
987
 
        # Emit D-Bus signal
988
 
        self.PropertyChanged(dbus.String("ApprovalDuration"),
989
 
                             dbus.UInt64(value, variant_level=1))
990
1009
    
991
1010
    # Name - property
992
1011
    @dbus_service_property(_interface, signature="s", access="read")
1005
1024
        if value is None:       # get
1006
1025
            return dbus.String(self.host)
1007
1026
        self.host = value
1008
 
        # Emit D-Bus signal
1009
 
        self.PropertyChanged(dbus.String("Host"),
1010
 
                             dbus.String(value, variant_level=1))
1011
1027
    
1012
1028
    # Created - property
1013
1029
    @dbus_service_property(_interface, signature="s", access="read")
1014
1030
    def Created_dbus_property(self):
1015
 
        return dbus.String(self._datetime_to_dbus(self.created))
 
1031
        return dbus.String(datetime_to_dbus(self.created))
1016
1032
    
1017
1033
    # LastEnabled - property
1018
1034
    @dbus_service_property(_interface, signature="s", access="read")
1019
1035
    def LastEnabled_dbus_property(self):
1020
 
        if self.last_enabled is None:
1021
 
            return dbus.String("")
1022
 
        return dbus.String(self._datetime_to_dbus(self.last_enabled))
 
1036
        return datetime_to_dbus(self.last_enabled)
1023
1037
    
1024
1038
    # Enabled - property
1025
1039
    @dbus_service_property(_interface, signature="b",
1039
1053
        if value is not None:
1040
1054
            self.checked_ok()
1041
1055
            return
1042
 
        if self.last_checked_ok is None:
1043
 
            return dbus.String("")
1044
 
        return dbus.String(self._datetime_to_dbus(self
1045
 
                                                  .last_checked_ok))
 
1056
        return datetime_to_dbus(self.last_checked_ok)
 
1057
    
 
1058
    # Expires - property
 
1059
    @dbus_service_property(_interface, signature="s", access="read")
 
1060
    def Expires_dbus_property(self):
 
1061
        return datetime_to_dbus(self.expires)
1046
1062
    
1047
1063
    # LastApprovalRequest - property
1048
1064
    @dbus_service_property(_interface, signature="s", access="read")
1049
1065
    def LastApprovalRequest_dbus_property(self):
1050
 
        if self.last_approval_request is None:
1051
 
            return dbus.String("")
1052
 
        return dbus.String(self.
1053
 
                           _datetime_to_dbus(self
1054
 
                                             .last_approval_request))
 
1066
        return datetime_to_dbus(self.last_approval_request)
1055
1067
    
1056
1068
    # Timeout - property
1057
1069
    @dbus_service_property(_interface, signature="t",
1060
1072
        if value is None:       # get
1061
1073
            return dbus.UInt64(self.timeout_milliseconds())
1062
1074
        self.timeout = datetime.timedelta(0, 0, 0, value)
1063
 
        # Emit D-Bus signal
1064
 
        self.PropertyChanged(dbus.String("Timeout"),
1065
 
                             dbus.UInt64(value, variant_level=1))
1066
1075
        if getattr(self, "disable_initiator_tag", None) is None:
1067
1076
            return
1068
1077
        # Reschedule timeout
1069
1078
        gobject.source_remove(self.disable_initiator_tag)
1070
1079
        self.disable_initiator_tag = None
 
1080
        self.expires = None
1071
1081
        time_to_die = (self.
1072
1082
                       _timedelta_to_milliseconds((self
1073
1083
                                                   .last_checked_ok
1078
1088
            # The timeout has passed
1079
1089
            self.disable()
1080
1090
        else:
 
1091
            self.expires = (datetime.datetime.utcnow()
 
1092
                            + datetime.timedelta(milliseconds = time_to_die))
1081
1093
            self.disable_initiator_tag = (gobject.timeout_add
1082
1094
                                          (time_to_die, self.disable))
1083
1095
    
 
1096
    # ExtendedTimeout - property
 
1097
    @dbus_service_property(_interface, signature="t",
 
1098
                           access="readwrite")
 
1099
    def ExtendedTimeout_dbus_property(self, value=None):
 
1100
        if value is None:       # get
 
1101
            return dbus.UInt64(self.extended_timeout_milliseconds())
 
1102
        self.extended_timeout = datetime.timedelta(0, 0, 0, value)
 
1103
    
1084
1104
    # Interval - property
1085
1105
    @dbus_service_property(_interface, signature="t",
1086
1106
                           access="readwrite")
1088
1108
        if value is None:       # get
1089
1109
            return dbus.UInt64(self.interval_milliseconds())
1090
1110
        self.interval = datetime.timedelta(0, 0, 0, value)
1091
 
        # Emit D-Bus signal
1092
 
        self.PropertyChanged(dbus.String("Interval"),
1093
 
                             dbus.UInt64(value, variant_level=1))
1094
1111
        if getattr(self, "checker_initiator_tag", None) is None:
1095
1112
            return
1096
1113
        # Reschedule checker run
1098
1115
        self.checker_initiator_tag = (gobject.timeout_add
1099
1116
                                      (value, self.start_checker))
1100
1117
        self.start_checker()    # Start one now, too
1101
 
 
 
1118
    
1102
1119
    # Checker - property
1103
1120
    @dbus_service_property(_interface, signature="s",
1104
1121
                           access="readwrite")
1106
1123
        if value is None:       # get
1107
1124
            return dbus.String(self.checker_command)
1108
1125
        self.checker_command = value
1109
 
        # Emit D-Bus signal
1110
 
        self.PropertyChanged(dbus.String("Checker"),
1111
 
                             dbus.String(self.checker_command,
1112
 
                                         variant_level=1))
1113
1126
    
1114
1127
    # CheckerRunning - property
1115
1128
    @dbus_service_property(_interface, signature="b",
1142
1155
        self._pipe.send(('init', fpr, address))
1143
1156
        if not self._pipe.recv():
1144
1157
            raise KeyError()
1145
 
 
 
1158
    
1146
1159
    def __getattribute__(self, name):
1147
1160
        if(name == '_pipe'):
1148
1161
            return super(ProxyClient, self).__getattribute__(name)
1155
1168
                self._pipe.send(('funcall', name, args, kwargs))
1156
1169
                return self._pipe.recv()[1]
1157
1170
            return func
1158
 
 
 
1171
    
1159
1172
    def __setattr__(self, name, value):
1160
1173
        if(name == '_pipe'):
1161
1174
            return super(ProxyClient, self).__setattr__(name, value)
1174
1187
                        unicode(self.client_address))
1175
1188
            logger.debug("Pipe FD: %d",
1176
1189
                         self.server.child_pipe.fileno())
1177
 
 
 
1190
            
1178
1191
            session = (gnutls.connection
1179
1192
                       .ClientSession(self.request,
1180
1193
                                      gnutls.connection
1181
1194
                                      .X509Credentials()))
1182
 
 
 
1195
            
1183
1196
            # Note: gnutls.connection.X509Credentials is really a
1184
1197
            # generic GnuTLS certificate credentials object so long as
1185
1198
            # no X.509 keys are added to it.  Therefore, we can use it
1186
1199
            # here despite using OpenPGP certificates.
1187
 
 
 
1200
            
1188
1201
            #priority = ':'.join(("NONE", "+VERS-TLS1.1",
1189
1202
            #                      "+AES-256-CBC", "+SHA1",
1190
1203
            #                      "+COMP-NULL", "+CTYPE-OPENPGP",
1196
1209
            (gnutls.library.functions
1197
1210
             .gnutls_priority_set_direct(session._c_object,
1198
1211
                                         priority, None))
1199
 
 
 
1212
            
1200
1213
            # Start communication using the Mandos protocol
1201
1214
            # Get protocol number
1202
1215
            line = self.request.makefile().readline()
1204
1217
            try:
1205
1218
                if int(line.strip().split()[0]) > 1:
1206
1219
                    raise RuntimeError
1207
 
            except (ValueError, IndexError, RuntimeError), error:
 
1220
            except (ValueError, IndexError, RuntimeError) as error:
1208
1221
                logger.error("Unknown protocol version: %s", error)
1209
1222
                return
1210
 
 
 
1223
            
1211
1224
            # Start GnuTLS connection
1212
1225
            try:
1213
1226
                session.handshake()
1214
 
            except gnutls.errors.GNUTLSError, error:
 
1227
            except gnutls.errors.GNUTLSError as error:
1215
1228
                logger.warning("Handshake failed: %s", error)
1216
1229
                # Do not run session.bye() here: the session is not
1217
1230
                # established.  Just abandon the request.
1218
1231
                return
1219
1232
            logger.debug("Handshake succeeded")
1220
 
 
 
1233
            
1221
1234
            approval_required = False
1222
1235
            try:
1223
1236
                try:
1224
1237
                    fpr = self.fingerprint(self.peer_certificate
1225
1238
                                           (session))
1226
 
                except (TypeError, gnutls.errors.GNUTLSError), error:
 
1239
                except (TypeError,
 
1240
                        gnutls.errors.GNUTLSError) as error:
1227
1241
                    logger.warning("Bad certificate: %s", error)
1228
1242
                    return
1229
1243
                logger.debug("Fingerprint: %s", fpr)
1230
 
 
 
1244
                
1231
1245
                try:
1232
1246
                    client = ProxyClient(child_pipe, fpr,
1233
1247
                                         self.client_address)
1241
1255
                
1242
1256
                while True:
1243
1257
                    if not client.enabled:
1244
 
                        logger.warning("Client %s is disabled",
 
1258
                        logger.info("Client %s is disabled",
1245
1259
                                       client.name)
1246
1260
                        if self.server.use_dbus:
1247
1261
                            # Emit D-Bus signal
1292
1306
                while sent_size < len(client.secret):
1293
1307
                    try:
1294
1308
                        sent = session.send(client.secret[sent_size:])
1295
 
                    except (gnutls.errors.GNUTLSError), error:
 
1309
                    except gnutls.errors.GNUTLSError as error:
1296
1310
                        logger.warning("gnutls send failed")
1297
1311
                        return
1298
1312
                    logger.debug("Sent: %d, remaining: %d",
1299
1313
                                 sent, len(client.secret)
1300
1314
                                 - (sent_size + sent))
1301
1315
                    sent_size += sent
1302
 
 
 
1316
                
1303
1317
                logger.info("Sending secret to %s", client.name)
1304
1318
                # bump the timeout as if seen
1305
 
                client.checked_ok()
 
1319
                client.checked_ok(client.extended_timeout)
1306
1320
                if self.server.use_dbus:
1307
1321
                    # Emit D-Bus signal
1308
1322
                    client.GotSecret()
1312
1326
                    client.approvals_pending -= 1
1313
1327
                try:
1314
1328
                    session.bye()
1315
 
                except (gnutls.errors.GNUTLSError), error:
 
1329
                except gnutls.errors.GNUTLSError as error:
1316
1330
                    logger.warning("GnuTLS bye failed")
1317
1331
    
1318
1332
    @staticmethod
1393
1407
        multiprocessing.Process(target = self.sub_process_main,
1394
1408
                                args = (request, address)).start()
1395
1409
 
 
1410
 
1396
1411
class MultiprocessingMixInWithPipe(MultiprocessingMixIn, object):
1397
1412
    """ adds a pipe to the MixIn """
1398
1413
    def process_request(self, request, client_address):
1401
1416
        This function creates a new pipe in self.pipe
1402
1417
        """
1403
1418
        parent_pipe, self.child_pipe = multiprocessing.Pipe()
1404
 
 
 
1419
        
1405
1420
        super(MultiprocessingMixInWithPipe,
1406
1421
              self).process_request(request, client_address)
1407
1422
        self.child_pipe.close()
1408
1423
        self.add_pipe(parent_pipe)
1409
 
 
 
1424
    
1410
1425
    def add_pipe(self, parent_pipe):
1411
1426
        """Dummy function; override as necessary"""
1412
1427
        raise NotImplementedError
1413
1428
 
 
1429
 
1414
1430
class IPv6_TCPServer(MultiprocessingMixInWithPipe,
1415
1431
                     socketserver.TCPServer, object):
1416
1432
    """IPv6-capable TCP server.  Accepts 'None' as address and/or port
1442
1458
                                           SO_BINDTODEVICE,
1443
1459
                                           str(self.interface
1444
1460
                                               + '\0'))
1445
 
                except socket.error, error:
 
1461
                except socket.error as error:
1446
1462
                    if error[0] == errno.EPERM:
1447
1463
                        logger.error("No permission to"
1448
1464
                                     " bind to interface %s",
1542
1558
                    client = c
1543
1559
                    break
1544
1560
            else:
1545
 
                logger.warning("Client not found for fingerprint: %s, ad"
1546
 
                               "dress: %s", fpr, address)
 
1561
                logger.info("Client not found for fingerprint: %s, ad"
 
1562
                            "dress: %s", fpr, address)
1547
1563
                if self.use_dbus:
1548
1564
                    # Emit D-Bus signal
1549
1565
                    mandos_dbus_service.ClientNotFound(fpr, address[0])
1564
1580
            kwargs = request[3]
1565
1581
            
1566
1582
            parent_pipe.send(('data', getattr(client_object, funcname)(*args, **kwargs)))
1567
 
 
 
1583
        
1568
1584
        if command == 'getattr':
1569
1585
            attrname = request[1]
1570
1586
            if callable(client_object.__getattribute__(attrname)):
1576
1592
            attrname = request[1]
1577
1593
            value = request[2]
1578
1594
            setattr(client_object, attrname, value)
1579
 
 
 
1595
        
1580
1596
        return True
1581
1597
 
1582
1598
 
1613
1629
                delta = datetime.timedelta(0, 0, 0, 0, 0, 0, value)
1614
1630
            else:
1615
1631
                raise ValueError("Unknown suffix %r" % suffix)
1616
 
        except (ValueError, IndexError), e:
 
1632
        except (ValueError, IndexError) as e:
1617
1633
            raise ValueError(*(e.args))
1618
1634
        timevalue += delta
1619
1635
    return timevalue
1673
1689
    ##################################################################
1674
1690
    # Parsing of options, both command line and config file
1675
1691
    
1676
 
    parser = optparse.OptionParser(version = "%%prog %s" % version)
1677
 
    parser.add_option("-i", "--interface", type="string",
1678
 
                      metavar="IF", help="Bind to interface IF")
1679
 
    parser.add_option("-a", "--address", type="string",
1680
 
                      help="Address to listen for requests on")
1681
 
    parser.add_option("-p", "--port", type="int",
1682
 
                      help="Port number to receive requests on")
1683
 
    parser.add_option("--check", action="store_true",
1684
 
                      help="Run self-test")
1685
 
    parser.add_option("--debug", action="store_true",
1686
 
                      help="Debug mode; run in foreground and log to"
1687
 
                      " terminal")
1688
 
    parser.add_option("--debuglevel", type="string", metavar="LEVEL",
1689
 
                      help="Debug level for stdout output")
1690
 
    parser.add_option("--priority", type="string", help="GnuTLS"
1691
 
                      " priority string (see GnuTLS documentation)")
1692
 
    parser.add_option("--servicename", type="string",
1693
 
                      metavar="NAME", help="Zeroconf service name")
1694
 
    parser.add_option("--configdir", type="string",
1695
 
                      default="/etc/mandos", metavar="DIR",
1696
 
                      help="Directory to search for configuration"
1697
 
                      " files")
1698
 
    parser.add_option("--no-dbus", action="store_false",
1699
 
                      dest="use_dbus", help="Do not provide D-Bus"
1700
 
                      " system bus interface")
1701
 
    parser.add_option("--no-ipv6", action="store_false",
1702
 
                      dest="use_ipv6", help="Do not use IPv6")
1703
 
    options = parser.parse_args()[0]
 
1692
    parser = argparse.ArgumentParser()
 
1693
    parser.add_argument("-v", "--version", action="version",
 
1694
                        version = "%%(prog)s %s" % version,
 
1695
                        help="show version number and exit")
 
1696
    parser.add_argument("-i", "--interface", metavar="IF",
 
1697
                        help="Bind to interface IF")
 
1698
    parser.add_argument("-a", "--address",
 
1699
                        help="Address to listen for requests on")
 
1700
    parser.add_argument("-p", "--port", type=int,
 
1701
                        help="Port number to receive requests on")
 
1702
    parser.add_argument("--check", action="store_true",
 
1703
                        help="Run self-test")
 
1704
    parser.add_argument("--debug", action="store_true",
 
1705
                        help="Debug mode; run in foreground and log"
 
1706
                        " to terminal")
 
1707
    parser.add_argument("--debuglevel", metavar="LEVEL",
 
1708
                        help="Debug level for stdout output")
 
1709
    parser.add_argument("--priority", help="GnuTLS"
 
1710
                        " priority string (see GnuTLS documentation)")
 
1711
    parser.add_argument("--servicename",
 
1712
                        metavar="NAME", help="Zeroconf service name")
 
1713
    parser.add_argument("--configdir",
 
1714
                        default="/etc/mandos", metavar="DIR",
 
1715
                        help="Directory to search for configuration"
 
1716
                        " files")
 
1717
    parser.add_argument("--no-dbus", action="store_false",
 
1718
                        dest="use_dbus", help="Do not provide D-Bus"
 
1719
                        " system bus interface")
 
1720
    parser.add_argument("--no-ipv6", action="store_false",
 
1721
                        dest="use_ipv6", help="Do not use IPv6")
 
1722
    options = parser.parse_args()
1704
1723
    
1705
1724
    if options.check:
1706
1725
        import doctest
1758
1777
    debuglevel = server_settings["debuglevel"]
1759
1778
    use_dbus = server_settings["use_dbus"]
1760
1779
    use_ipv6 = server_settings["use_ipv6"]
1761
 
 
 
1780
    
1762
1781
    if server_settings["servicename"] != "Mandos":
1763
1782
        syslogger.setFormatter(logging.Formatter
1764
1783
                               ('Mandos (%s) [%%(process)d]:'
1766
1785
                                % server_settings["servicename"]))
1767
1786
    
1768
1787
    # Parse config file with clients
1769
 
    client_defaults = { "timeout": "1h",
1770
 
                        "interval": "5m",
 
1788
    client_defaults = { "timeout": "5m",
 
1789
                        "extended_timeout": "15m",
 
1790
                        "interval": "2m",
1771
1791
                        "checker": "fping -q -- %%(host)s",
1772
1792
                        "host": "",
1773
1793
                        "approval_delay": "0s",
1813
1833
    try:
1814
1834
        os.setgid(gid)
1815
1835
        os.setuid(uid)
1816
 
    except OSError, error:
 
1836
    except OSError as error:
1817
1837
        if error[0] != errno.EPERM:
1818
1838
            raise error
1819
1839
    
1824
1844
        level = getattr(logging, debuglevel.upper())
1825
1845
        syslogger.setLevel(level)
1826
1846
        console.setLevel(level)
1827
 
 
 
1847
    
1828
1848
    if debug:
1829
1849
        # Enable all possible GnuTLS debugging
1830
1850
        
1863
1883
        try:
1864
1884
            bus_name = dbus.service.BusName("se.bsnet.fukt.Mandos",
1865
1885
                                            bus, do_not_queue=True)
1866
 
        except dbus.exceptions.NameExistsException, e:
 
1886
        except dbus.exceptions.NameExistsException as e:
1867
1887
            logger.error(unicode(e) + ", disabling D-Bus")
1868
1888
            use_dbus = False
1869
1889
            server_settings["use_dbus"] = False
1917
1937
        del pidfilename
1918
1938
        
1919
1939
        signal.signal(signal.SIGINT, signal.SIG_IGN)
1920
 
 
 
1940
    
1921
1941
    signal.signal(signal.SIGHUP, lambda signum, frame: sys.exit())
1922
1942
    signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit())
1923
1943
    
2019
2039
        # From the Avahi example code
2020
2040
        try:
2021
2041
            service.activate()
2022
 
        except dbus.exceptions.DBusException, error:
 
2042
        except dbus.exceptions.DBusException as error:
2023
2043
            logger.critical("DBusException: %s", error)
2024
2044
            cleanup()
2025
2045
            sys.exit(1)
2032
2052
        
2033
2053
        logger.debug("Starting main loop")
2034
2054
        main_loop.run()
2035
 
    except AvahiError, error:
 
2055
    except AvahiError as error:
2036
2056
        logger.critical("AvahiError: %s", error)
2037
2057
        cleanup()
2038
2058
        sys.exit(1)
2044
2064
    # Must run before the D-Bus bus name gets deregistered
2045
2065
    cleanup()
2046
2066
 
 
2067
 
2047
2068
if __name__ == '__main__':
2048
2069
    main()