/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

* plugins.d/password-prompt.c (conflict_detection): Check for both
                                                    "plymouth" and
                                                    "plymouthd".

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-2011 Teddy Hogeborn
 
15
# Copyright © 2008-2011 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
31
31
# Contact the authors at <mandos@fukt.bsnet.se>.
32
32
33
33
 
34
 
from __future__ import division, with_statement, absolute_import
 
34
from __future__ import (division, absolute_import, print_function,
 
35
                        unicode_literals)
35
36
 
36
37
import SocketServer as socketserver
37
38
import socket
81
82
        SO_BINDTODEVICE = None
82
83
 
83
84
 
84
 
version = "1.0.14"
 
85
version = "1.2.3"
85
86
 
86
 
logger = logging.Logger(u'mandos')
 
87
#logger = logging.getLogger('mandos')
 
88
logger = logging.Logger('mandos')
87
89
syslogger = (logging.handlers.SysLogHandler
88
90
             (facility = logging.handlers.SysLogHandler.LOG_DAEMON,
89
 
              address = "/dev/log"))
 
91
              address = str("/dev/log")))
90
92
syslogger.setFormatter(logging.Formatter
91
 
                       (u'Mandos [%(process)d]: %(levelname)s:'
92
 
                        u' %(message)s'))
 
93
                       ('Mandos [%(process)d]: %(levelname)s:'
 
94
                        ' %(message)s'))
93
95
logger.addHandler(syslogger)
94
96
 
95
97
console = logging.StreamHandler()
96
 
console.setFormatter(logging.Formatter(u'%(name)s [%(process)d]:'
97
 
                                       u' %(levelname)s:'
98
 
                                       u' %(message)s'))
 
98
console.setFormatter(logging.Formatter('%(name)s [%(process)d]:'
 
99
                                       ' %(levelname)s:'
 
100
                                       ' %(message)s'))
99
101
logger.addHandler(console)
100
102
 
101
103
class AvahiError(Exception):
118
120
    Attributes:
119
121
    interface: integer; avahi.IF_UNSPEC or an interface index.
120
122
               Used to optionally bind to the specified interface.
121
 
    name: string; Example: u'Mandos'
122
 
    type: string; Example: u'_mandos._tcp'.
 
123
    name: string; Example: 'Mandos'
 
124
    type: string; Example: '_mandos._tcp'.
123
125
                  See <http://www.dns-sd.org/ServiceTypes.html>
124
126
    port: integer; what port to announce
125
127
    TXT: list of strings; TXT record for the service
134
136
    """
135
137
    def __init__(self, interface = avahi.IF_UNSPEC, name = None,
136
138
                 servicetype = None, port = None, TXT = None,
137
 
                 domain = u"", host = u"", max_renames = 32768,
 
139
                 domain = "", host = "", max_renames = 32768,
138
140
                 protocol = avahi.PROTO_UNSPEC, bus = None):
139
141
        self.interface = interface
140
142
        self.name = name
152
154
    def rename(self):
153
155
        """Derived from the Avahi example code"""
154
156
        if self.rename_count >= self.max_renames:
155
 
            logger.critical(u"No suitable Zeroconf service name found"
156
 
                            u" after %i retries, exiting.",
 
157
            logger.critical("No suitable Zeroconf service name found"
 
158
                            " after %i retries, exiting.",
157
159
                            self.rename_count)
158
 
            raise AvahiServiceError(u"Too many renames")
159
 
        self.name = self.server.GetAlternativeServiceName(self.name)
160
 
        logger.info(u"Changing Zeroconf service name to %r ...",
161
 
                    unicode(self.name))
 
160
            raise AvahiServiceError("Too many renames")
 
161
        self.name = unicode(self.server.GetAlternativeServiceName(self.name))
 
162
        logger.info("Changing Zeroconf service name to %r ...",
 
163
                    self.name)
162
164
        syslogger.setFormatter(logging.Formatter
163
 
                               (u'Mandos (%s) [%%(process)d]:'
164
 
                                u' %%(levelname)s: %%(message)s'
 
165
                               ('Mandos (%s) [%%(process)d]:'
 
166
                                ' %%(levelname)s: %%(message)s'
165
167
                                % self.name))
166
168
        self.remove()
167
 
        self.add()
 
169
        try:
 
170
            self.add()
 
171
        except dbus.exceptions.DBusException, error:
 
172
            logger.critical("DBusException: %s", error)
 
173
            self.cleanup()
 
174
            os._exit(1)
168
175
        self.rename_count += 1
169
176
    def remove(self):
170
177
        """Derived from the Avahi example code"""
180
187
            self.group.connect_to_signal('StateChanged',
181
188
                                         self
182
189
                                         .entry_group_state_changed)
183
 
        logger.debug(u"Adding Zeroconf service '%s' of type '%s' ...",
 
190
        logger.debug("Adding Zeroconf service '%s' of type '%s' ...",
184
191
                     self.name, self.type)
185
192
        self.group.AddService(
186
193
            self.interface,
193
200
        self.group.Commit()
194
201
    def entry_group_state_changed(self, state, error):
195
202
        """Derived from the Avahi example code"""
196
 
        logger.debug(u"Avahi state change: %i", state)
 
203
        logger.debug("Avahi entry group state change: %i", state)
197
204
        
198
205
        if state == avahi.ENTRY_GROUP_ESTABLISHED:
199
 
            logger.debug(u"Zeroconf service established.")
 
206
            logger.debug("Zeroconf service established.")
200
207
        elif state == avahi.ENTRY_GROUP_COLLISION:
201
 
            logger.warning(u"Zeroconf service name collision.")
 
208
            logger.info("Zeroconf service name collision.")
202
209
            self.rename()
203
210
        elif state == avahi.ENTRY_GROUP_FAILURE:
204
 
            logger.critical(u"Avahi: Error in group state changed %s",
 
211
            logger.critical("Avahi: Error in group state changed %s",
205
212
                            unicode(error))
206
 
            raise AvahiGroupError(u"State changed: %s"
 
213
            raise AvahiGroupError("State changed: %s"
207
214
                                  % unicode(error))
208
215
    def cleanup(self):
209
216
        """Derived from the Avahi example code"""
212
219
            self.group = None
213
220
    def server_state_changed(self, state):
214
221
        """Derived from the Avahi example code"""
 
222
        logger.debug("Avahi server state change: %i", state)
215
223
        if state == avahi.SERVER_COLLISION:
216
 
            logger.error(u"Zeroconf server name collision")
 
224
            logger.error("Zeroconf server name collision")
217
225
            self.remove()
218
226
        elif state == avahi.SERVER_RUNNING:
219
227
            self.add()
224
232
                self.bus.get_object(avahi.DBUS_NAME,
225
233
                                    avahi.DBUS_PATH_SERVER),
226
234
                avahi.DBUS_INTERFACE_SERVER)
227
 
        self.server.connect_to_signal(u"StateChanged",
 
235
        self.server.connect_to_signal("StateChanged",
228
236
                                 self.server_state_changed)
229
237
        self.server_state_changed(self.server.GetState())
230
238
 
233
241
    """A representation of a client host served by this server.
234
242
    
235
243
    Attributes:
236
 
    name:       string; from the config file, used in log messages and
237
 
                        D-Bus identifiers
 
244
    _approved:   bool(); 'None' if not yet approved/disapproved
 
245
    approval_delay: datetime.timedelta(); Time to wait for approval
 
246
    approval_duration: datetime.timedelta(); Duration of one approval
 
247
    checker:    subprocess.Popen(); a running checker process used
 
248
                                    to see if the client lives.
 
249
                                    'None' if no process is running.
 
250
    checker_callback_tag: a gobject event source tag, or None
 
251
    checker_command: string; External command which is run to check
 
252
                     if client lives.  %() expansions are done at
 
253
                     runtime with vars(self) as dict, so that for
 
254
                     instance %(name)s can be used in the command.
 
255
    checker_initiator_tag: a gobject event source tag, or None
 
256
    created:    datetime.datetime(); (UTC) object creation
 
257
    current_checker_command: string; current running checker_command
 
258
    disable_hook:  If set, called by disable() as disable_hook(self)
 
259
    disable_initiator_tag: a gobject event source tag, or None
 
260
    enabled:    bool()
238
261
    fingerprint: string (40 or 32 hexadecimal digits); used to
239
262
                 uniquely identify the client
240
 
    secret:     bytestring; sent verbatim (over TLS) to client
241
263
    host:       string; available for use by the checker command
242
 
    created:    datetime.datetime(); (UTC) object creation
 
264
    interval:   datetime.timedelta(); How often to start a new checker
 
265
    last_approval_request: datetime.datetime(); (UTC) or None
 
266
    last_checked_ok: datetime.datetime(); (UTC) or None
243
267
    last_enabled: datetime.datetime(); (UTC)
244
 
    enabled:    bool()
245
 
    last_checked_ok: datetime.datetime(); (UTC) or None
 
268
    name:       string; from the config file, used in log messages and
 
269
                        D-Bus identifiers
 
270
    secret:     bytestring; sent verbatim (over TLS) to client
246
271
    timeout:    datetime.timedelta(); How long from last_checked_ok
247
272
                                      until this client is disabled
248
 
    interval:   datetime.timedelta(); How often to start a new checker
249
 
    disable_hook:  If set, called by disable() as disable_hook(self)
250
 
    checker:    subprocess.Popen(); a running checker process used
251
 
                                    to see if the client lives.
252
 
                                    'None' if no process is running.
253
 
    checker_initiator_tag: a gobject event source tag, or None
254
 
    disable_initiator_tag: - '' -
255
 
    checker_callback_tag:  - '' -
256
 
    checker_command: string; External command which is run to check if
257
 
                     client lives.  %() expansions are done at
258
 
                     runtime with vars(self) as dict, so that for
259
 
                     instance %(name)s can be used in the command.
260
 
    current_checker_command: string; current running checker_command
261
 
    approved_delay: datetime.timedelta(); Time to wait for approval
262
 
    _approved:   bool(); 'None' if not yet approved/disapproved
263
 
    approved_duration: datetime.timedelta(); Duration of one approval
 
273
    runtime_expansions: Allowed attributes for runtime expansion.
264
274
    """
265
275
    
 
276
    runtime_expansions = ("approval_delay", "approval_duration",
 
277
                          "created", "enabled", "fingerprint",
 
278
                          "host", "interval", "last_checked_ok",
 
279
                          "last_enabled", "name", "timeout")
 
280
    
266
281
    @staticmethod
267
282
    def _timedelta_to_milliseconds(td):
268
283
        "Convert a datetime.timedelta() to milliseconds"
278
293
        "Return the 'interval' attribute in milliseconds"
279
294
        return self._timedelta_to_milliseconds(self.interval)
280
295
 
281
 
    def approved_delay_milliseconds(self):
282
 
        return self._timedelta_to_milliseconds(self.approved_delay)
 
296
    def approval_delay_milliseconds(self):
 
297
        return self._timedelta_to_milliseconds(self.approval_delay)
283
298
    
284
299
    def __init__(self, name = None, disable_hook=None, config=None):
285
300
        """Note: the 'checker' key in 'config' sets the
