/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: 2011-02-11 19:36:42 UTC
  • mto: This revision was merged to the branch mainline in revision 465.
  • Revision ID: teddy@fukt.bsnet.se-20110211193642-bj1fr6n33hc0oi0m
* mandos: Use only unicode string literals.

Show diffs side-by-side

added added

removed removed

Lines of Context:
81
81
        SO_BINDTODEVICE = None
82
82
 
83
83
 
84
 
version = "1.2.3"
 
84
version = u"1.2.3"
85
85
 
86
86
#logger = logging.getLogger(u'mandos')
87
87
logger = logging.Logger(u'mandos')
88
88
syslogger = (logging.handlers.SysLogHandler
89
89
             (facility = logging.handlers.SysLogHandler.LOG_DAEMON,
90
 
              address = "/dev/log"))
 
90
              address = u"/dev/log"))
91
91
syslogger.setFormatter(logging.Formatter
92
92
                       (u'Mandos [%(process)d]: %(levelname)s:'
93
93
                        u' %(message)s'))
314
314
        elif u"secfile" in config:
315
315
            with open(os.path.expanduser(os.path.expandvars
316
316
                                         (config[u"secfile"])),
317
 
                      "rb") as secfile:
 
317
                      u"rb") as secfile:
318
318
                self.secret = secfile.read()
319
319
        else:
320
320
            raise TypeError(u"No secret or secfile for client %s"
372
372
    
373
373
    def disable(self, quiet=True):
374
374
        """Disable this client."""
375
 
        if not getattr(self, "enabled", False):
 
375
        if not getattr(self, u"enabled", False):
376
376
            return False
377
377
        if not quiet:
378
378
            self.send_changedstate()
663
663
    
664
664
    @dbus.service.method(dbus.INTROSPECTABLE_IFACE,
665
665
                         out_signature=u"s",
666
 
                         path_keyword='object_path',
667
 
                         connection_keyword='connection')
 
666
                         path_keyword=u'object_path',
 
667
                         connection_keyword=u'connection')
668
668
    def Introspect(self, object_path, connection):
669
669
        """Standard D-Bus method, overloaded to insert property tags.
670
670
        """
742
742
        old_value = self._approvals_pending
743
743
        self._approvals_pending = value
744
744
        bval = bool(value)
745
 
        if (hasattr(self, "dbus_object_path")
 
745
        if (hasattr(self, u"dbus_object_path")
746
746
            and bval is not bool(old_value)):
747
747
            dbus_bool = dbus.Boolean(bval, variant_level=1)
748
748
            self.PropertyChanged(dbus.String(u"ApprovalPending"),
1138
1138
class ProxyClient(object):
1139
1139
    def __init__(self, child_pipe, fpr, address):
1140
1140
        self._pipe = child_pipe
1141
 
        self._pipe.send(('init', fpr, address))
 
1141
        self._pipe.send((u'init', fpr, address))
1142
1142
        if not self._pipe.recv():
1143
1143
            raise KeyError()
1144
1144
 
1145
1145
    def __getattribute__(self, name):
1146
 
        if(name == '_pipe'):
 
1146
        if(name == u'_pipe'):
1147
1147
            return super(ProxyClient, self).__getattribute__(name)
1148
 
        self._pipe.send(('getattr', name))
 
1148
        self._pipe.send((u'getattr', name))
1149
1149
        data = self._pipe.recv()
1150
 
        if data[0] == 'data':
 
1150
        if data[0] == u'data':
1151
1151
            return data[1]
1152
 
        if data[0] == 'function':
 
1152
        if data[0] == u'function':
1153
1153
            def func(*args, **kwargs):
1154
 
                self._pipe.send(('funcall', name, args, kwargs))
 
1154
                self._pipe.send((u'funcall', name, args, kwargs))
1155
1155
                return self._pipe.recv()[1]
1156
1156
            return func
1157
1157
 
1158
1158
    def __setattr__(self, name, value):
1159
 
        if(name == '_pipe'):
 
1159
        if(name == u'_pipe'):
1160
1160
            return super(ProxyClient, self).__setattr__(name, value)
1161
 
        self._pipe.send(('setattr', name, value))
 
1161
        self._pipe.send((u'setattr', name, value))
1162
1162
 
1163
1163
 
1164
1164
class ClientHandler(socketserver.BaseRequestHandler, object):
1244
1244
                                       client.name)
1245
1245
                        if self.server.use_dbus:
1246
1246
                            # Emit D-Bus signal
1247
 
                            client.Rejected("Disabled")                    
 
1247
                            client.Rejected(u"Disabled")                    
1248
1248
                        return
1249
1249
                    
1250
1250
                    if client._approved or not client.approval_delay:
1263
1263
                                       client.name)
