/mandos/release

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

« back to all changes in this revision

Viewing changes to mandos

merge

Show diffs side-by-side

added added

removed removed

Lines of Context:
11
11
# "AvahiService" class, and some lines in "main".
12
12
13
13
# Everything else is
14
 
# Copyright © 2008,2009 Teddy Hogeborn
15
 
# Copyright © 2008,2009 Björn Påhlsson
 
14
# Copyright © 2008-2010 Teddy Hogeborn
 
15
# Copyright © 2008-2010 Björn Påhlsson
16
16
17
17
# This program is free software: you can redistribute it and/or modify
18
18
# it under the terms of the GNU General Public License as published by
81
81
        SO_BINDTODEVICE = None
82
82
 
83
83
 
84
 
version = "1.0.14"
 
84
version = "1.2"
85
85
 
86
86
#logger = logging.getLogger(u'mandos')
87
87
logger = logging.Logger(u'mandos')
240
240
    """A representation of a client host served by this server.
241
241
    
242
242
    Attributes:
243
 
    name:       string; from the config file, used in log messages and
244
 
                        D-Bus identifiers
 
243
    _approved:   bool(); 'None' if not yet approved/disapproved
 
244
    approval_delay: datetime.timedelta(); Time to wait for approval
 
245
    approval_duration: datetime.timedelta(); Duration of one approval
 
246
    checker:    subprocess.Popen(); a running checker process used
 
247
                                    to see if the client lives.
 
248
                                    'None' if no process is running.
 
249
    checker_callback_tag: a gobject event source tag, or None
 
250
    checker_command: string; External command which is run to check
 
251
                     if client lives.  %() expansions are done at
 
252
                     runtime with vars(self) as dict, so that for
 
253
                     instance %(name)s can be used in the command.
 
254
    checker_initiator_tag: a gobject event source tag, or None
 
255
    created:    datetime.datetime(); (UTC) object creation
 
256
    current_checker_command: string; current running checker_command
 
257
    disable_hook:  If set, called by disable() as disable_hook(self)
 
258
    disable_initiator_tag: a gobject event source tag, or None
 
259
    enabled:    bool()
245
260
    fingerprint: string (40 or 32 hexadecimal digits); used to
246
261
                 uniquely identify the client
247
 
    secret:     bytestring; sent verbatim (over TLS) to client
248
262
    host:       string; available for use by the checker command
249
 
    created:    datetime.datetime(); (UTC) object creation
 
263
    interval:   datetime.timedelta(); How often to start a new checker
 
264
    last_approval_request: datetime.datetime(); (UTC) or None
 
265
    last_checked_ok: datetime.datetime(); (UTC) or None
250
266
    last_enabled: datetime.datetime(); (UTC)
251
 
    enabled:    bool()
252
 
    last_checked_ok: datetime.datetime(); (UTC) or None
 
267
    name:       string; from the config file, used in log messages and
 
268
                        D-Bus identifiers
 
269
    secret:     bytestring; sent verbatim (over TLS) to client
253
270
    timeout:    datetime.timedelta(); How long from last_checked_ok
254
271
                                      until this client is disabled
255
 
    interval:   datetime.timedelta(); How often to start a new checker
256
 
    disable_hook:  If set, called by disable() as disable_hook(self)
257
 
    checker:    subprocess.Popen(); a running checker process used
258
 
                                    to see if the client lives.
259
 
                                    'None' if no process is running.
260
 
    checker_initiator_tag: a gobject event source tag, or None
261
 
    disable_initiator_tag: - '' -
262
 
    checker_callback_tag:  - '' -
263
 
    checker_command: string; External command which is run to check if
264
 
                     client lives.  %() expansions are done at
265
 
                     runtime with vars(self) as dict, so that for
266
 
                     instance %(name)s can be used in the command.
267
 
    current_checker_command: string; current running checker_command
268
 
    approval_delay: datetime.timedelta(); Time to wait for approval
269
 
    _approved:   bool(); 'None' if not yet approved/disapproved
270
 
    approval_duration: datetime.timedelta(); Duration of one approval
 
272
    runtime_expansions: Allowed attributes for runtime expansion.
271
273
    """