288
303
        self.name = name
289
304
        if config is None:
290
305
            config = {}
291
 
        logger.debug(u"Creating client %r", self.name)
 
306
        logger.debug("Creating client %r", self.name)
292
307
        # Uppercase and remove spaces from fingerprint for later
293
308
        # comparison purposes with return value from the fingerprint()
294
309
        # function
295
 
        self.fingerprint = (config[u"fingerprint"].upper()
296
 
                            .replace(u" ", u""))
297
 
        logger.debug(u"  Fingerprint: %s", self.fingerprint)
298
 
        if u"secret" in config:
299
 
            self.secret = config[u"secret"].decode(u"base64")
300
 
        elif u"secfile" in config:
 
310
        self.fingerprint = (config["fingerprint"].upper()
 
311
                            .replace(" ", ""))
 
312
        logger.debug("  Fingerprint: %s", self.fingerprint)
 
313
        if "secret" in config:
 
314
            self.secret = config["secret"].decode("base64")
 
315
        elif "secfile" in config:
301
316
            with open(os.path.expanduser(os.path.expandvars
302
 
                                         (config[u"secfile"])),
 
317
                                         (config["secfile"])),
303
318
                      "rb") as secfile:
304
319
                self.secret = secfile.read()
305
320
        else:
306
 
            #XXX Need to allow secret on demand!