1264
1264
                        if self.server.use_dbus:
1265
1265
                            # Emit D-Bus signal
1266
 
                            client.Rejected("Denied")
 
1266
                            client.Rejected(u"Denied")
1267
1267
                        return
1268
1268
                    
1269
1269
                    #wait until timeout or approved
1275
1275
                    time2 = datetime.datetime.now()
1276
1276
                    if (time2 - time) >= delay:
1277
1277
                        if not client.approved_by_default:
1278
 
                            logger.warning("Client %s timed out while"
1279
 
                                           " waiting for approval",
 
1278
                            logger.warning(u"Client %s timed out while"
 
1279
                                           u" waiting for approval",
1280
1280
                                           client.name)
1281
1281
                            if self.server.use_dbus:
1282
1282
                                # Emit D-Bus signal
1283
 
                                client.Rejected("Approval timed out")
 
1283
                                client.Rejected(u"Approval timed out")
1284
1284
                            return
1285
1285
                        else:
1286
1286
                            break
1292
1292
                    try:
1293
1293
                        sent = session.send(client.secret[sent_size:])
1294
1294
                    except (gnutls.errors.GNUTLSError), error:
1295
 
                        logger.warning("gnutls send failed")
 
1295
                        logger.warning(u"gnutls send failed")
1296
1296
                        return
1297
1297
                    logger.debug(u"Sent: %d, remaining: %d",
1298
1298
                                 sent, len(client.secret)
1312
1312
                try:
1313
1313
                    session.bye()
1314
1314
                except (gnutls.errors.GNUTLSError), error:
1315
 
                    logger.warning("GnuTLS bye failed")
 
1315
                    logger.warning(u"GnuTLS bye failed")
1316
1316
    
1317
1317
    @staticmethod
1318
1318
    def peer_certificate(session):
1520
1520
                                    # broken, usually for pipes and
1521
1521
                                    # sockets).
1522
1522
            }
1523
 
        conditions_string = ' | '.join(name
 
1523
        conditions_string = u' | '.join(name
1524
1524
                                       for cond, name in
1525
1525
                                       condition_names.iteritems()
1526
1526
                                       if cond & condition)
1532
1532
        request = parent_pipe.recv()
1533
1533
        command = request[0]
1534
1534
        
1535
 
        if command == 'init':
 
1535
        if command == u'init':
1536
1536
            fpr = request[1]
1537
1537
            address = request[2]
1538
1538
            
1557
1557
            parent_pipe.send(True)
1558
1558
            # remove the old hook in favor of the new above hook on same fileno
1559
1559
            return False
1560
 
        if command == 'funcall':
 
1560
        if command == u'funcall':
1561
1561
            funcname = request[1]
1562
1562
            args = request[2]
1563
1563
            kwargs = request[3]
1564
1564
            
1565
 
            parent_pipe.send(('data', getattr(client_object, funcname)(*args, **kwargs)))
 
1565
            parent_pipe.send((u'data', getattr(client_object, funcname)(*args, **kwargs)))
1566
1566
 
1567
 
        if command == 'getattr':
 
1567
        if command == u'getattr':
1568
1568
            attrname = request[1]
1569
1569
            if callable(client_object.__getattribute__(attrname)):
1570
 
                parent_pipe.send(('function',))
 
1570
                parent_pipe.send((u'function',))
1571
1571
            else:
1572
 
                parent_pipe.send(('data', client_object.__getattribute__(attrname)))
 
1572
                parent_pipe.send((u'data', client_object.__getattribute__(attrname)))
1573
1573
        
1574
 
        if command == 'setattr':
 
1574
        if command == u'setattr':
1575
1575
            attrname = request[1]
1576
1576
            value = request[2]
1577
1577
            setattr(client_object, attrname, value)
1672
1672
    ##################################################################
1673
1673
    # Parsing of options, both command line and config file
1674
1674
    
1675
 
    parser = optparse.OptionParser(version = "%%prog %s" % version)
1676
 
    parser.add_option("-i", u"--interface", type=u"string",
1677
 
                      metavar="IF", help=u"Bind to interface IF")
1678
 
    parser.add_option("-a", u"--address", type=u"string",
 
1675
    parser = optparse.OptionParser(version = u"%%prog %s" % version)
 
1676
    parser.add_option(u"-i", u"--interface", type=u"string",
 
1677
                      metavar=u"IF", help=u"Bind to interface IF")
 
1678
    parser.add_option(u"-a", u"--address", type=u"string",
1679
1679
                      help=u"Address to listen for requests on")
1680
 
    parser.add_option("-p", u"--port", type=u"int",
 
1680
    parser.add_option(u"-p", u"--port", type=u"int",
1681
1681
                      help=u"Port number to receive requests on")
1682
 
    parser.add_option("--check", action=u"store_true",
 
1682
    parser.add_option(u"--check", action=u"store_true",
1683
1683
                      help=u"Run self-test")
1684
 
    parser.add_option("--debug", action=u"store_true",
 
1684
    parser.add_option(u"--debug", action=u"store_true",
1685
1685
                      help=u"Debug mode; run in foreground and log to"
1686
1686
                      u" terminal")
1687
 
    parser.add_option("--debuglevel", type=u"string", metavar="LEVEL",
 
1687
    parser.add_option(u"--debuglevel", type=u"string", metavar="LEVEL",
1688
1688
                      help=u"Debug level for stdout output")
1689
 
    parser.add_option("--priority", type=u"string", help=u"GnuTLS"
 
1689
    parser.add_option(u"--priority", type=u"string", help=u"GnuTLS"
1690
1690
                      u" priority string (see GnuTLS documentation)")
1691
 
    parser.add_option("--servicename", type=u"string",
 
1691
    parser.add_option(u"--servicename", type=u"string",
1692
1692
                      metavar=u"NAME", help=u"Zeroconf service name")
1693
 
    parser.add_option("--configdir", type=u"string",
 
1693
    parser.add_option(u"--configdir", type=u"string",
1694
1694
                      default=u"/etc/mandos", metavar=u"DIR",
1695
1695
                      help=u"Directory to search for configuration"
1696
1696
                      u" files")
1697
 
    parser.add_option("--no-dbus", action=u"store_false",
 
1697
    parser.add_option(u"--no-dbus", action=u"store_false",
1698
1698
                      dest=u"use_dbus", help=u"Do not provide D-Bus"
1699
1699
                      u" system bus interface")
1700
 
    parser.add_option("--no-ipv6", action=u"store_false",
 
1700
    parser.add_option(u"--no-ipv6", action=u"store_false",
1701
1701
                      dest=u"use_ipv6", help=u"Do not use IPv6")
1702
1702
    options = parser.parse_args()[0]
1703
1703
    
1730
1730
    for option in (u"debug", u"use_dbus", u"use_ipv6"):
1731
1731
        server_settings[option] = server_config.getboolean(u"DEFAULT",
1732
1732
                                                           option)
1733
 
    if server_settings["port"]:
1734
 
        server_settings["port"] = server_config.getint(u"DEFAULT",
 
1733
    if server_settings[u"port"]:
 
1734
        server_settings[u"port"] = server_config.getint(u"DEFAULT",
1735
1735
                                                       u"port")
1736
1736
    del server_config
1737
1737
    
1871
1871
    service = AvahiService(name = server_settings[u"servicename"],
1872
1872
                           servicetype = u"_mandos._tcp",
1873
1873
                           protocol = protocol, bus = bus)
1874
 
    if server_settings["interface"]:
 
1874
    if server_settings[u"interface"]:
1875
1875
        service.interface = (if_nametoindex
1876
1876
                             (str(server_settings[u"interface"])))
1877
1877
    
1883
1883
        client_class = functools.partial(ClientDBus, bus = bus)
1884
1884
    def client_config_items(config, section):
1885
1885
        special_settings = {
1886
 
            "approved_by_default":
 
1886
            u"approved_by_default":
1887
1887
                lambda: config.getboolean(section,
1888
 
                                          "approved_by_default"),
 
1888
                                          u"approved_by_default"),
1889
1889
            }
1890
1890
        for name, value in config.items(section):
1891
1891
            try:
1905
1905
        try:
1906
1906
            with pidfile:
1907
1907
                pid = os.getpid()
1908
 
                pidfile.write(str(pid) + "\n")
 
1908
                pidfile.write(str(pid) + u"\n".encode("utf-8"))
1909
1909
            del pidfile
1910
1910
        except IOError:
1911
1911
            logger.error(u"Could not write to file %r with PID %d",
2006
2006
    service.port = tcp_server.socket.getsockname()[1]
2007
2007
    if use_ipv6:
2008
2008
        logger.info(u"Now listening on address %r, port %d,"
2009
 
                    " flowinfo %d, scope_id %d"
 
2009
                    u" flowinfo %d, scope_id %d"
2010
2010
                    % tcp_server.socket.getsockname())
2011
2011
    else:                       # IPv4
2012
2012
        logger.info(u"Now listening on address %r, port %d"
2043
2043
    # Must run before the D-Bus bus name gets deregistered
2044
2044
    cleanup()
2045
2045
 
2046
 
if __name__ == '__main__':
 
2046
if __name__ == u'__main__':
2047
2047
    main()