/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-09-12 03:00:40 UTC
  • Revision ID: teddy@fukt.bsnet.se-20100912030040-b0uopyennste9fdh
Documentation changes:

* DBUS-API: New file documenting the server D-Bus interface.

* clients.conf: Add examples of new approval settings.

* debian/mandos.docs: Added "DBUS-API".

* mandos-clients.conf.xml (OPTIONS): Added "approved_by_default",
                                     "approval_delay", and
                                     "approval_duration".
* mandos.xml (D-BUS INTERFACE): Refer to the "DBUS-API" file.
  (BUGS): Remove mention of lack of a remote query interface.

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-2010 Teddy Hogeborn
15
 
# Copyright © 2008-2010 Björn Påhlsson
 
14
# Copyright © 2008,2009 Teddy Hogeborn
 
15
# Copyright © 2008,2009 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
240
240
    """A representation of a client host served by this server.
241
241
    
242
242
    Attributes:
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
 
243
    name:       string; from the config file, used in log messages and
 
244
                        D-Bus identifiers
 
245
    fingerprint: string (40 or 32 hexadecimal digits); used to
 
246
                 uniquely identify the client
 
247
    secret:     bytestring; sent verbatim (over TLS) to client
 
248
    host:       string; available for use by the checker command
 
249
    created:    datetime.datetime(); (UTC) object creation
 
250
    last_enabled: datetime.datetime(); (UTC)
 
251
    enabled:    bool()
 
252
    last_checked_ok: datetime.datetime(); (UTC) or None
 
253
    timeout:    datetime.timedelta(); How long from last_checked_ok
 
254
                                      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)
246
257
    checker:    subprocess.Popen(); a running checker process used
247
258
                                    to see if the client lives.
248
259
                                    '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
 
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
252
265
                     runtime with vars(self) as dict, so that for
253
266
                     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
267
    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()
260
 
    fingerprint: string (40 or 32 hexadecimal digits); used to
261
 
                 uniquely identify the client
262
 
    host:       string; available for use by the checker command
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
266
 
    last_enabled: datetime.datetime(); (UTC)
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
270
 
    timeout:    datetime.timedelta(); How long from last_checked_ok
271
 
                                      until this client is disabled
272
 
    runtime_expansions: Allowed attributes for runtime expansion.
 
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
273
271
    """
274
272
    
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
 
    
280
273
    @staticmethod
281
274
    def _timedelta_to_milliseconds(td):
282
275
        "Convert a datetime.timedelta() to milliseconds"
322
315
        self.host = config.get(u"host", u"")
323
316
        self.created = datetime.datetime.utcnow()
324
317
        self.enabled = False
325
 
        self.last_approval_request = None
326
318
        self.last_enabled = None
327
319
        self.last_checked_ok = None
328
320
        self.timeout = string_to_delta(config[u"timeout"])
424
416
                                      (self.timeout_milliseconds(),
425
417
                                       self.disable))
426
418
    
427
 
    def need_approval(self):
428
 
        self.last_approval_request = datetime.datetime.utcnow()
429
 
    
430
419
    def start_checker(self):
431
420
        """Start a new checker subprocess if one is not running.
432
421
        
461
450
                command = self.checker_command % self.host
462
451
            except TypeError:
463
452
                # Escape attributes for the shell
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
 
 
 
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())
472
459
                try:
473
460
                    command = self.checker_command % escaped_attrs
474
461
                except TypeError, error:
716
703
    dbus_object_path: dbus.ObjectPath
717
704
    bus: dbus.SystemBus()
718
705
    """
719
 
    
720
 
    runtime_expansions = (Client.runtime_expansions
721
 
                          + (u"dbus_object_path",))
722
 
    
723
706
    # dbus.service.Object doesn't use super(), so we can't either.
724
707
    
725
708
    def __init__(self, bus = None, *args, **kwargs):
728
711
        Client.__init__(self, *args, **kwargs)
729
712
        # Only now, when this client is initialized, can it show up on
730
713
        # the D-Bus
731
 
        client_object_name = unicode(self.name).translate(
732
 
            {ord(u"."): ord(u"_"),
733
 
             ord(u"-"): ord(u"_")})