307
 
            raise TypeError(u"No secret or secfile for client %s"
 
321
            raise TypeError("No secret or secfile for client %s"
308
322
                            % self.name)
309
 
        self.host = config.get(u"host", u"")
 
323
        self.host = config.get("host", "")
310
324
        self.created = datetime.datetime.utcnow()
311
325
        self.enabled = False
 
326
        self.last_approval_request = None
312
327
        self.last_enabled = None
313
328
        self.last_checked_ok = None
314
 
        self.timeout = string_to_delta(config[u"timeout"])
315
 
        self.interval = string_to_delta(config[u"interval"])
 
329
        self.timeout = string_to_delta(config["timeout"])
 
330
        self.interval = string_to_delta(config["interval"])
316
331
        self.disable_hook = disable_hook
317
332
        self.checker = None
318
333
        self.checker_initiator_tag = None
319
334
        self.disable_initiator_tag = None
320
335
        self.checker_callback_tag = None
321
 
        self.checker_command = config[u"checker"]
 
336
        self.checker_command = config["checker"]
322
337
        self.current_checker_command = None
323
338
        self.last_connect = None
 
339
        self._approved = None
 
340
        self.approved_by_default = config.get("approved_by_default",
 
341
                                              True)
324
342
        self.approvals_pending = 0
325
 
        self._approved = None
326
 
        self.approved_by_default = config.get(u"approved_by_default",
327
 
                                              False)
328
 
        self.approved_delay = string_to_delta(
329
 
            config[u"approved_delay"])
330
 
        self.approved_duration = string_to_delta(
331
 
            config[u"approved_duration"])
 
343
        self.approval_delay = string_to_delta(
 
344
            config["approval_delay"])
 
345
        self.approval_duration = string_to_delta(
 
346
            config["approval_duration"])
332
347
        self.changedstate = multiprocessing_manager.Condition(multiprocessing_manager.Lock())
333
 
 
 
348
    
334
349
    def send_changedstate(self):
335
350
        self.changedstate.acquire()
336
351
        self.changedstate.notify_all()
338
353
        
339
354
    def enable(self):
340
355
        """Start this client's checker and timeout hooks"""
341
 
        if getattr(self, u"enabled", False):
 
356
        if getattr(self, "enabled", False):
342
357
            # Already enabled
343
358
            return
344
359
        self.send_changedstate()
363
378
        if not quiet:
364
379
            self.send_changedstate()
365
380
        if not quiet:
366
 
            logger.info(u"Disabling client %s", self.name)
367
 
        if getattr(self, u"disable_initiator_tag", False):
 
381
            logger.info("Disabling client %s", self.name)
 
382
        if getattr(self, "disable_initiator_tag", False):
368
383
            gobject.source_remove(self.disable_initiator_tag)
369
384
            self.disable_initiator_tag = None
370
 
        if getattr(self, u"checker_initiator_tag", False):
 
385
        if getattr(self, "checker_initiator_tag", False):
371
386
            gobject.source_remove(self.checker_initiator_tag)
372
387
            self.checker_initiator_tag = None
373
388
        self.stop_checker()
388
403
        if os.WIFEXITED(condition):
389
404
            exitstatus = os.WEXITSTATUS(condition)
390
405
            if exitstatus == 0:
391
 
                logger.info(u"Checker for %(name)s succeeded",
 
406
                logger.info("Checker for %(name)s succeeded",
392
407
                            vars(self))
393
408
                self.checked_ok()
394
409
            else:
395
 
                logger.info(u"Checker for %(name)s failed",
 
410
                logger.info("Checker for %(name)s failed",
396
411
                            vars(self))
397
412
        else:
398
 
            logger.warning(u"Checker for %(name)s crashed?",
 
413
            logger.warning("Checker for %(name)s crashed?",
399
414
                           vars(self))
400
415
    
401
416
    def checked_ok(self):
410
425
                                      (self.timeout_milliseconds(),
411
426
                                       self.disable))
412
427
    
 
428
    def need_approval(self):
 
429
        self.last_approval_request = datetime.datetime.utcnow()
 
430
    
413
431
    def start_checker(self):
414
432
        """Start a new checker subprocess if one is not running.
415
433
        
433
451
                raise error
434
452
        else:
435
453
            if pid:
436
 
                logger.warning(u"Checker was a zombie")
 
454
                logger.warning("Checker was a zombie")
437
455
                gobject.source_remove(self.checker_callback_tag)
438
456
                self.checker_callback(pid, status,
439
457
                                      self.current_checker_command)
444
462
                command = self.checker_command % self.host
445
463
            except TypeError:
446
464
                # Escape attributes for the shell
447
 
                escaped_attrs = dict((key,
448
 
                                      re.escape(unicode(str(val),
449
 
                                                        errors=
450
 
                                                        u'replace')))
451
 
                                     for key, val in
452
 
                                     vars(self).iteritems())
 
465
                escaped_attrs = dict(
 
466
                    (attr,
 
467
                     re.escape(unicode(str(getattr(self, attr, "")),
 
468
                                       errors=
 
469
                                       'replace')))
 
470
                    for attr in
 
471
                    self.runtime_expansions)
 
472
 
453
473
                try:
454
474
                    command = self.checker_command % escaped_attrs
455
475
                except TypeError, error:
456
 
                    logger.error(u'Could not format string "%s":'
457
 
                                 u' %s', self.checker_command, error)
 
476
                    logger.error('Could not format string "%s":'
 
477
                                 ' %s', self.checker_command, error)
458
478
                    return True # Try again later
459
479
            self.current_checker_command = command
460
480
            try:
461
 
                logger.info(u"Starting checker %r for %s",
 
481
                logger.info("Starting checker %r for %s",
462
482
                            command, self.name)
463
483
                # We don't need to redirect stdout and stderr, since
464
484
                # in normal mode, that is already done by daemon(),
466
486
                # always replaced by /dev/null.)
467
487
                self.checker = subprocess.Popen(command,
468
488
                                                close_fds=True,
469
 
                                                shell=True, cwd=u"/")
 
489
                                                shell=True, cwd="/")
470
490
                self.checker_callback_tag = (gobject.child_watch_add
471
491
                                             (self.checker.pid,
472
492
                                              self.checker_callback,
478
498
                    gobject.source_remove(self.checker_callback_tag)
479
499
                    self.checker_callback(pid, status, command)
480
500
            except OSError, error:
481
 
                logger.error(u"Failed to start subprocess: %s",
 
501
                logger.error("Failed to start subprocess: %s",
482
502
                             error)
483
503
        # Re-run this periodically if run by gobject.timeout_add
484
504
        return True
488
508
        if self.checker_callback_tag:
489
509
            gobject.source_remove(self.checker_callback_tag)
490
510
            self.checker_callback_tag = None
491
 
        if getattr(self, u"checker", None) is None:
 
511
        if getattr(self, "checker", None) is None:
492
512
            return
493
 
        logger.debug(u"Stopping checker for %(name)s", vars(self))
 
513
        logger.debug("Stopping checker for %(name)s", vars(self))
494
514
        try:
495
515
            os.kill(self.checker.pid, signal.SIGTERM)
496
516
            #time.sleep(0.5)
501
521
                raise
502
522
        self.checker = None
503
523
 
504
 
def dbus_service_property(dbus_interface, signature=u"v",
505
 
                          access=u"readwrite", byte_arrays=False):
 
524
def dbus_service_property(dbus_interface, signature="v",
 
525
                          access="readwrite", byte_arrays=False):
506
526
    """Decorators for marking methods of a DBusObjectWithProperties to
507
527
    become properties on the D-Bus.
508
528
    
515
535
    """
516
536
    # Encoding deeply encoded byte arrays is not supported yet by the
517
537
    # "Set" method, so we fail early here:
518
 
    if byte_arrays and signature != u"ay":
519
 
        raise ValueError(u"Byte arrays not supported for non-'ay'"
520
 
                         u" signature %r" % signature)
 
538
    if byte_arrays and signature != "ay":
 
539
        raise ValueError("Byte arrays not supported for non-'ay'"
 
540
                         " signature %r" % signature)
521
541
    def decorator(func):
522
542
        func._dbus_is_property = True
523
543
        func._dbus_interface = dbus_interface
524
544
        func._dbus_signature = signature
525
545
        func._dbus_access = access
526
546
        func._dbus_name = func.__name__
527
 
        if func._dbus_name.endswith(u"_dbus_property"):
 
547
        if func._dbus_name.endswith("_dbus_property"):
528
548
            func._dbus_name = func._dbus_name[:-14]
529
 
        func._dbus_get_args_options = {u'byte_arrays': byte_arrays }
 
549
        func._dbus_get_args_options = {'byte_arrays': byte_arrays }
530
550
        return func
531
551
    return decorator
532
552
 
560
580
    
561
581
    @staticmethod
562
582
    def _is_dbus_property(obj):
563
 
        return getattr(obj, u"_dbus_is_property", False)
 
583
        return getattr(obj, "_dbus_is_property", False)
564
584
    
565
585
    def _get_all_dbus_properties(self):
566
586
        """Returns a generator of (name, attribute) pairs
574
594
        property with the specified name and interface.
575
595
        """
576
596
        for name in (property_name,
577
 
                     property_name + u"_dbus_property"):
 
597
                     property_name + "_dbus_property"):
578
598
            prop = getattr(self, name, None)
579
599
            if (prop is None
580
600
                or not self._is_dbus_property(prop)
584
604
                continue
585
605
            return prop
586
606
        # No such property
587
 
        raise DBusPropertyNotFound(self.dbus_object_path + u":"
588
 
                                   + interface_name + u"."
 
607
        raise DBusPropertyNotFound(self.dbus_object_path + ":"
 
608
                                   + interface_name + "."
589
609
                                   + property_name)
590
610
    
591
 
    @dbus.service.method(dbus.PROPERTIES_IFACE, in_signature=u"ss",
592
 
                         out_signature=u"v")
 
611
    @dbus.service.method(dbus.PROPERTIES_IFACE, in_signature="ss",
 
612
                         out_signature="v")
593
613
    def Get(self, interface_name, property_name):
594
614
        """Standard D-Bus property Get() method, see D-Bus standard.
595
615
        """
596
616
        prop = self._get_dbus_property(interface_name, property_name)
597
 
        if prop._dbus_access == u"write":
 
617
        if prop._dbus_access == "write":
598
618
            raise DBusPropertyAccessException(property_name)
599
619
        value = prop()
600
 
        if not hasattr(value, u"variant_level"):
 
620
        if not hasattr(value, "variant_level"):
601
621
            return value
602
622
        return type(value)(value, variant_level=value.variant_level+1)
603
623
    
604
 
    @dbus.service.method(dbus.PROPERTIES_IFACE, in_signature=u"ssv")
 
624
    @dbus.service.method(dbus.PROPERTIES_IFACE, in_signature="ssv")
605
625
    def Set(self, interface_name, property_name, value):
606
626
        """Standard D-Bus property Set() method, see D-Bus standard.
607
627
        """
608
628
        prop = self._get_dbus_property(interface_name, property_name)
609
 
        if prop._dbus_access == u"read":
 
629
        if prop._dbus_access == "read":
610
630
            raise DBusPropertyAccessException(property_name)
611
 
        if prop._dbus_get_args_options[u"byte_arrays"]:
 
631
        if prop._dbus_get_args_options["byte_arrays"]:
612
632
            # The byte_arrays option is not supported yet on
613
633
            # signatures other than "ay".
614
 
            if prop._dbus_signature != u"ay":
 
634
            if prop._dbus_signature != "ay":
615
635
                raise ValueError
616
636
            value = dbus.ByteArray(''.join(unichr(byte)
617
637
                                           for byte in value))
618
638
        prop(value)
619
639
    
620
 
    @dbus.service.method(dbus.PROPERTIES_IFACE, in_signature=u"s",
621
 
                         out_signature=u"a{sv}")
 
640
    @dbus.service.method(dbus.PROPERTIES_IFACE, in_signature="s",
 
641
                         out_signature="a{sv}")
622
642
    def GetAll(self, interface_name):
623
643
        """Standard D-Bus property GetAll() method, see D-Bus
624
644
        standard.
632
652
                # Interface non-empty but did not match
633
653
                continue
634
654
            # Ignore write-only properties
635
 
            if prop._dbus_access == u"write":
 
655
            if prop._dbus_access == "write":
636
656
                continue
637
657
            value = prop()
638
 
            if not hasattr(value, u"variant_level"):
 
658
            if not hasattr(value, "variant_level"):
639
659
                all[name] = value
640
660
                continue
641
661
            all[name] = type(value)(value, variant_level=
642
662
                                    value.variant_level+1)
643
 
        return dbus.Dictionary(all, signature=u"sv")
 
663
        return dbus.Dictionary(all, signature="sv")
644
664
    
645
665
    @dbus.service.method(dbus.INTROSPECTABLE_IFACE,
646
 
                         out_signature=u"s",
 
666
                         out_signature="s",
647
667
                         path_keyword='object_path',
648
668
                         connection_keyword='connection')
649
669
    def Introspect(self, object_path, connection):
654
674
        try:
655
675
            document = xml.dom.minidom.parseString(xmlstring)
656
676
            def make_tag(document, name, prop):
657
 
                e = document.createElement(u"property")
658
 
                e.setAttribute(u"name", name)
659
 
                e.setAttribute(u"type", prop._dbus_signature)
660
 
                e.setAttribute(u"access", prop._dbus_access)
 
677
                e = document.createElement("property")
 
678
                e.setAttribute("name", name)
 
679
                e.setAttribute("type", prop._dbus_signature)
 
680
                e.setAttribute("access", prop._dbus_access)
661
681
                return e
662
 
            for if_tag in document.getElementsByTagName(u"interface"):
 
682
            for if_tag in document.getElementsByTagName("interface"):
663
683
                for tag in (make_tag(document, name, prop)
664
684
                            for name, prop
665
685
                            in self._get_all_dbus_properties()
666
686
                            if prop._dbus_interface
667
 
                            == if_tag.getAttribute(u"name")):
 
687
                            == if_tag.getAttribute("name")):
668
688
                    if_tag.appendChild(tag)
669
689
                # Add the names to the return values for the
670
690
                # "org.freedesktop.DBus.Properties" methods
671
 
                if (if_tag.getAttribute(u"name")
672
 
                    == u"org.freedesktop.DBus.Properties"):
673
 
                    for cn in if_tag.getElementsByTagName(u"method"):
674
 
                        if cn.getAttribute(u"name") == u"Get":
675
 
                            for arg in cn.getElementsByTagName(u"arg"):
676
 
                                if (arg.getAttribute(u"direction")
677
 
                                    == u"out"):
678
 
                                    arg.setAttribute(u"name", u"value")
679
 
                        elif cn.getAttribute(u"name") == u"GetAll":
680
 
                            for arg in cn.getElementsByTagName(u"arg"):
681
 
                                if (arg.getAttribute(u"direction")
682
 
                                    == u"out"):
683
 
                                    arg.setAttribute(u"name", u"props")
684
 
            xmlstring = document.toxml(u"utf-8")
 
691
                if (if_tag.getAttribute("name")
 
692
                    == "org.freedesktop.DBus.Properties"):
 
693
                    for cn in if_tag.getElementsByTagName("method"):
 
694
                        if cn.getAttribute("name") == "Get":
 
695
                            for arg in cn.getElementsByTagName("arg"):
 
696
                                if (arg.getAttribute("direction")
 
697
                                    == "out"):
 
698
                                    arg.setAttribute("name", "value")
 
699
                        elif cn.getAttribute("name") == "GetAll":
 
700
                            for arg in cn.getElementsByTagName("arg"):
 
701
                                if (arg.getAttribute("direction")
 
702
                                    == "out"):
 
703
                                    arg.setAttribute("name", "props")
 
704
            xmlstring = document.toxml("utf-8")
685
705
            document.unlink()
686
706
        except (AttributeError, xml.dom.DOMException,
687
707
                xml.parsers.expat.ExpatError), error:
688
 
            logger.error(u"Failed to override Introspection method",
 
708
            logger.error("Failed to override Introspection method",
689
709
                         error)
690
710
        return xmlstring
691
711
 
697
717
    dbus_object_path: dbus.ObjectPath
698
718
    bus: dbus.SystemBus()
699
719
    """
 
720
    
 
721
    runtime_expansions = (Client.runtime_expansions
 
722
                          + ("dbus_object_path",))
 
723
    
700
724
    # dbus.service.Object doesn't use super(), so we can't either.
701
725
    
702
726
    def __init__(self, bus = None, *args, **kwargs):
 
727
        self._approvals_pending = 0
703
728
        self.bus = bus
704
729
        Client.__init__(self, *args, **kwargs)
705
730
        # Only now, when this client is initialized, can it show up on
706
731
        # the D-Bus
 
732
        client_object_name = unicode(self.name).translate(
 
733
            {ord("."): ord("_"),
 
734
             ord("-"): ord("_")})
707
735
        self.dbus_object_path = (dbus.ObjectPath
708
 
                                 (u"/clients/"
709
 
                                  + self.name.replace(u".", u"_")))
 
736
                                 ("/clients/" + client_object_name))
710
737
        DBusObjectWithProperties.__init__(self, self.bus,
711
738
                                          self.dbus_object_path)
 
739
        
 
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
712
755
    
713
756
    @staticmethod
714
757
    def _datetime_to_dbus(dt, variant_level=0):
717
760
                           variant_level=variant_level)
718
761
    
719
762
    def enable(self):
720
 
        oldstate = getattr(self, u"enabled", False)
 
763
        oldstate = getattr(self, "enabled", False)
721
764
        r = Client.enable(self)
722
765
        if oldstate != self.enabled:
723
766
            # Emit D-Bus signals
724
 
            self.PropertyChanged(dbus.String(u"enabled"),
 
767
            self.PropertyChanged(dbus.String("Enabled"),
725
768
                                 dbus.Boolean(True, variant_level=1))
726
769
            self.PropertyChanged(
727
 
                dbus.String(u"last_enabled"),
 
770
                dbus.String("LastEnabled"),
728
771
                self._datetime_to_dbus(self.last_enabled,
729
772
                                       variant_level=1))
730
773
        return r
731
774
    
732
775
    def disable(self, quiet = False):
733
 
        oldstate = getattr(self, u"enabled", False)
 
776
        oldstate = getattr(self, "enabled", False)
734
777
        r = Client.disable(self, quiet=quiet)
735
778
        if not quiet and oldstate != self.enabled:
736
779
            # Emit D-Bus signal
737
 
            self.PropertyChanged(dbus.String(u"enabled"),
 
780
            self.PropertyChanged(dbus.String("Enabled"),
738
781
                                 dbus.Boolean(False, variant_level=1))
739
782
        return r
740
783
    
743
786
            self.remove_from_connection()
744
787
        except LookupError:
745
788
            pass
746
 
        if hasattr(DBusObjectWithProperties, u"__del__"):
 
789
        if hasattr(DBusObjectWithProperties, "__del__"):
747
790
            DBusObjectWithProperties.__del__(self, *args, **kwargs)
748
791
        Client.__del__(self, *args, **kwargs)
749
792
    
752
795
        self.checker_callback_tag = None
753
796
        self.checker = None
754
797
        # Emit D-Bus signal
755
 
        self.PropertyChanged(dbus.String(u"checker_running"),
 
798
        self.PropertyChanged(dbus.String("CheckerRunning"),
756
799
                             dbus.Boolean(False, variant_level=1))
757
800
        if os.WIFEXITED(condition):
758
801
            exitstatus = os.WEXITSTATUS(condition)
773
816
        r = Client.checked_ok(self, *args, **kwargs)
774
817
        # Emit D-Bus signal
775
818
        self.PropertyChanged(
776
 
            dbus.String(u"last_checked_ok"),
 
819
            dbus.String("LastCheckedOK"),
777
820
            (self._datetime_to_dbus(self.last_checked_ok,
778
821
                                    variant_level=1)))
779
822
        return r
780
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
    
781
833
    def start_checker(self, *args, **kwargs):
782
834
        old_checker = self.checker
783
835
        if self.checker is not None:
791
843
            # Emit D-Bus signal
792
844
            self.CheckerStarted(self.current_checker_command)
793
845
            self.PropertyChanged(
794
 
                dbus.String(u"checker_running"),
 
846
                dbus.String("CheckerRunning"),
795
847
                dbus.Boolean(True, variant_level=1))
796
848
        return r
797
849
    
798
850
    def stop_checker(self, *args, **kwargs):
799
 
        old_checker = getattr(self, u"checker", None)
 
851
        old_checker = getattr(self, "checker", None)
800
852
        r = Client.stop_checker(self, *args, **kwargs)
801
853
        if (old_checker is not None
802
 
            and getattr(self, u"checker", None) is None):
803
 
            self.PropertyChanged(dbus.String(u"checker_running"),
 
854
            and getattr(self, "checker", None) is None):
 
855
            self.PropertyChanged(dbus.String("CheckerRunning"),
804
856
                                 dbus.Boolean(False, variant_level=1))
805
857
        return r
806
858
 
809
861
        return False
810
862
    
811
863
    def approve(self, value=True):
 
864
        self.send_changedstate()
812
865
        self._approved = value
813
 
        gobject.timeout_add(self._timedelta_to_milliseconds(self.approved_duration, self._reset_approved))
814
 
 
815
 
    def approved_pending(self):
816
 
        return self.approvals_pending > 0
817
 
 
 
866
        gobject.timeout_add(self._timedelta_to_milliseconds
 
867
                            (self.approval_duration),
 
868
                            self._reset_approved)
 
869
    
818
870
    
819
871
    ## D-Bus methods, signals & properties
820
 
    _interface = u"se.bsnet.fukt.Mandos.Client"
 
872
    _interface = "se.bsnet.fukt.Mandos.Client"
821
873
    
822
874
    ## Signals
823
875
    
824
876
    # CheckerCompleted - signal
825
 
    @dbus.service.signal(_interface, signature=u"nxs")
 
877
    @dbus.service.signal(_interface, signature="nxs")
826
878
    def CheckerCompleted(self, exitcode, waitstatus, command):
827
879
        "D-Bus signal"
828
880
        pass
829
881
    
830
882
    # CheckerStarted - signal
831
 
    @dbus.service.signal(_interface, signature=u"s")
 
883
    @dbus.service.signal(_interface, signature="s")
832
884
    def CheckerStarted(self, command):
833
885
        "D-Bus signal"
834
886
        pass
835
887
    
836
888
    # PropertyChanged - signal
837
 
    @dbus.service.signal(_interface, signature=u"sv")
 
889
    @dbus.service.signal(_interface, signature="sv")
838
890
    def PropertyChanged(self, property, value):
839
891
        "D-Bus signal"
840
892
        pass
841
893
    
842
894
    # GotSecret - signal
843
 
    # Is sent after succesfull transfer of secret from mandos-server to mandos-client
844
895
    @dbus.service.signal(_interface)
845
896
    def GotSecret(self):
846
 
        "D-Bus signal"
 
897
        """D-Bus signal
 
898
        Is sent after a successful transfer of secret from the Mandos
 
899
        server to mandos-client
 
900
        """
847
901
        pass
848
902
    
849
903
    # Rejected - signal
850
 
    @dbus.service.signal(_interface, signature=u"s")
 
904
    @dbus.service.signal(_interface, signature="s")
851
905
    def Rejected(self, reason):
852
906
        "D-Bus signal"
853
907
        pass
854
908
    
855
909
    # NeedApproval - signal
856
 
    @dbus.service.signal(_interface, signature=u"db")
 
910
    @dbus.service.signal(_interface, signature="tb")
857
911
    def NeedApproval(self, timeout, default):
858
912
        "D-Bus signal"
859
 
        pass
 
913
        return self.need_approval()
860
914
    
861
915
    ## Methods
862
 
 
 
916
    
863
917
    # Approve - method
864
 
    @dbus.service.method(_interface, in_signature=u"b")
 
918
    @dbus.service.method(_interface, in_signature="b")
865
919
    def Approve(self, value):
866
920
        self.approve(value)
867
 
 
 
921
    
868
922
    # CheckedOK - method
869
923
    @dbus.service.method(_interface)
870
924
    def CheckedOK(self):
895
949
    
896
950
    ## Properties
897
951
    
898
 
    # approved_pending - property
899
 
    @dbus_service_property(_interface, signature=u"b", access=u"read")
900
 
    def approved_pending_dbus_property(self):
901
 
        return dbus.Boolean(self.approved_pending())
902
 
    
903
 
    # approved_by_default - property
904
 
    @dbus_service_property(_interface, signature=u"b",
905
 
                           access=u"readwrite")
906
 
    def approved_by_default_dbus_property(self):
907
 
        return dbus.Boolean(self.approved_by_default)
908
 
    
909
 
    # approved_delay - property
910
 
    @dbus_service_property(_interface, signature=u"t",
911
 
                           access=u"readwrite")
912
 
    def approved_delay_dbus_property(self):
913
 
        return dbus.UInt64(self.approved_delay_milliseconds())
914
 
    
915
 
    # approved_duration - property
916
 
    @dbus_service_property(_interface, signature=u"t",
917
 
                           access=u"readwrite")
918
 
    def approved_duration_dbus_property(self):
919
 
        return dbus.UInt64(self._timedelta_to_milliseconds(
920
 
                self.approved_duration))
921
 
    
922
 
    # name - property
923
 
    @dbus_service_property(_interface, signature=u"s", access=u"read")
924
 
    def name_dbus_property(self):
 
952
    # ApprovalPending - property
 
953
    @dbus_service_property(_interface, signature="b", access="read")
 
954
    def ApprovalPending_dbus_property(self):
 
955
        return dbus.Boolean(bool(self.approvals_pending))
 
956
    
 
957
    # ApprovedByDefault - property
 
958
    @dbus_service_property(_interface, signature="b",
 
959
                           access="readwrite")
 
960
    def ApprovedByDefault_dbus_property(self, value=None):
 
961
        if value is None:       # get
 
962
            return dbus.Boolean(self.approved_by_default)
 
963
        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
    
 
968
    # ApprovalDelay - property
 
969
    @dbus_service_property(_interface, signature="t",
 
970
                           access="readwrite")
 
971
    def ApprovalDelay_dbus_property(self, value=None):
 
972
        if value is None:       # get
 
973
            return dbus.UInt64(self.approval_delay_milliseconds())
 
974
        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
    
 
979
    # ApprovalDuration - property
 
980
    @dbus_service_property(_interface, signature="t",
 
981
                           access="readwrite")
 
982
    def ApprovalDuration_dbus_property(self, value=None):
 
983
        if value is None:       # get
 
984
            return dbus.UInt64(self._timedelta_to_milliseconds(
 
985
                    self.approval_duration))
 
986
        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
    
 
991
    # Name - property
 
992
    @dbus_service_property(_interface, signature="s", access="read")
 
993
    def Name_dbus_property(self):
925
994
        return dbus.String(self.name)
926
995
    
927
 
    # fingerprint - property
928
 
    @dbus_service_property(_interface, signature=u"s", access=u"read")
929
 
    def fingerprint_dbus_property(self):
 
996
    # Fingerprint - property
 
997
    @dbus_service_property(_interface, signature="s", access="read")
 
998
    def Fingerprint_dbus_property(self):
930
999
        return dbus.String(self.fingerprint)
931
1000
    
932
 
    # host - property
933
 
    @dbus_service_property(_interface, signature=u"s",
934
 
                           access=u"readwrite")
935
 
    def host_dbus_property(self, value=None):
 
1001
    # Host - property
 
1002
    @dbus_service_property(_interface, signature="s",
 
1003
                           access="readwrite")
 
1004
    def Host_dbus_property(self, value=None):
936
1005
        if value is None:       # get
937
1006
            return dbus.String(self.host)
938
1007
        self.host = value
939
1008
        # Emit D-Bus signal
940
 
        self.PropertyChanged(dbus.String(u"host"),
 
1009
        self.PropertyChanged(dbus.String("Host"),
941
1010
                             dbus.String(value, variant_level=1))
942
1011
    
943
 
    # created - property
944
 
    @dbus_service_property(_interface, signature=u"s", access=u"read")
945
 
    def created_dbus_property(self):
 
1012
    # Created - property
 
1013
    @dbus_service_property(_interface, signature="s", access="read")
 
1014
    def Created_dbus_property(self):
946
1015
        return dbus.String(self._datetime_to_dbus(self.created))
947
1016
    
948
 
    # last_enabled - property
949
 
    @dbus_service_property(_interface, signature=u"s", access=u"read")
950
 
    def last_enabled_dbus_property(self):
 
1017
    # LastEnabled - property
 
1018
    @dbus_service_property(_interface, signature="s", access="read")
 
1019
    def LastEnabled_dbus_property(self):
951
1020
        if self.last_enabled is None:
952
 
            return dbus.String(u"")
 
1021
            return dbus.String("")
953
1022
        return dbus.String(self._datetime_to_dbus(self.last_enabled))
954
1023
    
955
 
    # enabled - property
956
 
    @dbus_service_property(_interface, signature=u"b",
957
 
                           access=u"readwrite")
958
 
    def enabled_dbus_property(self, value=None):
 
1024
    # Enabled - property
 
1025
    @dbus_service_property(_interface, signature="b",
 
1026
                           access="readwrite")
 
1027
    def Enabled_dbus_property(self, value=None):
959
1028
        if value is None:       # get
960
1029
            return dbus.Boolean(self.enabled)
961
1030
        if value:
963
1032
        else:
964
1033
            self.disable()
965
1034
    
966
 
    # last_checked_ok - property
967
 
    @dbus_service_property(_interface, signature=u"s",
968
 
                           access=u"readwrite")
969
 
    def last_checked_ok_dbus_property(self, value=None):
 
1035
    # LastCheckedOK - property
 
1036
    @dbus_service_property(_interface, signature="s",
 
1037
                           access="readwrite")
 
1038
    def LastCheckedOK_dbus_property(self, value=None):
970
1039
        if value is not None:
971
1040
            self.checked_ok()
972
1041
            return
973
1042
        if self.last_checked_ok is None:
974
 
            return dbus.String(u"")
 
1043
            return dbus.String("")
975
1044
        return dbus.String(self._datetime_to_dbus(self
976
1045
                                                  .last_checked_ok))
977
1046
    
978
 
    # timeout - property
979
 
    @dbus_service_property(_interface, signature=u"t",
980
 
                           access=u"readwrite")
981
 
    def timeout_dbus_property(self, value=None):
 
1047
    # LastApprovalRequest - property
 
1048
    @dbus_service_property(_interface, signature="s", access="read")
 
1049
    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))
 
1055
    
 
1056
    # Timeout - property
 
1057
    @dbus_service_property(_interface, signature="t",
 
1058
                           access="readwrite")
 
1059
    def Timeout_dbus_property(self, value=None):
982
1060
        if value is None:       # get
983
1061
            return dbus.UInt64(self.timeout_milliseconds())
984
1062
        self.timeout = datetime.timedelta(0, 0, 0, value)
985
1063
        # Emit D-Bus signal
986
 
        self.PropertyChanged(dbus.String(u"timeout"),
 
1064
        self.PropertyChanged(dbus.String("Timeout"),
987
1065
                             dbus.UInt64(value, variant_level=1))
988
 
        if getattr(self, u"disable_initiator_tag", None) is None:
 
1066
        if getattr(self, "disable_initiator_tag", None) is None:
989
1067
            return
990
1068
        # Reschedule timeout
991
1069
        gobject.source_remove(self.disable_initiator_tag)
1003
1081
            self.disable_initiator_tag = (gobject.timeout_add
1004
1082
                                          (time_to_die, self.disable))
1005
1083
    
1006
 
    # interval - property
1007
 
    @dbus_service_property(_interface, signature=u"t",
1008
 
                           access=u"readwrite")
1009
 
    def interval_dbus_property(self, value=None):
 
1084
    # Interval - property
 
1085
    @dbus_service_property(_interface, signature="t",
 
1086
                           access="readwrite")
 
1087
    def Interval_dbus_property(self, value=None):
1010
1088
        if value is None:       # get
1011
1089
            return dbus.UInt64(self.interval_milliseconds())
1012
1090
        self.interval = datetime.timedelta(0, 0, 0, value)
1013
1091
        # Emit D-Bus signal
1014
 
        self.PropertyChanged(dbus.String(u"interval"),
 
1092
        self.PropertyChanged(dbus.String("Interval"),
1015
1093
                             dbus.UInt64(value, variant_level=1))
1016
 
        if getattr(self, u"checker_initiator_tag", None) is None:
 
1094
        if getattr(self, "checker_initiator_tag", None) is None:
1017
1095
            return
1018
1096
        # Reschedule checker run
1019
1097
        gobject.source_remove(self.checker_initiator_tag)
1021
1099
                                      (value, self.start_checker))
1022
1100
        self.start_checker()    # Start one now, too
1023
1101
 
1024
 
    # checker - property
1025
 
    @dbus_service_property(_interface, signature=u"s",
1026
 
                           access=u"readwrite")
1027
 
    def checker_dbus_property(self, value=None):
 
1102
    # Checker - property
 
1103
    @dbus_service_property(_interface, signature="s",
 
1104
                           access="readwrite")
 
1105
    def Checker_dbus_property(self, value=None):
1028
1106
        if value is None:       # get
1029
1107
            return dbus.String(self.checker_command)
1030
1108
        self.checker_command = value
1031
1109
        # Emit D-Bus signal
1032
 
        self.PropertyChanged(dbus.String(u"checker"),
 
1110
        self.PropertyChanged(dbus.String("Checker"),
1033
1111
                             dbus.String(self.checker_command,
1034
1112
                                         variant_level=1))
1035
1113
    
1036
 
    # checker_running - property
1037
 
    @dbus_service_property(_interface, signature=u"b",
1038
 
                           access=u"readwrite")
1039
 
    def checker_running_dbus_property(self, value=None):
 
1114
    # CheckerRunning - property
 
1115
    @dbus_service_property(_interface, signature="b",
 
1116
                           access="readwrite")
 
1117
    def CheckerRunning_dbus_property(self, value=None):
1040
1118
        if value is None:       # get
1041
1119
            return dbus.Boolean(self.checker is not None)
1042
1120
        if value:
1044
1122
        else:
1045
1123
            self.stop_checker()
1046
1124
    
1047
 
    # object_path - property
1048
 
    @dbus_service_property(_interface, signature=u"o", access=u"read")
1049
 
    def object_path_dbus_property(self):
 
1125
    # ObjectPath - property
 
1126
    @dbus_service_property(_interface, signature="o", access="read")
 
1127
    def ObjectPath_dbus_property(self):
1050
1128
        return self.dbus_object_path # is already a dbus.ObjectPath
1051
1129
    
1052
 
    # secret = property
1053
 
    @dbus_service_property(_interface, signature=u"ay",
1054
 
                           access=u"write", byte_arrays=True)
1055
 
    def secret_dbus_property(self, value):
 
1130
    # Secret = property
 
1131
    @dbus_service_property(_interface, signature="ay",
 
1132
                           access="write", byte_arrays=True)
 
1133
    def Secret_dbus_property(self, value):
1056
1134
        self.secret = str(value)
1057
1135
    
1058
1136
    del _interface
1092
1170
    
1093
1171
    def handle(self):
1094
1172
        with contextlib.closing(self.server.child_pipe) as child_pipe:
1095
 
            logger.info(u"TCP connection from: %s",
 
1173
            logger.info("TCP connection from: %s",
1096
1174
                        unicode(self.client_address))
1097
 
            logger.debug(u"Pipe FD: %d",
 
1175
            logger.debug("Pipe FD: %d",
1098
1176
                         self.server.child_pipe.fileno())
1099
1177
 
1100
1178
            session = (gnutls.connection
1107
1185
            # no X.509 keys are added to it.  Therefore, we can use it
1108
1186
            # here despite using OpenPGP certificates.
1109
1187
 
1110
 
            #priority = u':'.join((u"NONE", u"+VERS-TLS1.1",
1111
 
            #                      u"+AES-256-CBC", u"+SHA1",
1112
 
            #                      u"+COMP-NULL", u"+CTYPE-OPENPGP",
1113
 
            #                      u"+DHE-DSS"))
 
1188
            #priority = ':'.join(("NONE", "+VERS-TLS1.1",
 
1189
            #                      "+AES-256-CBC", "+SHA1",
 
1190
            #                      "+COMP-NULL", "+CTYPE-OPENPGP",
 
1191
            #                      "+DHE-DSS"))
1114
1192
            # Use a fallback default, since this MUST be set.
1115
1193
            priority = self.server.gnutls_priority
1116
1194
            if priority is None:
1117
 
                priority = u"NORMAL"
 
1195
                priority = "NORMAL"
1118
1196
            (gnutls.library.functions
1119
1197
             .gnutls_priority_set_direct(session._c_object,
1120
1198
                                         priority, None))
1122
1200
            # Start communication using the Mandos protocol
1123
1201
            # Get protocol number
1124
1202
            line = self.request.makefile().readline()
1125
 
            logger.debug(u"Protocol version: %r", line)
 
1203
            logger.debug("Protocol version: %r", line)
1126
1204
            try:
1127
1205
                if int(line.strip().split()[0]) > 1:
1128
1206
                    raise RuntimeError
1129
1207
            except (ValueError, IndexError, RuntimeError), error:
1130
 
                logger.error(u"Unknown protocol version: %s", error)
 
1208
                logger.error("Unknown protocol version: %s", error)
1131
1209
                return
1132
1210
 
1133
1211
            # Start GnuTLS connection
1134
1212
            try:
1135
1213
                session.handshake()
1136
1214
            except gnutls.errors.GNUTLSError, error:
1137
 
                logger.warning(u"Handshake failed: %s", error)
 
1215
                logger.warning("Handshake failed: %s", error)
1138
1216
                # Do not run session.bye() here: the session is not
1139
1217
                # established.  Just abandon the request.
1140
1218
                return
1141
 
            logger.debug(u"Handshake succeeded")
 
1219
            logger.debug("Handshake succeeded")
1142
1220
 
1143
1221
            approval_required = False
1144
1222
            try:
1146
1224
                    fpr = self.fingerprint(self.peer_certificate
1147
1225
                                           (session))
1148
1226
                except (TypeError, gnutls.errors.GNUTLSError), error:
1149
 
                    logger.warning(u"Bad certificate: %s", error)
 
1227
                    logger.warning("Bad certificate: %s", error)
1150
1228
                    return
1151
 
                logger.debug(u"Fingerprint: %s", fpr)
 
1229
                logger.debug("Fingerprint: %s", fpr)
1152
1230
 
1153
1231
                try:
1154
1232
                    client = ProxyClient(child_pipe, fpr,
1156
1234
                except KeyError:
1157
1235
                    return
1158
1236
                
1159
 
                if client.approved_delay:
1160
 
                    delay = client.approved_delay
 
1237
                if client.approval_delay:
 
1238
                    delay = client.approval_delay
1161
1239
                    client.approvals_pending += 1
1162
1240
                    approval_required = True
1163
1241
                
1164
1242
                while True:
1165
1243
                    if not client.enabled:
1166
 
                        logger.warning(u"Client %s is disabled",
 
1244
                        logger.warning("Client %s is disabled",
1167
1245
                                       client.name)
1168
1246
                        if self.server.use_dbus:
1169
1247
                            # Emit D-Bus signal
1170
1248
                            client.Rejected("Disabled")                    
1171
1249
                        return
1172
1250
                    
1173
 
                    if client._approved or not client.approved_delay:
 
1251
                    if client._approved or not client.approval_delay:
1174
1252
                        #We are approved or approval is disabled
1175
1253
                        break
1176
1254
                    elif client._approved is None:
1177
 
                        logger.info(u"Client %s need approval",
 
1255
                        logger.info("Client %s needs approval",
1178
1256
                                    client.name)
1179
1257
                        if self.server.use_dbus:
1180
1258
                            # Emit D-Bus signal
1181
1259
                            client.NeedApproval(
1182
 
                                client.approved_delay_milliseconds(),
 
1260
                                client.approval_delay_milliseconds(),
1183
1261
                                client.approved_by_default)
1184
1262
                    else:
1185
 
                        logger.warning(u"Client %s was not approved",
 
1263
                        logger.warning("Client %s was not approved",
1186
1264
                                       client.name)
1187
1265
                        if self.server.use_dbus:
1188
1266
                            # Emit D-Bus signal
1189
 
                            client.Rejected("Disapproved")
 
1267
                            client.Rejected("Denied")
1190
1268
                        return
1191
1269
                    
1192
1270
                    #wait until timeout or approved
1203
1281
                                           client.name)
1204
1282
                            if self.server.use_dbus:
1205
1283
                                # Emit D-Bus signal
1206
 
                                client.Rejected("Time out")
 
1284
                                client.Rejected("Approval timed out")
1207
1285
                            return
1208
1286
                        else:
1209
1287
                            break
1212
1290
                
1213
1291
                sent_size = 0
1214
1292
                while sent_size < len(client.secret):
1215
 
                    # XXX handle session exception
1216
 
                    sent = session.send(client.secret[sent_size:])
1217
 
                    logger.debug(u"Sent: %d, remaining: %d",
 
1293
                    try:
 
1294
                        sent = session.send(client.secret[sent_size:])
 
1295
                    except (gnutls.errors.GNUTLSError), error:
 
1296
                        logger.warning("gnutls send failed")
 
1297
                        return
 
1298
                    logger.debug("Sent: %d, remaining: %d",
1218
1299
                                 sent, len(client.secret)
1219
1300
                                 - (sent_size + sent))
1220
1301
                    sent_size += sent
1221
1302
 
1222
 
                logger.info(u"Sending secret to %s", client.name)
 
1303
                logger.info("Sending secret to %s", client.name)
1223
1304
                # bump the timeout as if seen
1224
1305
                client.checked_ok()
1225
1306
                if self.server.use_dbus:
1229
1310
            finally:
1230
1311
                if approval_required:
1231
1312
                    client.approvals_pending -= 1
1232
 
                session.bye()
 
1313
                try:
 
1314
                    session.bye()
 
1315
                except (gnutls.errors.GNUTLSError), error:
 
1316
                    logger.warning("GnuTLS bye failed")
1233
1317
    
1234
1318
    @staticmethod
1235
1319
    def peer_certificate(session):
1245
1329
                     .gnutls_certificate_get_peers
1246
1330
                     (session._c_object, ctypes.byref(list_size)))
1247
1331
        if not bool(cert_list) and list_size.value != 0:
1248
 
            raise gnutls.errors.GNUTLSError(u"error getting peer"
1249
 
                                            u" certificate")
 
1332
            raise gnutls.errors.GNUTLSError("error getting peer"
 
1333
                                            " certificate")
1250
1334
        if list_size.value == 0:
1251
1335
            return None
1252
1336
        cert = cert_list[0]
1278
1362
        if crtverify.value != 0:
1279
1363
            gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
1280
1364
            raise (gnutls.errors.CertificateSecurityError
1281
 
                   (u"Verify failed"))
 
1365
                   ("Verify failed"))
1282
1366
        # New buffer for the fingerprint
1283
1367
        buf = ctypes.create_string_buffer(20)
1284
1368
        buf_len = ctypes.c_size_t()
1291
1375
        # Convert the buffer to a Python bytestring
1292
1376
        fpr = ctypes.string_at(buf, buf_len.value)
1293
1377
        # Convert the bytestring to hexadecimal notation
1294
 
        hex_fpr = u''.join(u"%02X" % ord(char) for char in fpr)
 
1378
        hex_fpr = ''.join("%02X" % ord(char) for char in fpr)
1295
1379
        return hex_fpr
1296
1380
 
1297
1381
 
1322
1406
              self).process_request(request, client_address)
1323
1407
        self.child_pipe.close()
1324
1408
        self.add_pipe(parent_pipe)
1325
 
        
 
1409
 
1326
1410
    def add_pipe(self, parent_pipe):
1327
1411
        """Dummy function; override as necessary"""
1328
 
        pass
 
1412
        raise NotImplementedError
1329
1413
 
1330
1414
class IPv6_TCPServer(MultiprocessingMixInWithPipe,
1331
1415
                     socketserver.TCPServer, object):
1349
1433
        bind to an address or port if they were not specified."""
1350
1434
        if self.interface is not None:
1351
1435
            if SO_BINDTODEVICE is None:
1352
 
                logger.error(u"SO_BINDTODEVICE does not exist;"
1353
 
                             u" cannot bind to interface %s",
 
1436
                logger.error("SO_BINDTODEVICE does not exist;"
 
1437
                             " cannot bind to interface %s",
1354
1438
                             self.interface)
1355
1439
            else:
1356
1440
                try:
1357
1441
                    self.socket.setsockopt(socket.SOL_SOCKET,
1358
1442
                                           SO_BINDTODEVICE,
1359
1443
                                           str(self.interface
1360
 
                                               + u'\0'))
 
1444
                                               + '\0'))
1361
1445
                except socket.error, error:
1362
1446
                    if error[0] == errno.EPERM:
1363
 
                        logger.error(u"No permission to"
1364
 
                                     u" bind to interface %s",
 
1447
                        logger.error("No permission to"
 
1448
                                     " bind to interface %s",
1365
1449
                                     self.interface)
1366
1450
                    elif error[0] == errno.ENOPROTOOPT:
1367
 
                        logger.error(u"SO_BINDTODEVICE not available;"
1368
 
                                     u" cannot bind to interface %s",
 
1451
                        logger.error("SO_BINDTODEVICE not available;"
 
1452
                                     " cannot bind to interface %s",
1369
1453
                                     self.interface)
1370
1454
                    else:
1371
1455
                        raise
1373
1457
        if self.server_address[0] or self.server_address[1]:
1374
1458
            if not self.server_address[0]:
1375
1459
                if self.address_family == socket.AF_INET6:
1376
 
                    any_address = u"::" # in6addr_any
 
1460
                    any_address = "::" # in6addr_any
1377
1461
                else:
1378
1462
                    any_address = socket.INADDR_ANY
1379
1463
                self.server_address = (any_address,
1428
1512
    def handle_ipc(self, source, condition, parent_pipe=None,
1429
1513
                   client_object=None):
1430
1514
        condition_names = {
1431
 
            gobject.IO_IN: u"IN",   # There is data to read.
1432
 
            gobject.IO_OUT: u"OUT", # Data can be written (without
 
1515
            gobject.IO_IN: "IN",   # There is data to read.
 
1516
            gobject.IO_OUT: "OUT", # Data can be written (without
1433
1517
                                    # blocking).
1434
 
            gobject.IO_PRI: u"PRI", # There is urgent data to read.
1435
 
            gobject.IO_ERR: u"ERR", # Error condition.
1436
 
            gobject.IO_HUP: u"HUP"  # Hung up (the connection has been
 
1518
            gobject.IO_PRI: "PRI", # There is urgent data to read.
 
1519
            gobject.IO_ERR: "ERR", # Error condition.
 
1520
            gobject.IO_HUP: "HUP"  # Hung up (the connection has been
1437
1521
                                    # broken, usually for pipes and
1438
1522
                                    # sockets).
1439
1523
            }
1441
1525
                                       for cond, name in
1442
1526
                                       condition_names.iteritems()
1443
1527
                                       if cond & condition)
1444
 
        logger.debug(u"Handling IPC: FD = %d, condition = %s", source,
1445
 
                     conditions_string)
1446
 
 
1447
1528
        # error or the other end of multiprocessing.Pipe has closed
1448
 
        if condition & gobject.IO_HUP or condition & gobject.IO_ERR:
 
1529
        if condition & (gobject.IO_ERR | condition & gobject.IO_HUP):
1449
1530
            return False
1450
1531
        
1451
1532
        # Read a request from the child
1452
1533
        request = parent_pipe.recv()
1453
 
        logger.debug(u"IPC request: %s", repr(request))
1454
1534
        command = request[0]
1455
1535
        
1456
1536
        if command == 'init':
1462
1542
                    client = c
1463
1543
                    break
1464
1544
            else:
1465
 
                logger.warning(u"Client not found for fingerprint: %s, ad"
1466
 
                               u"dress: %s", fpr, address)
 
1545
                logger.warning("Client not found for fingerprint: %s, ad"
 
1546
                               "dress: %s", fpr, address)
1467
1547
                if self.use_dbus:
1468
1548
                    # Emit D-Bus signal
1469
 
                    mandos_dbus_service.ClientNotFound(fpr, address)
 
1549
                    mandos_dbus_service.ClientNotFound(fpr, address[0])
1470
1550
                parent_pipe.send(False)
1471
1551
                return False
1472
1552
            
1491
1571
                parent_pipe.send(('function',))
1492
1572
            else:
1493
1573
                parent_pipe.send(('data', client_object.__getattribute__(attrname)))
1494
 
 
 
1574
        
1495
1575
        if command == 'setattr':
1496
1576
            attrname = request[1]
1497
1577
            value = request[2]
1498
1578
            setattr(client_object, attrname, value)
1499
 
            
 
1579
 
1500
1580
        return True
1501
1581
 
1502
1582
 
1503
1583
def string_to_delta(interval):
1504
1584
    """Parse a string and return a datetime.timedelta
1505
1585
    
1506
 
    >>> string_to_delta(u'7d')
 
1586
    >>> string_to_delta('7d')
1507
1587
    datetime.timedelta(7)
1508
 
    >>> string_to_delta(u'60s')
 
1588
    >>> string_to_delta('60s')
1509
1589
    datetime.timedelta(0, 60)
1510
 
    >>> string_to_delta(u'60m')
 
1590
    >>> string_to_delta('60m')
1511
1591
    datetime.timedelta(0, 3600)
1512
 
    >>> string_to_delta(u'24h')
 
1592
    >>> string_to_delta('24h')
1513
1593
    datetime.timedelta(1)
1514
 
    >>> string_to_delta(u'1w')
 
1594
    >>> string_to_delta('1w')
1515
1595
    datetime.timedelta(7)
1516
 
    >>> string_to_delta(u'5m 30s')
 
1596
    >>> string_to_delta('5m 30s')
1517
1597
    datetime.timedelta(0, 330)
1518
1598
    """
1519
1599
    timevalue = datetime.timedelta(0)
1521
1601
        try:
1522
1602
            suffix = unicode(s[-1])
1523
1603
            value = int(s[:-1])
1524
 
            if suffix == u"d":
 
1604
            if suffix == "d":
1525
1605
                delta = datetime.timedelta(value)
1526
 
            elif suffix == u"s":
 
1606
            elif suffix == "s":
1527
1607
                delta = datetime.timedelta(0, value)
1528
 
            elif suffix == u"m":
 
1608
            elif suffix == "m":
1529
1609
                delta = datetime.timedelta(0, 0, 0, 0, value)
1530
 
            elif suffix == u"h":
 
1610
            elif suffix == "h":
1531
1611
                delta = datetime.timedelta(0, 0, 0, 0, 0, value)
1532
 
            elif suffix == u"w":
 
1612
            elif suffix == "w":
1533
1613
                delta = datetime.timedelta(0, 0, 0, 0, 0, 0, value)
1534
1614
            else:
1535
 
                raise ValueError(u"Unknown suffix %r" % suffix)
 
1615
                raise ValueError("Unknown suffix %r" % suffix)
1536
1616
        except (ValueError, IndexError), e:
1537
 
            raise ValueError(e.message)
 
1617
            raise ValueError(*(e.args))
1538
1618
        timevalue += delta
1539
1619
    return timevalue
1540
1620
 
1546
1626
    global if_nametoindex
1547
1627
    try:
1548
1628
        if_nametoindex = (ctypes.cdll.LoadLibrary
1549
 
                          (ctypes.util.find_library(u"c"))
 
1629
                          (ctypes.util.find_library("c"))
1550
1630
                          .if_nametoindex)
1551
1631
    except (OSError, AttributeError):
1552
 
        logger.warning(u"Doing if_nametoindex the hard way")
 
1632
        logger.warning("Doing if_nametoindex the hard way")
1553
1633
        def if_nametoindex(interface):
1554
1634
            "Get an interface index the hard way, i.e. using fcntl()"
1555
1635
            SIOCGIFINDEX = 0x8933  # From /usr/include/linux/sockios.h
1556
1636
            with contextlib.closing(socket.socket()) as s:
1557
1637
                ifreq = fcntl.ioctl(s, SIOCGIFINDEX,
1558
 
                                    struct.pack(str(u"16s16x"),
 
1638
                                    struct.pack(str("16s16x"),
1559
1639
                                                interface))
1560
 
            interface_index = struct.unpack(str(u"I"),
 
1640
            interface_index = struct.unpack(str("I"),
1561
1641
                                            ifreq[16:20])[0]
1562
1642
            return interface_index
1563
1643
    return if_nametoindex(interface)
1571
1651
        sys.exit()
1572
1652
    os.setsid()
1573
1653
    if not nochdir:
1574
 
        os.chdir(u"/")
 
1654
        os.chdir("/")
1575
1655
    if os.fork():
1576
1656
        sys.exit()
1577
1657
    if not noclose:
1579
1659
        null = os.open(os.path.devnull, os.O_NOCTTY | os.O_RDWR)
1580
1660
        if not stat.S_ISCHR(os.fstat(null).st_mode):
1581
1661
            raise OSError(errno.ENODEV,
1582
 
                          u"%s not a character device"
 
1662
                          "%s not a character device"
1583
1663
                          % os.path.devnull)
1584
1664
        os.dup2(null, sys.stdin.fileno())
1585
1665
        os.dup2(null, sys.stdout.fileno())
1594
1674
    # Parsing of options, both command line and config file
1595
1675
    
1596
1676
    parser = optparse.OptionParser(version = "%%prog %s" % version)
1597
 
    parser.add_option("-i", u"--interface", type=u"string",
1598
 
                      metavar="IF", help=u"Bind to interface IF")
1599
 
    parser.add_option("-a", u"--address", type=u"string",
1600
 
                      help=u"Address to listen for requests on")
1601
 
    parser.add_option("-p", u"--port", type=u"int",
1602
 
                      help=u"Port number to receive requests on")
1603
 
    parser.add_option("--check", action=u"store_true",
1604
 
                      help=u"Run self-test")
1605
 
    parser.add_option("--debug", action=u"store_true",
1606
 
                      help=u"Debug mode; run in foreground and log to"
1607
 
                      u" terminal")
1608
 
    parser.add_option("--priority", type=u"string", help=u"GnuTLS"
1609
 
                      u" priority string (see GnuTLS documentation)")
1610
 
    parser.add_option("--servicename", type=u"string",
1611
 
                      metavar=u"NAME", help=u"Zeroconf service name")
1612
 
    parser.add_option("--configdir", type=u"string",
1613
 
                      default=u"/etc/mandos", metavar=u"DIR",
1614
 
                      help=u"Directory to search for configuration"
1615
 
                      u" files")
1616
 
    parser.add_option("--no-dbus", action=u"store_false",
1617
 
                      dest=u"use_dbus", help=u"Do not provide D-Bus"
1618
 
                      u" system bus interface")
1619
 
    parser.add_option("--no-ipv6", action=u"store_false",
1620
 
                      dest=u"use_ipv6", help=u"Do not use IPv6")
 
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")
1621
1703
    options = parser.parse_args()[0]
1622
1704
    
1623
1705
    if options.check:
1626
1708
        sys.exit()
1627
1709
    
1628
1710
    # Default values for config file for server-global settings
1629
 
    server_defaults = { u"interface": u"",
1630
 
                        u"address": u"",
1631
 
                        u"port": u"",
1632
 
                        u"debug": u"False",
1633
 
                        u"priority":
1634
 
                        u"SECURE256:!CTYPE-X.509:+CTYPE-OPENPGP",
1635
 
                        u"servicename": u"Mandos",
1636
 
                        u"use_dbus": u"True",
1637
 
                        u"use_ipv6": u"True",
 
1711
    server_defaults = { "interface": "",
 
1712
                        "address": "",
 
1713
                        "port": "",
 
1714
                        "debug": "False",
 
1715
                        "priority":
 
1716
                        "SECURE256:!CTYPE-X.509:+CTYPE-OPENPGP",
 
1717
                        "servicename": "Mandos",
 
1718
                        "use_dbus": "True",
 
1719
                        "use_ipv6": "True",
 
1720
                        "debuglevel": "",
1638
1721
                        }
1639
1722
    
1640
1723
    # Parse config file for server-global settings
1641
1724
    server_config = configparser.SafeConfigParser(server_defaults)
1642
1725
    del server_defaults
1643
1726
    server_config.read(os.path.join(options.configdir,
1644
 
                                    u"mandos.conf"))
 
1727
                                    "mandos.conf"))
1645
1728
    # Convert the SafeConfigParser object to a dict
1646
1729
    server_settings = server_config.defaults()
1647
1730
    # Use the appropriate methods on the non-string config options
1648
 
    for option in (u"debug", u"use_dbus", u"use_ipv6"):
1649
 
        server_settings[option] = server_config.getboolean(u"DEFAULT",
 
1731
    for option in ("debug", "use_dbus", "use_ipv6"):
 
1732
        server_settings[option] = server_config.getboolean("DEFAULT",
1650
1733
                                                           option)
1651
1734
    if server_settings["port"]:
1652
 
        server_settings["port"] = server_config.getint(u"DEFAULT",
1653
 
                                                       u"port")
 
1735
        server_settings["port"] = server_config.getint("DEFAULT",
 
1736
                                                       "port")
1654
1737
    del server_config
1655
1738
    
1656
1739
    # Override the settings from the config file with command line
1657
1740
    # options, if set.
1658
 
    for option in (u"interface", u"address", u"port", u"debug",
1659
 
                   u"priority", u"servicename", u"configdir",
1660
 
                   u"use_dbus", u"use_ipv6"):
 
1741
    for option in ("interface", "address", "port", "debug",
 
1742
                   "priority", "servicename", "configdir",
 
1743
                   "use_dbus", "use_ipv6", "debuglevel"):
1661
1744
        value = getattr(options, option)
1662
1745
        if value is not None:
1663
1746
            server_settings[option] = value
1671
1754
    ##################################################################
1672
1755
    
1673
1756
    # For convenience
1674
 
    debug = server_settings[u"debug"]
1675
 
    use_dbus = server_settings[u"use_dbus"]
1676
 
    use_ipv6 = server_settings[u"use_ipv6"]
1677
 
    
1678
 
    if not debug:
1679
 
        syslogger.setLevel(logging.WARNING)
1680
 
        console.setLevel(logging.WARNING)
1681
 
    
1682
 
    if server_settings[u"servicename"] != u"Mandos":
 
1757
    debug = server_settings["debug"]
 
1758
    debuglevel = server_settings["debuglevel"]
 
1759
    use_dbus = server_settings["use_dbus"]
 
1760
    use_ipv6 = server_settings["use_ipv6"]
 
1761
 
 
1762
    if server_settings["servicename"] != "Mandos":
1683
1763
        syslogger.setFormatter(logging.Formatter
1684
 
                               (u'Mandos (%s) [%%(process)d]:'
1685
 
                                u' %%(levelname)s: %%(message)s'
1686
 
                                % server_settings[u"servicename"]))
 
1764
                               ('Mandos (%s) [%%(process)d]:'
 
1765
                                ' %%(levelname)s: %%(message)s'
 
1766
                                % server_settings["servicename"]))
1687
1767
    
1688
1768
    # Parse config file with clients
1689
 
    client_defaults = { u"timeout": u"1h",
1690
 
                        u"interval": u"5m",
1691
 
                        u"checker": u"fping -q -- %%(host)s",
1692
 
                        u"host": u"",
1693
 
                        u"approved_delay": u"5m",
1694
 
                        u"approved_duration": u"1s",
 
1769
    client_defaults = { "timeout": "1h",
 
1770
                        "interval": "5m",
 
1771
                        "checker": "fping -q -- %%(host)s",
 
1772
                        "host": "",
 
1773
                        "approval_delay": "0s",
 
1774
                        "approval_duration": "1s",
1695
1775
                        }
1696
1776
    client_config = configparser.SafeConfigParser(client_defaults)
1697
 
    client_config.read(os.path.join(server_settings[u"configdir"],
1698
 
                                    u"clients.conf"))
 
1777
    client_config.read(os.path.join(server_settings["configdir"],
 
1778
                                    "clients.conf"))
1699
1779
    
1700
1780
    global mandos_dbus_service
1701
1781
    mandos_dbus_service = None
1702
1782
    
1703
 
    tcp_server = MandosServer((server_settings[u"address"],
1704
 
                               server_settings[u"port"]),
 
1783
    tcp_server = MandosServer((server_settings["address"],
 
1784
                               server_settings["port"]),
1705
1785
                              ClientHandler,
1706
 
                              interface=server_settings[u"interface"],
 
1786
                              interface=(server_settings["interface"]
 
1787
                                         or None),
1707
1788
                              use_ipv6=use_ipv6,
1708
1789
                              gnutls_priority=
1709
 
                              server_settings[u"priority"],
 
1790
                              server_settings["priority"],
1710
1791
                              use_dbus=use_dbus)
1711
 
    pidfilename = u"/var/run/mandos.pid"
1712
 
    try:
1713
 
        pidfile = open(pidfilename, u"w")
1714
 
    except IOError:
1715
 
        logger.error(u"Could not open file %r", pidfilename)
 
1792
    if not debug:
 
1793
        pidfilename = "/var/run/mandos.pid"
 
1794
        try:
 
1795
            pidfile = open(pidfilename, "w")
 
1796
        except IOError:
 
1797
            logger.error("Could not open file %r", pidfilename)
1716
1798
    
1717
1799
    try:
1718
 
        uid = pwd.getpwnam(u"_mandos").pw_uid
1719
 
        gid = pwd.getpwnam(u"_mandos").pw_gid
 
1800
        uid = pwd.getpwnam("_mandos").pw_uid
 
1801
        gid = pwd.getpwnam("_mandos").pw_gid
1720
1802
    except KeyError:
1721
1803
        try:
1722
 
            uid = pwd.getpwnam(u"mandos").pw_uid
1723
 
            gid = pwd.getpwnam(u"mandos").pw_gid
 
1804
            uid = pwd.getpwnam("mandos").pw_uid
 
1805
            gid = pwd.getpwnam("mandos").pw_gid
1724
1806
        except KeyError:
1725
1807
            try:
1726
 
                uid = pwd.getpwnam(u"nobody").pw_uid
1727
 
                gid = pwd.getpwnam(u"nobody").pw_gid
 
1808
                uid = pwd.getpwnam("nobody").pw_uid
 
1809
                gid = pwd.getpwnam("nobody").pw_gid
1728
1810
            except KeyError:
1729
1811
                uid = 65534
1730
1812
                gid = 65534
1735
1817
        if error[0] != errno.EPERM:
1736
1818
            raise error
1737
1819
    
1738
 
    # Enable all possible GnuTLS debugging
 
1820
    if not debug and not debuglevel:
 
1821
        syslogger.setLevel(logging.WARNING)
 
1822
        console.setLevel(logging.WARNING)
 
1823
    if debuglevel:
 
1824
        level = getattr(logging, debuglevel.upper())
 
1825
        syslogger.setLevel(level)
 
1826
        console.setLevel(level)
 
1827
 
1739
1828
    if debug:
 
1829
        # Enable all possible GnuTLS debugging
 
1830
        
1740
1831
        # "Use a log level over 10 to enable all debugging options."
1741
1832
        # - GnuTLS manual
1742
1833
        gnutls.library.functions.gnutls_global_set_log_level(11)
1743
1834
        
1744
1835
        @gnutls.library.types.gnutls_log_func
1745
1836
        def debug_gnutls(level, string):
1746
 
            logger.debug(u"GnuTLS: %s", string[:-1])
 
1837
            logger.debug("GnuTLS: %s", string[:-1])
1747
1838
        
1748
1839
        (gnutls.library.functions
1749
1840
         .gnutls_global_set_log_function(debug_gnutls))
 
1841
        
 
1842
        # Redirect stdin so all checkers get /dev/null
 
1843
        null = os.open(os.path.devnull, os.O_NOCTTY | os.O_RDWR)
 
1844
        os.dup2(null, sys.stdin.fileno())
 
1845
        if null > 2:
 
1846
            os.close(null)
 
1847
    else:
 
1848
        # No console logging
 
1849
        logger.removeHandler(console)
 
1850
    
 
1851
    # Need to fork before connecting to D-Bus
 
1852
    if not debug:
 
1853
        # Close all input and output, do double fork, etc.
 
1854
        daemon()
1750
1855
    
1751
1856
    global main_loop
1752
1857
    # From the Avahi example code
1756
1861
    # End of Avahi example code
1757
1862
    if use_dbus:
1758
1863
        try:
1759
 
            bus_name = dbus.service.BusName(u"se.bsnet.fukt.Mandos",
 
1864
            bus_name = dbus.service.BusName("se.bsnet.fukt.Mandos",
1760
1865
                                            bus, do_not_queue=True)
1761
1866
        except dbus.exceptions.NameExistsException, e:
1762
 
            logger.error(unicode(e) + u", disabling D-Bus")
 
1867
            logger.error(unicode(e) + ", disabling D-Bus")
1763
1868
            use_dbus = False
1764
 
            server_settings[u"use_dbus"] = False
 
1869
            server_settings["use_dbus"] = False
1765
1870
            tcp_server.use_dbus = False
1766
1871
    protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
1767
 
    service = AvahiService(name = server_settings[u"servicename"],
1768
 
                           servicetype = u"_mandos._tcp",
 
1872
    service = AvahiService(name = server_settings["servicename"],
 
1873
                           servicetype = "_mandos._tcp",
1769
1874
                           protocol = protocol, bus = bus)
1770
1875
    if server_settings["interface"]:
1771
1876
        service.interface = (if_nametoindex
1772
 
                             (str(server_settings[u"interface"])))
1773
 
 
 
1877
                             (str(server_settings["interface"])))
 
1878
    
1774
1879
    global multiprocessing_manager
1775
1880
    multiprocessing_manager = multiprocessing.Manager()
1776
1881
    
1795
1900
                        client_config, section)))
1796
1901
            for section in client_config.sections()))
1797
1902
    if not tcp_server.clients:
1798
 
        logger.warning(u"No clients defined")
1799
 
    
1800
 
    if debug:
1801
 
        # Redirect stdin so all checkers get /dev/null
1802
 
        null = os.open(os.path.devnull, os.O_NOCTTY | os.O_RDWR)
1803
 
        os.dup2(null, sys.stdin.fileno())
1804
 
        if null > 2:
1805
 
            os.close(null)
1806
 
    else:
1807
 
        # No console logging
1808
 
        logger.removeHandler(console)
1809
 
        # Close all input and output, do double fork, etc.
1810
 
        daemon()
1811
 
    
1812
 
    try:
1813
 
        with pidfile:
1814
 
            pid = os.getpid()
1815
 
            pidfile.write(str(pid) + "\n")
1816
 
        del pidfile
1817
 
    except IOError:
1818
 
        logger.error(u"Could not write to file %r with PID %d",
1819
 
                     pidfilename, pid)
1820
 
    except NameError:
1821
 
        # "pidfile" was never created
1822
 
        pass
1823
 
    del pidfilename
1824
 
    
 
1903
        logger.warning("No clients defined")
 
1904
        
1825
1905
    if not debug:
 
1906
        try:
 
1907
            with pidfile:
 
1908
                pid = os.getpid()
 
1909
                pidfile.write(str(pid) + "\n".encode("utf-8"))
 
1910
            del pidfile
 
1911
        except IOError:
 
1912
            logger.error("Could not write to file %r with PID %d",
 
1913
                         pidfilename, pid)
 
1914
        except NameError:
 
1915
            # "pidfile" was never created
 
1916
            pass
 
1917
        del pidfilename
 
1918
        
1826
1919
        signal.signal(signal.SIGINT, signal.SIG_IGN)
 
1920
 
1827
1921
    signal.signal(signal.SIGHUP, lambda signum, frame: sys.exit())
1828
1922
    signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit())
1829
1923
    
1831
1925
        class MandosDBusService(dbus.service.Object):
1832
1926
            """A D-Bus proxy object"""
1833
1927
            def __init__(self):
1834
 
                dbus.service.Object.__init__(self, bus, u"/")
1835
 
            _interface = u"se.bsnet.fukt.Mandos"
 
1928
                dbus.service.Object.__init__(self, bus, "/")
 
1929
            _interface = "se.bsnet.fukt.Mandos"
1836
1930
            
1837
 
            @dbus.service.signal(_interface, signature=u"o")
 
1931
            @dbus.service.signal(_interface, signature="o")
1838
1932
            def ClientAdded(self, objpath):
1839
1933
                "D-Bus signal"
1840
1934
                pass
1841
1935
            
1842
 
            @dbus.service.signal(_interface, signature=u"ss")
 
1936
            @dbus.service.signal(_interface, signature="ss")
1843
1937
            def ClientNotFound(self, fingerprint, address):
1844
1938
                "D-Bus signal"
1845
1939
                pass
1846
1940
            
1847
 
            @dbus.service.signal(_interface, signature=u"os")
 
1941
            @dbus.service.signal(_interface, signature="os")
1848
1942
            def ClientRemoved(self, objpath, name):
1849
1943
                "D-Bus signal"
1850
1944
                pass
1851
1945
            
1852
 
            @dbus.service.method(_interface, out_signature=u"ao")
 
1946
            @dbus.service.method(_interface, out_signature="ao")
1853
1947
            def GetAllClients(self):
1854
1948
                "D-Bus method"
1855
1949
                return dbus.Array(c.dbus_object_path
1856
1950
                                  for c in tcp_server.clients)
1857
1951
            
1858
1952
            @dbus.service.method(_interface,
1859
 
                                 out_signature=u"a{oa{sv}}")
 
1953
                                 out_signature="a{oa{sv}}")
1860
1954
            def GetAllClientsWithProperties(self):
1861
1955
                "D-Bus method"
1862
1956
                return dbus.Dictionary(
1863
 
                    ((c.dbus_object_path, c.GetAll(u""))
 
1957
                    ((c.dbus_object_path, c.GetAll(""))
1864
1958
                     for c in tcp_server.clients),
1865
 
                    signature=u"oa{sv}")
 
1959
                    signature="oa{sv}")
1866
1960
            
1867
 
            @dbus.service.method(_interface, in_signature=u"o")
 
1961
            @dbus.service.method(_interface, in_signature="o")
1868
1962
            def RemoveClient(self, object_path):
1869
1963
                "D-Bus method"
1870
1964
                for c in tcp_server.clients:
1912
2006
    # Find out what port we got
1913
2007
    service.port = tcp_server.socket.getsockname()[1]
1914
2008
    if use_ipv6:
1915
 
        logger.info(u"Now listening on address %r, port %d,"
 
2009
        logger.info("Now listening on address %r, port %d,"
1916
2010
                    " flowinfo %d, scope_id %d"
1917
2011
                    % tcp_server.socket.getsockname())
1918
2012
    else:                       # IPv4
1919
 
        logger.info(u"Now listening on address %r, port %d"
 
2013
        logger.info("Now listening on address %r, port %d"
1920
2014
                    % tcp_server.socket.getsockname())
1921
2015
    
1922
2016
    #service.interface = tcp_server.socket.getsockname()[3]
1926
2020
        try:
1927
2021
            service.activate()
1928
2022
        except dbus.exceptions.DBusException, error:
1929
 
            logger.critical(u"DBusException: %s", error)
 
2023
            logger.critical("DBusException: %s", error)
1930
2024
            cleanup()
1931
2025
            sys.exit(1)
1932
2026
        # End of Avahi example code
1936
2030
                             (tcp_server.handle_request
1937
2031
                              (*args[2:], **kwargs) or True))
1938
2032
        
1939
 
        logger.debug(u"Starting main loop")
 
2033
        logger.debug("Starting main loop")
1940
2034
        main_loop.run()
1941
2035
    except AvahiError, error:
1942
 
        logger.critical(u"AvahiError: %s", error)
 
2036
        logger.critical("AvahiError: %s", error)
1943
2037
        cleanup()
1944
2038
        sys.exit(1)
1945
2039
    except KeyboardInterrupt:
1946
2040
        if debug:
1947
 
            print >> sys.stderr
1948
 
        logger.debug(u"Server received KeyboardInterrupt")
1949
 
    logger.debug(u"Server exiting")
 
2041
            print("", file=sys.stderr)
 
2042
        logger.debug("Server received KeyboardInterrupt")
 
2043
    logger.debug("Server exiting")
1950
2044
    # Must run before the D-Bus bus name gets deregistered
1951
2045
    cleanup()
1952
2046