/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: 2010-10-13 06:12:52 UTC
  • Revision ID: teddy@fukt.bsnet.se-20101013061252-3a918xedja5caya8
* debian/mandos-client.lintian-overrides: Added plugins.d/plymouth.

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.3"
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")
1243
1280
                                           client.name)
1244
1281
                            if self.server.use_dbus:
1245
1282
                                # Emit D-Bus signal
1246
 
                                client.Rejected("Timed out")
 
1283
                                client.Rejected("Approval timed out")
1247
1284
                            return
1248
1285
                        else:
1249
1286
                            break
1487
1524
                                       for cond, name in
1488
1525
                                       condition_names.iteritems()
1489
1526
                                       if cond & condition)
1490
 
        logger.debug(u"Handling IPC: FD = %d, condition = %s", source,
1491
 
                     conditions_string)
1492
 
 
1493
1527
        # error or the other end of multiprocessing.Pipe has closed
1494
1528
        if condition & (gobject.IO_ERR | condition & gobject.IO_HUP):
1495
1529
            return False
1496
1530
        
1497
1531
        # Read a request from the child
1498
1532
        request = parent_pipe.recv()
1499
 
        logger.debug(u"IPC request: %s", repr(request))
1500
1533
        command = request[0]
1501
1534
        
1502
1535
        if command == 'init':
1512
1545
                               u"dress: %s", fpr, address)
1513
1546
                if self.use_dbus:
1514
1547
                    # Emit D-Bus signal
1515
 
                    mandos_dbus_service.ClientNotFound(fpr, address)
 
1548
                    mandos_dbus_service.ClientNotFound(fpr, address[0])
1516
1549
                parent_pipe.send(False)
1517
1550
                return False
1518
1551
            
1651
1684
    parser.add_option("--debug", action=u"store_true",
1652
1685
                      help=u"Debug mode; run in foreground and log to"
1653
1686
                      u" terminal")
1654
 
    parser.add_option("--debuglevel", type=u"string", metavar="Level",
 
1687
    parser.add_option("--debuglevel", type=u"string", metavar="LEVEL",
1655
1688
                      help=u"Debug level for stdout output")
1656
1689
    parser.add_option("--priority", type=u"string", help=u"GnuTLS"
1657
1690
                      u" priority string (see GnuTLS documentation)")
1755
1788
                              gnutls_priority=
1756
1789
                              server_settings[u"priority"],
1757
1790
                              use_dbus=use_dbus)
1758
 
    pidfilename = u"/var/run/mandos.pid"
1759
 
    try:
1760
 
        pidfile = open(pidfilename, u"w")
1761
 
    except IOError:
1762
 
        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)
1763
1797
    
1764
1798
    try:
1765
1799
        uid = pwd.getpwnam(u"_mandos").pw_uid
1813
1847
        # No console logging
1814
1848
        logger.removeHandler(console)
1815
1849
    
 
1850
    # Need to fork before connecting to D-Bus
 
1851
    if not debug:
 
1852
        # Close all input and output, do double fork, etc.
 
1853
        daemon()
1816
1854
    
1817
1855
    global main_loop
1818
1856
    # From the Avahi example code
1836
1874
    if server_settings["interface"]:
1837
1875
        service.interface = (if_nametoindex
1838
1876
                             (str(server_settings[u"interface"])))
1839
 
 
1840
 
    if not debug:
1841
 
        # Close all input and output, do double fork, etc.
1842
 
        daemon()
1843
 
        
 
1877
    
1844
1878
    global multiprocessing_manager
1845
1879
    multiprocessing_manager = multiprocessing.Manager()
1846
1880
    
1867
1901
    if not tcp_server.clients:
1868
1902
        logger.warning(u"No clients defined")
1869
1903
        
1870
 
    try:
1871
 
        with pidfile:
1872
 
            pid = os.getpid()
1873
 
            pidfile.write(str(pid) + "\n")
1874
 
        del pidfile
1875
 
    except IOError:
1876
 
        logger.error(u"Could not write to file %r with PID %d",
1877
 
                     pidfilename, pid)
1878
 
    except NameError:
1879
 
        # "pidfile" was never created
1880
 
        pass
1881
 
    del pidfilename
1882
 
    
1883
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
        
1884
1918
        signal.signal(signal.SIGINT, signal.SIG_IGN)
 
1919
 
1885
1920
    signal.signal(signal.SIGHUP, lambda signum, frame: sys.exit())
1886
1921
    signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit())
1887
1922