734
714
        self.dbus_object_path = (dbus.ObjectPath
735
 
                                 (u"/clients/" + client_object_name))
 
715
                                 (u"/clients/"
 
716
                                  + self.name.replace(u".", u"_")))
736
717
        DBusObjectWithProperties.__init__(self, self.bus,
737
718
                                          self.dbus_object_path)
738
719
        
820
801
                                    variant_level=1)))
821
802
        return r
822
803
    
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
 
    
832
804
    def start_checker(self, *args, **kwargs):
833
805
        old_checker = self.checker
834
806
        if self.checker is not None:
909
881
    @dbus.service.signal(_interface, signature=u"tb")
910
882
    def NeedApproval(self, timeout, default):
911
883
        "D-Bus signal"
912
 
        return self.need_approval()
 
884
        pass
913
885
    
914
886
    ## Methods
915
 
    
 
887
 
916
888
    # Approve - method
917
889
    @dbus.service.method(_interface, in_signature=u"b")
918
890
    def Approve(self, value):
919
891
        self.approve(value)
920
 
    
 
892
 
921
893
    # CheckedOK - method
922
894
    @dbus.service.method(_interface)
923
895
    def CheckedOK(self):
1043
1015
        return dbus.String(self._datetime_to_dbus(self
1044
1016
                                                  .last_checked_ok))
1045
1017
    
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
 
    
1055
1018
    # Timeout - property
1056
1019
    @dbus_service_property(_interface, signature=u"t",
1057
1020
                           access=u"readwrite")
1280
1243
                                           client.name)
1281
1244
                            if self.server.use_dbus:
1282
1245
                                # Emit D-Bus signal
1283
 
                                client.Rejected("Approval timed out")
 
1246
                                client.Rejected("Timed out")
1284
1247
                            return
1285
1248
                        else:
1286
1249
                            break
1524
1487
                                       for cond, name in
1525
1488
                                       condition_names.iteritems()
1526
1489
                                       if cond & condition)
 
1490
        logger.debug(u"Handling IPC: FD = %d, condition = %s", source,
 
1491
                     conditions_string)
 
1492
 
1527
1493
        # error or the other end of multiprocessing.Pipe has closed
1528
1494
        if condition & (gobject.IO_ERR | condition & gobject.IO_HUP):
1529
1495
            return False
1530
1496
        
1531
1497
        # Read a request from the child
1532
1498
        request = parent_pipe.recv()
 
1499
        logger.debug(u"IPC request: %s", repr(request))
1533
1500
        command = request[0]
1534
1501
        
1535
1502
        if command == 'init':
1545
1512
                               u"dress: %s", fpr, address)
1546
1513
                if self.use_dbus:
1547
1514
                    # Emit D-Bus signal
1548
 
                    mandos_dbus_service.ClientNotFound(fpr, address[0])
 
1515
                    mandos_dbus_service.ClientNotFound(fpr, address)
1549
1516
                parent_pipe.send(False)
1550
1517
                return False
1551
1518
            
1684
1651
    parser.add_option("--debug", action=u"store_true",
1685
1652
                      help=u"Debug mode; run in foreground and log to"
1686
1653
                      u" terminal")
1687
 
    parser.add_option("--debuglevel", type=u"string", metavar="LEVEL",
 
1654
    parser.add_option("--debuglevel", type=u"string", metavar="Level",
1688
1655
                      help=u"Debug level for stdout output")
1689
1656
    parser.add_option("--priority", type=u"string", help=u"GnuTLS"
1690
1657
                      u" priority string (see GnuTLS documentation)")
1788
1755
                              gnutls_priority=
1789
1756
                              server_settings[u"priority"],
1790
1757
                              use_dbus=use_dbus)
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)
 
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)
1797
1763
    
1798
1764
    try:
1799
1765
        uid = pwd.getpwnam(u"_mandos").pw_uid
1901
1867
    if not tcp_server.clients:
1902
1868
        logger.warning(u"No clients defined")
1903
1869
        
 
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
    
1904
1883
    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
 
        
1918
1884
        signal.signal(signal.SIGINT, signal.SIG_IGN)
1919
 
 
1920
1885
    signal.signal(signal.SIGHUP, lambda signum, frame: sys.exit())
1921
1886
    signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit())
1922
1887