272
274
    
 
275
    runtime_expansions = (u"approval_delay", u"approval_duration",
 
276
                          u"created", u"enabled", u"fingerprint",
 
277
                          u"host", u"interval", u"last_checked_ok",
 
278
                          u"last_enabled", u"name", u"timeout")
 
279
    
273
280
    @staticmethod
274
281
    def _timedelta_to_milliseconds(td):
275
282
        "Convert a datetime.timedelta() to milliseconds"
315
322
        self.host = config.get(u"host", u"")
316
323
        self.created = datetime.datetime.utcnow()
317
324
        self.enabled = False
 
325
        self.last_approval_request = None
318
326
        self.last_enabled = None
319
327
        self.last_checked_ok = None
320
328
        self.timeout = string_to_delta(config[u"timeout"])
416
424
                                      (self.timeout_milliseconds(),
417
425
                                       self.disable))
418
426
    
 
427
    def need_approval(self):
 
428
        self.last_approval_request = datetime.datetime.utcnow()
 
429
    
419
430
    def start_checker(self):
420
431
        """Start a new checker subprocess if one is not running.
421
432
        
450
461
                command = self.checker_command % self.host
451
462
            except TypeError:
452
463
                # Escape attributes for the shell
453
 
                escaped_attrs = dict((key,
454
 
                                      re.escape(unicode(str(val),
455
 
                                                        errors=
456
 
                                                        u'replace')))
457
 
                                     for key, val in
458
 
                                     vars(self).iteritems())
 
464
                escaped_attrs = dict(
 
465
                    (attr,
 
466
                     re.escape(unicode(str(getattr(self, attr, u"")),
 
467
                                       errors=
 
468
                                       u'replace')))
 
469
                    for attr in
 
470
                    self.runtime_expansions)
 
471
 
459
472
                try:
460
473
                    command = self.checker_command % escaped_attrs
461
474
                except TypeError, error:
703
716
    dbus_object_path: dbus.ObjectPath
704
717
    bus: dbus.SystemBus()
705
718
    """
 
719
    
 
720
    runtime_expansions = (Client.runtime_expansions
 
721
                          + (u"dbus_object_path",))
 
722
    
706
723
    # dbus.service.Object doesn't use super(), so we can't either.
707
724
    
708
725
    def __init__(self, bus = None, *args, **kwargs):
711
728
        Client.__init__(self, *args, **kwargs)
712
729
        # Only now, when this client is initialized, can it show up on
713
730
        # the D-Bus
 
731
        client_object_name = unicode(self.name).translate(
 
732
            {ord(u"."): ord(u"_"),
 
733
             ord(u"-"): ord(u"_")})
714
734
        self.dbus_object_path = (dbus.ObjectPath
715
 
                                 (u"/clients/"
716
 
                                  + self.name.replace(u".", u"_")))
 
735
                                 (u"/clients/" + client_object_name))
717
736
        DBusObjectWithProperties.__init__(self, self.bus,
718
737
                                          self.dbus_object_path)
719
738
        
801
820
                                    variant_level=1)))
802
821
        return r
803
822
    
 
823
    def need_approval(self, *args, **kwargs):
 
824
        r = Client.need_approval(self, *args, **kwargs)
 
825
        # Emit D-Bus signal
 
826
        self.PropertyChanged(
 
827
            dbus.String(u"LastApprovalRequest"),
 
828
            (self._datetime_to_dbus(self.last_approval_request,
 
829
                                    variant_level=1)))
 
830
        return r
 
831
    
804
832
    def start_checker(self, *args, **kwargs):
805
833
        old_checker = self.checker
806
834
        if self.checker is not None:
881
909
    @dbus.service.signal(_interface, signature=u"tb")
882
910
    def NeedApproval(self, timeout, default):
883
911
        "D-Bus signal"
884
 
        pass
 
912
        return self.need_approval()
885
913
    
886
914
    ## Methods
887
 
 
 
915
    
888
916
    # Approve - method
889
917
    @dbus.service.method(_interface, in_signature=u"b")
890
918
    def Approve(self, value):
891
919
        self.approve(value)
892
 
 
 
920
    
893
921
    # CheckedOK - method
894
922
    @dbus.service.method(_interface)
895
923
    def CheckedOK(self):
1015
1043
        return dbus.String(self._datetime_to_dbus(self
1016
1044
                                                  .last_checked_ok))
1017
1045
    
 
1046
    # LastApprovalRequest - property
 
1047
    @dbus_service_property(_interface, signature=u"s", access=u"read")
 
1048
    def LastApprovalRequest_dbus_property(self):
 
1049
        if self.last_approval_request is None:
 
1050
            return dbus.String(u"")
 
1051
        return dbus.String(self.
 
1052
                           _datetime_to_dbus(self
 
1053
                                             .last_approval_request))
 
1054
    
1018
1055
    # Timeout - property
1019
1056
    @dbus_service_property(_interface, signature=u"t",
1020
1057
                           access=u"readwrite")
1508
1545
                               u"dress: %s", fpr, address)
1509
1546
                if self.use_dbus:
1510
1547
                    # Emit D-Bus signal
1511
 
                    mandos_dbus_service.ClientNotFound(fpr, address)
 
1548
                    mandos_dbus_service.ClientNotFound(fpr, address[0])
1512
1549
                parent_pipe.send(False)
1513
1550
                return False
1514
1551
            
1647
1684
    parser.add_option("--debug", action=u"store_true",
1648
1685
                      help=u"Debug mode; run in foreground and log to"
1649
1686
                      u" terminal")
1650
 
    parser.add_option("--debuglevel", type=u"string", metavar="Level",
 
1687
    parser.add_option("--debuglevel", type=u"string", metavar="LEVEL",
1651
1688
                      help=u"Debug level for stdout output")
1652
1689
    parser.add_option("--priority", type=u"string", help=u"GnuTLS"
1653
1690
                      u" priority string (see GnuTLS documentation)")
1751
1788
                              gnutls_priority=
1752
1789
                              server_settings[u"priority"],
1753
1790
                              use_dbus=use_dbus)
1754
 
    pidfilename = u"/var/run/mandos.pid"
1755
 
    try:
1756
 
        pidfile = open(pidfilename, u"w")
1757
 
    except IOError:
1758
 
        logger.error(u"Could not open file %r", pidfilename)
 
1791
    if not debug:
 
1792
        pidfilename = u"/var/run/mandos.pid"
 
1793
        try:
 
1794
            pidfile = open(pidfilename, u"w")
 
1795
        except IOError:
 
1796
            logger.error(u"Could not open file %r", pidfilename)
1759
1797
    
1760
1798
    try:
1761
1799
        uid = pwd.getpwnam(u"_mandos").pw_uid
1863
1901
    if not tcp_server.clients:
1864
1902
        logger.warning(u"No clients defined")
1865
1903
        
1866
 
    try:
1867
 
        with pidfile:
1868
 
            pid = os.getpid()
1869
 
            pidfile.write(str(pid) + "\n")
1870
 
        del pidfile
1871
 
    except IOError:
1872
 
        logger.error(u"Could not write to file %r with PID %d",
1873
 
                     pidfilename, pid)
1874
 
    except NameError:
1875
 
        # "pidfile" was never created
1876
 
        pass
1877
 
    del pidfilename
1878
 
    
1879
1904
    if not debug:
 
1905
        try:
 
1906
            with pidfile:
 
1907
                pid = os.getpid()
 
1908
                pidfile.write(str(pid) + "\n")
 
1909
            del pidfile
 
1910
        except IOError:
 
1911
            logger.error(u"Could not write to file %r with PID %d",
 
1912
                         pidfilename, pid)
 
1913
        except NameError:
 
1914
            # "pidfile" was never created
 
1915
            pass
 
1916
        del pidfilename
 
1917
        
1880
1918
        signal.signal(signal.SIGINT, signal.SIG_IGN)
 
1919
 
1881
1920
    signal.signal(signal.SIGHUP, lambda signum, frame: sys.exit())
1882
1921
    signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit())
1883
1922