/mandos/trunk

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

« back to all changes in this revision

Viewing changes to mandos

  • Committer: Teddy Hogeborn
  • Date: 2015-03-10 18:03:38 UTC
  • Revision ID: teddy@recompile.se-20150310180338-pcxw6r2qmw9k6br9
Add ":!RSA" to GnuTLS priority string, to disallow non-DHE kx.

If Mandos was somehow made to use a non-ephemeral Diffie-Hellman key
exchange algorithm in the TLS handshake, any saved network traffic
could then be decrypted later if the Mandos client key was obtained.
By default, Mandos uses ephemeral DH key exchanges which does not have
this problem, but a non-ephemeral key exchange algorithm was still
enabled by default.  The simplest solution is to simply turn that off,
which ensures that Mandos will always use ephemeral DH key exchanges.

There is a "PFS" priority string specifier, but we can't use it because:

1. Security-wise, it is a mix between "NORMAL" and "SECURE128" - it
   enables a lot more algorithms than "SECURE256".

2. It is only available since GnuTLS 3.2.4.

Thanks to Andreas Fischer <af@bantuX.org> for reporting this issue.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
#!/usr/bin/python
 
1
#!/usr/bin/python2.7
2
2
# -*- mode: python; coding: utf-8 -*-
3
3
4
4
# Mandos server - give out binary blobs to connecting clients.
11
11
# "AvahiService" class, and some lines in "main".
12
12
13
13
# Everything else is
14
 
# Copyright © 2008-2016 Teddy Hogeborn
15
 
# Copyright © 2008-2016 Björn Påhlsson
 
14
# Copyright © 2008-2014 Teddy Hogeborn
 
15
# Copyright © 2008-2014 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
34
34
from __future__ import (division, absolute_import, print_function,
35
35
                        unicode_literals)
36
36
 
37
 
try:
38
 
    from future_builtins import *
39
 
except ImportError:
40
 
    pass
 
37
from future_builtins import *
41
38
 
42
 
try:
43
 
    import SocketServer as socketserver
44
 
except ImportError:
45
 
    import socketserver
 
39
import SocketServer as socketserver
46
40
import socket
47
41
import argparse
48
42
import datetime
49
43
import errno
50
 
try:
51
 
    import ConfigParser as configparser
52
 
except ImportError:
53
 
    import configparser
 
44
import gnutls.crypto
 
45
import gnutls.connection
 
46
import gnutls.errors
 
47
import gnutls.library.functions
 
48
import gnutls.library.constants
 
49
import gnutls.library.types
 
50
import ConfigParser as configparser
54
51
import sys
55
52
import re
56
53
import os
65
62
import struct
66
63
import fcntl
67
64
import functools
68
 
try:
69
 
    import cPickle as pickle
70
 
except ImportError:
71
 
    import pickle
 
65
import cPickle as pickle
72
66
import multiprocessing
73
67
import types
74
68
import binascii
75
69
import tempfile
76
70
import itertools
77
71
import collections
78
 
import codecs
79
72
 
80
73
import dbus
81
74
import dbus.service
82
 
from gi.repository import GLib
 
75
import gobject
 
76
import avahi
83
77
from dbus.mainloop.glib import DBusGMainLoop
84
78
import ctypes
85
79
import ctypes.util
97
91
if sys.version_info.major == 2:
98
92
    str = unicode
99
93
 
100
 
version = "1.7.7"
 
94
version = "1.6.9"
101
95
stored_state_file = "clients.pickle"
102
96
 
103
97
logger = logging.getLogger()
104
98
syslogger = None
105
99
 
106
100
try:
107
 
    if_nametoindex = ctypes.cdll.LoadLibrary(
108
 
        ctypes.util.find_library("c")).if_nametoindex
 
101
    if_nametoindex = (ctypes.cdll.LoadLibrary
 
102
                      (ctypes.util.find_library("c"))
 
103
                      .if_nametoindex)
109
104
except (OSError, AttributeError):
110
 
    
111
105
    def if_nametoindex(interface):
112
106
        "Get an interface index the hard way, i.e. using fcntl()"
113
107
        SIOCGIFINDEX = 0x8933  # From /usr/include/linux/sockios.h
118
112
        return interface_index
119
113
 
120
114
 
121
 
def copy_function(func):
122
 
    """Make a copy of a function"""
123
 
    if sys.version_info.major == 2:
124
 
        return types.FunctionType(func.func_code,
125
 
                                  func.func_globals,
126
 
                                  func.func_name,
127
 
                                  func.func_defaults,
128
 
                                  func.func_closure)
129
 
    else:
130
 
        return types.FunctionType(func.__code__,
131
 
                                  func.__globals__,
132
 
                                  func.__name__,
133
 
                                  func.__defaults__,
134
 
                                  func.__closure__)
135
 
 
136
 
 
137
115
def initlogger(debug, level=logging.WARNING):
138
116
    """init logger and add loglevel"""
139
117
    
140
118
    global syslogger
141
 
    syslogger = (logging.handlers.SysLogHandler(
142
 
        facility = logging.handlers.SysLogHandler.LOG_DAEMON,
143
 
        address = "/dev/log"))
 
119
    syslogger = (logging.handlers.SysLogHandler
 
120
                 (facility =
 
121
                  logging.handlers.SysLogHandler.LOG_DAEMON,
 
122
                  address = "/dev/log"))
144
123
    syslogger.setFormatter(logging.Formatter
145
124
                           ('Mandos [%(process)d]: %(levelname)s:'
146
125
                            ' %(message)s'))
163
142
 
164
143
class PGPEngine(object):
165
144
    """A simple class for OpenPGP symmetric encryption & decryption"""
166
 
    
167
145
    def __init__(self):
168
146
        self.tempdir = tempfile.mkdtemp(prefix="mandos-")
169
 
        self.gpg = "gpg"
170
 
        try:
171
 
            output = subprocess.check_output(["gpgconf"])
172
 
            for line in output.splitlines():
173
 
                name, text, path = line.split(b":")
174
 
                if name == "gpg":
175
 
                    self.gpg = path
176
 
                    break
177
 
        except OSError as e:
178
 
            if e.errno != errno.ENOENT:
179
 
                raise
180
147
        self.gnupgargs = ['--batch',
181
 
                          '--homedir', self.tempdir,
 
148
                          '--home', self.tempdir,
182
149
                          '--force-mdc',
183
 
                          '--quiet']
184
 
        # Only GPG version 1 has the --no-use-agent option.
185
 
        if self.gpg == "gpg" or self.gpg.endswith("/gpg"):
186
 
            self.gnupgargs.append("--no-use-agent")
 
150
                          '--quiet',
 
151
                          '--no-use-agent']
187
152
    
188
153
    def __enter__(self):
189
154
        return self
221
186
    
222
187
    def encrypt(self, data, password):
223
188
        passphrase = self.password_encode(password)
224
 
        with tempfile.NamedTemporaryFile(
225
 
                dir=self.tempdir) as passfile:
 
189
        with tempfile.NamedTemporaryFile(dir=self.tempdir
 
190
                                         ) as passfile:
226
191
            passfile.write(passphrase)
227
192
            passfile.flush()
228
 
            proc = subprocess.Popen([self.gpg, '--symmetric',
 
193
            proc = subprocess.Popen(['gpg', '--symmetric',
229
194
                                     '--passphrase-file',
230
195
                                     passfile.name]
231
196
                                    + self.gnupgargs,
239
204
    
240
205
    def decrypt(self, data, password):
241
206
        passphrase = self.password_encode(password)
242
 
        with tempfile.NamedTemporaryFile(
243
 
                dir = self.tempdir) as passfile:
 
207
        with tempfile.NamedTemporaryFile(dir = self.tempdir
 
208
                                         ) as passfile:
244
209
            passfile.write(passphrase)
245
210
            passfile.flush()
246
 
            proc = subprocess.Popen([self.gpg, '--decrypt',
 
211
            proc = subprocess.Popen(['gpg', '--decrypt',
247
212
                                     '--passphrase-file',
248
213
                                     passfile.name]
249
214
                                    + self.gnupgargs,
250
215
                                    stdin = subprocess.PIPE,
251
216
                                    stdout = subprocess.PIPE,
252
217
                                    stderr = subprocess.PIPE)
253
 
            decrypted_plaintext, err = proc.communicate(input = data)
 
218
            decrypted_plaintext, err = proc.communicate(input
 
219
                                                        = data)
254
220
        if proc.returncode != 0:
255
221
            raise PGPError(err)
256
222
        return decrypted_plaintext
257
223
 
258
 
# Pretend that we have an Avahi module
259
 
class Avahi(object):
260
 
    """This isn't so much a class as it is a module-like namespace.
261
 
    It is instantiated once, and simulates having an Avahi module."""
262
 
    IF_UNSPEC = -1              # avahi-common/address.h
263
 
    PROTO_UNSPEC = -1           # avahi-common/address.h
264
 
    PROTO_INET = 0              # avahi-common/address.h
265
 
    PROTO_INET6 = 1             # avahi-common/address.h
266
 
    DBUS_NAME = "org.freedesktop.Avahi"
267
 
    DBUS_INTERFACE_ENTRY_GROUP = DBUS_NAME + ".EntryGroup"
268
 
    DBUS_INTERFACE_SERVER = DBUS_NAME + ".Server"
269
 
    DBUS_PATH_SERVER = "/"
270
 
    def string_array_to_txt_array(self, t):
271
 
        return dbus.Array((dbus.ByteArray(s.encode("utf-8"))
272
 
                           for s in t), signature="ay")
273
 
    ENTRY_GROUP_ESTABLISHED = 2 # avahi-common/defs.h
274
 
    ENTRY_GROUP_COLLISION = 3   # avahi-common/defs.h
275
 
    ENTRY_GROUP_FAILURE = 4     # avahi-common/defs.h
276
 
    SERVER_INVALID = 0          # avahi-common/defs.h
277
 
    SERVER_REGISTERING = 1      # avahi-common/defs.h
278
 
    SERVER_RUNNING = 2          # avahi-common/defs.h
279
 
    SERVER_COLLISION = 3        # avahi-common/defs.h
280
 
    SERVER_FAILURE = 4          # avahi-common/defs.h
281
 
avahi = Avahi()
282
224
 
283
225
class AvahiError(Exception):
284
226
    def __init__(self, value, *args, **kwargs):
286
228
        return super(AvahiError, self).__init__(value, *args,
287
229
                                                **kwargs)
288
230
 
289
 
 
290
231
class AvahiServiceError(AvahiError):
291
232
    pass
292
233
 
293
 
 
294
234
class AvahiGroupError(AvahiError):
295
235
    pass
296
236
 
316
256
    bus: dbus.SystemBus()
317
257
    """
318
258
    
319
 
    def __init__(self,
320
 
                 interface = avahi.IF_UNSPEC,
321
 
                 name = None,
322
 
                 servicetype = None,
323
 
                 port = None,
324
 
                 TXT = None,
325
 
                 domain = "",
326
 
                 host = "",
327
 
                 max_renames = 32768,
328
 
                 protocol = avahi.PROTO_UNSPEC,
329
 
                 bus = None):
 
259
    def __init__(self, interface = avahi.IF_UNSPEC, name = None,
 
260
                 servicetype = None, port = None, TXT = None,
 
261
                 domain = "", host = "", max_renames = 32768,
 
262
                 protocol = avahi.PROTO_UNSPEC, bus = None):
330
263
        self.interface = interface
331
264
        self.name = name
332
265
        self.type = servicetype
349
282
                            " after %i retries, exiting.",
350
283
                            self.rename_count)
351
284
            raise AvahiServiceError("Too many renames")
352
 
        self.name = str(
353
 
            self.server.GetAlternativeServiceName(self.name))
 
285
        self.name = str(self.server
 
286
                        .GetAlternativeServiceName(self.name))
354
287
        self.rename_count += 1
355
288
        logger.info("Changing Zeroconf service name to %r ...",
356
289
                    self.name)
411
344
        elif state == avahi.ENTRY_GROUP_FAILURE:
412
345
            logger.critical("Avahi: Error in group state changed %s",
413
346
                            str(error))
414
 
            raise AvahiGroupError("State changed: {!s}".format(error))
 
347
            raise AvahiGroupError("State changed: {!s}"
 
348
                                  .format(error))
415
349
    
416
350
    def cleanup(self):
417
351
        """Derived from the Avahi example code"""
427
361
    def server_state_changed(self, state, error=None):
428
362
        """Derived from the Avahi example code"""
429
363
        logger.debug("Avahi server state change: %i", state)
430
 
        bad_states = {
431
 
            avahi.SERVER_INVALID: "Zeroconf server invalid",
432
 
            avahi.SERVER_REGISTERING: None,
433
 
            avahi.SERVER_COLLISION: "Zeroconf server name collision",
434
 
            avahi.SERVER_FAILURE: "Zeroconf server failure",
435
 
        }
 
364
        bad_states = { avahi.SERVER_INVALID:
 
365
                           "Zeroconf server invalid",
 
366
                       avahi.SERVER_REGISTERING: None,
 
367
                       avahi.SERVER_COLLISION:
 
368
                           "Zeroconf server name collision",
 
369
                       avahi.SERVER_FAILURE:
 
370
                           "Zeroconf server failure" }
436
371
        if state in bad_states:
437
372
            if bad_states[state] is not None:
438
373
                if error is None:
441
376
                    logger.error(bad_states[state] + ": %r", error)
442
377
            self.cleanup()
443
378
        elif state == avahi.SERVER_RUNNING:
444
 
            try:
445
 
                self.add()
446
 
            except dbus.exceptions.DBusException as error:
447
 
                if (error.get_dbus_name()
448
 
                    == "org.freedesktop.Avahi.CollisionError"):
449
 
                    logger.info("Local Zeroconf service name"
450
 
                                " collision.")
451
 
                    return self.rename(remove=False)
452
 
                else:
453
 
                    logger.critical("D-Bus Exception", exc_info=error)
454
 
                    self.cleanup()
455
 
                    os._exit(1)
 
379
            self.add()
456
380
        else:
457
381
            if error is None:
458
382
                logger.debug("Unknown state: %r", state)
468
392
                                    follow_name_owner_changes=True),
469
393
                avahi.DBUS_INTERFACE_SERVER)
470
394
        self.server.connect_to_signal("StateChanged",
471
 
                                      self.server_state_changed)
 
395
                                 self.server_state_changed)
472
396
        self.server_state_changed(self.server.GetState())
473
397
 
474
398
 
476
400
    def rename(self, *args, **kwargs):
477
401
        """Add the new name to the syslog messages"""
478
402
        ret = AvahiService.rename(self, *args, **kwargs)
479
 
        syslogger.setFormatter(logging.Formatter(
480
 
            'Mandos ({}) [%(process)d]: %(levelname)s: %(message)s'
481
 
            .format(self.name)))
 
403
        syslogger.setFormatter(logging.Formatter
 
404
                               ('Mandos ({}) [%(process)d]:'
 
405
                                ' %(levelname)s: %(message)s'
 
406
                                .format(self.name)))
482
407
        return ret
483
408
 
484
 
# Pretend that we have a GnuTLS module
485
 
class GnuTLS(object):
486
 
    """This isn't so much a class as it is a module-like namespace.
487
 
    It is instantiated once, and simulates having a GnuTLS module."""
488
 
    
489
 
    _library = ctypes.cdll.LoadLibrary(
490
 
        ctypes.util.find_library("gnutls"))
491
 
    _need_version = b"3.3.0"
492
 
    def __init__(self):
493
 
        # Need to use class name "GnuTLS" here, since this method is
494
 
        # called before the assignment to the "gnutls" global variable
495
 
        # happens.
496
 
        if GnuTLS.check_version(self._need_version) is None:
497
 
            raise GnuTLS.Error("Needs GnuTLS {} or later"
498
 
                               .format(self._need_version))
499
 
    
500
 
    # Unless otherwise indicated, the constants and types below are
501
 
    # all from the gnutls/gnutls.h C header file.
502
 
    
503
 
    # Constants
504
 
    E_SUCCESS = 0
505
 
    E_INTERRUPTED = -52
506
 
    E_AGAIN = -28
507
 
    CRT_OPENPGP = 2
508
 
    CLIENT = 2
509
 
    SHUT_RDWR = 0
510
 
    CRD_CERTIFICATE = 1
511
 
    E_NO_CERTIFICATE_FOUND = -49
512
 
    OPENPGP_FMT_RAW = 0         # gnutls/openpgp.h
513
 
    
514
 
    # Types
515
 
    class session_int(ctypes.Structure):
516
 
        _fields_ = []
517
 
    session_t = ctypes.POINTER(session_int)
518
 
    class certificate_credentials_st(ctypes.Structure):
519
 
        _fields_ = []
520
 
    certificate_credentials_t = ctypes.POINTER(
521
 
        certificate_credentials_st)
522
 
    certificate_type_t = ctypes.c_int
523
 
    class datum_t(ctypes.Structure):
524
 
        _fields_ = [('data', ctypes.POINTER(ctypes.c_ubyte)),
525
 
                    ('size', ctypes.c_uint)]
526
 
    class openpgp_crt_int(ctypes.Structure):
527
 
        _fields_ = []
528
 
    openpgp_crt_t = ctypes.POINTER(openpgp_crt_int)
529
 
    openpgp_crt_fmt_t = ctypes.c_int # gnutls/openpgp.h
530
 
    log_func = ctypes.CFUNCTYPE(None, ctypes.c_int, ctypes.c_char_p)
531
 
    credentials_type_t = ctypes.c_int
532
 
    transport_ptr_t = ctypes.c_void_p
533
 
    close_request_t = ctypes.c_int
534
 
    
535
 
    # Exceptions
536
 
    class Error(Exception):
537
 
        # We need to use the class name "GnuTLS" here, since this
538
 
        # exception might be raised from within GnuTLS.__init__,
539
 
        # which is called before the assignment to the "gnutls"
540
 
        # global variable has happened.
541
 
        def __init__(self, message = None, code = None, args=()):
542
 
            # Default usage is by a message string, but if a return
543
 
            # code is passed, convert it to a string with
544
 
            # gnutls.strerror()
545
 
            self.code = code
546
 
            if message is None and code is not None:
547
 
                message = GnuTLS.strerror(code)
548
 
            return super(GnuTLS.Error, self).__init__(
549
 
                message, *args)
550
 
    
551
 
    class CertificateSecurityError(Error):
552
 
        pass
553
 
    
554
 
    # Classes
555
 
    class Credentials(object):
556
 
        def __init__(self):
557
 
            self._c_object = gnutls.certificate_credentials_t()
558
 
            gnutls.certificate_allocate_credentials(
559
 
                ctypes.byref(self._c_object))
560
 
            self.type = gnutls.CRD_CERTIFICATE
561
 
        
562
 
        def __del__(self):
563
 
            gnutls.certificate_free_credentials(self._c_object)
564
 
    
565
 
    class ClientSession(object):
566
 
        def __init__(self, socket, credentials = None):
567
 
            self._c_object = gnutls.session_t()
568
 
            gnutls.init(ctypes.byref(self._c_object), gnutls.CLIENT)
569
 
            gnutls.set_default_priority(self._c_object)
570
 
            gnutls.transport_set_ptr(self._c_object, socket.fileno())
571
 
            gnutls.handshake_set_private_extensions(self._c_object,
572
 
                                                    True)
573
 
            self.socket = socket
574
 
            if credentials is None:
575
 
                credentials = gnutls.Credentials()
576
 
            gnutls.credentials_set(self._c_object, credentials.type,
577
 
                                   ctypes.cast(credentials._c_object,
578
 
                                               ctypes.c_void_p))
579
 
            self.credentials = credentials
580
 
        
581
 
        def __del__(self):
582
 
            gnutls.deinit(self._c_object)
583
 
        
584
 
        def handshake(self):
585
 
            return gnutls.handshake(self._c_object)
586
 
        
587
 
        def send(self, data):
588
 
            data = bytes(data)
589
 
            data_len = len(data)
590
 
            while data_len > 0:
591
 
                data_len -= gnutls.record_send(self._c_object,
592
 
                                               data[-data_len:],
593
 
                                               data_len)
594
 
        
595
 
        def bye(self):
596
 
            return gnutls.bye(self._c_object, gnutls.SHUT_RDWR)
597
 
    
598
 
    # Error handling functions
599
 
    def _error_code(result):
600
 
        """A function to raise exceptions on errors, suitable
601
 
        for the 'restype' attribute on ctypes functions"""
602
 
        if result >= 0:
603
 
            return result
604
 
        if result == gnutls.E_NO_CERTIFICATE_FOUND:
605
 
            raise gnutls.CertificateSecurityError(code = result)
606
 
        raise gnutls.Error(code = result)
607
 
    
608
 
    def _retry_on_error(result, func, arguments):
609
 
        """A function to retry on some errors, suitable
610
 
        for the 'errcheck' attribute on ctypes functions"""
611
 
        while result < 0:
612
 
            if result not in (gnutls.E_INTERRUPTED, gnutls.E_AGAIN):
613
 
                return _error_code(result)
614
 
            result = func(*arguments)
615
 
        return result
616
 
    
617
 
    # Unless otherwise indicated, the function declarations below are
618
 
    # all from the gnutls/gnutls.h C header file.
619
 
    
620
 
    # Functions
621
 
    priority_set_direct = _library.gnutls_priority_set_direct
622
 
    priority_set_direct.argtypes = [session_t, ctypes.c_char_p,
623
 
                                    ctypes.POINTER(ctypes.c_char_p)]
624
 
    priority_set_direct.restype = _error_code
625
 
    
626
 
    init = _library.gnutls_init
627
 
    init.argtypes = [ctypes.POINTER(session_t), ctypes.c_int]
628
 
    init.restype = _error_code
629
 
    
630
 
    set_default_priority = _library.gnutls_set_default_priority
631
 
    set_default_priority.argtypes = [session_t]
632
 
    set_default_priority.restype = _error_code
633
 
    
634
 
    record_send = _library.gnutls_record_send
635
 
    record_send.argtypes = [session_t, ctypes.c_void_p,
636
 
                            ctypes.c_size_t]
637
 
    record_send.restype = ctypes.c_ssize_t
638
 
    record_send.errcheck = _retry_on_error
639
 
    
640
 
    certificate_allocate_credentials = (
641
 
        _library.gnutls_certificate_allocate_credentials)
642
 
    certificate_allocate_credentials.argtypes = [
643
 
        ctypes.POINTER(certificate_credentials_t)]
644
 
    certificate_allocate_credentials.restype = _error_code
645
 
    
646
 
    certificate_free_credentials = (
647
 
        _library.gnutls_certificate_free_credentials)
648
 
    certificate_free_credentials.argtypes = [certificate_credentials_t]
649
 
    certificate_free_credentials.restype = None
650
 
    
651
 
    handshake_set_private_extensions = (
652
 
        _library.gnutls_handshake_set_private_extensions)
653
 
    handshake_set_private_extensions.argtypes = [session_t,
654
 
                                                 ctypes.c_int]
655
 
    handshake_set_private_extensions.restype = None
656
 
    
657
 
    credentials_set = _library.gnutls_credentials_set
658
 
    credentials_set.argtypes = [session_t, credentials_type_t,
659
 
                                ctypes.c_void_p]
660
 
    credentials_set.restype = _error_code
661
 
    
662
 
    strerror = _library.gnutls_strerror
663
 
    strerror.argtypes = [ctypes.c_int]
664
 
    strerror.restype = ctypes.c_char_p
665
 
    
666
 
    certificate_type_get = _library.gnutls_certificate_type_get
667
 
    certificate_type_get.argtypes = [session_t]
668
 
    certificate_type_get.restype = _error_code
669
 
    
670
 
    certificate_get_peers = _library.gnutls_certificate_get_peers
671
 
    certificate_get_peers.argtypes = [session_t,
672
 
                                      ctypes.POINTER(ctypes.c_uint)]
673
 
    certificate_get_peers.restype = ctypes.POINTER(datum_t)
674
 
    
675
 
    global_set_log_level = _library.gnutls_global_set_log_level
676
 
    global_set_log_level.argtypes = [ctypes.c_int]
677
 
    global_set_log_level.restype = None
678
 
    
679
 
    global_set_log_function = _library.gnutls_global_set_log_function
680
 
    global_set_log_function.argtypes = [log_func]
681
 
    global_set_log_function.restype = None
682
 
    
683
 
    deinit = _library.gnutls_deinit
684
 
    deinit.argtypes = [session_t]
685
 
    deinit.restype = None
686
 
    
687
 
    handshake = _library.gnutls_handshake
688
 
    handshake.argtypes = [session_t]
689
 
    handshake.restype = _error_code
690
 
    handshake.errcheck = _retry_on_error
691
 
    
692
 
    transport_set_ptr = _library.gnutls_transport_set_ptr
693
 
    transport_set_ptr.argtypes = [session_t, transport_ptr_t]
694
 
    transport_set_ptr.restype = None
695
 
    
696
 
    bye = _library.gnutls_bye
697
 
    bye.argtypes = [session_t, close_request_t]
698
 
    bye.restype = _error_code
699
 
    bye.errcheck = _retry_on_error
700
 
    
701
 
    check_version = _library.gnutls_check_version
702
 
    check_version.argtypes = [ctypes.c_char_p]
703
 
    check_version.restype = ctypes.c_char_p
704
 
    
705
 
    # All the function declarations below are from gnutls/openpgp.h
706
 
    
707
 
    openpgp_crt_init = _library.gnutls_openpgp_crt_init
708
 
    openpgp_crt_init.argtypes = [ctypes.POINTER(openpgp_crt_t)]
709
 
    openpgp_crt_init.restype = _error_code
710
 
    
711
 
    openpgp_crt_import = _library.gnutls_openpgp_crt_import
712
 
    openpgp_crt_import.argtypes = [openpgp_crt_t,
713
 
                                   ctypes.POINTER(datum_t),
714
 
                                   openpgp_crt_fmt_t]
715
 
    openpgp_crt_import.restype = _error_code
716
 
    
717
 
    openpgp_crt_verify_self = _library.gnutls_openpgp_crt_verify_self
718
 
    openpgp_crt_verify_self.argtypes = [openpgp_crt_t, ctypes.c_uint,
719
 
                                        ctypes.POINTER(ctypes.c_uint)]
720
 
    openpgp_crt_verify_self.restype = _error_code
721
 
    
722
 
    openpgp_crt_deinit = _library.gnutls_openpgp_crt_deinit
723
 
    openpgp_crt_deinit.argtypes = [openpgp_crt_t]
724
 
    openpgp_crt_deinit.restype = None
725
 
    
726
 
    openpgp_crt_get_fingerprint = (
727
 
        _library.gnutls_openpgp_crt_get_fingerprint)
728
 
    openpgp_crt_get_fingerprint.argtypes = [openpgp_crt_t,
729
 
                                            ctypes.c_void_p,
730
 
                                            ctypes.POINTER(
731
 
                                                ctypes.c_size_t)]
732
 
    openpgp_crt_get_fingerprint.restype = _error_code
733
 
    
734
 
    # Remove non-public functions
735
 
    del _error_code, _retry_on_error
736
 
# Create the global "gnutls" object, simulating a module
737
 
gnutls = GnuTLS()
738
 
 
739
 
def call_pipe(connection,       # : multiprocessing.Connection
740
 
              func, *args, **kwargs):
741
 
    """This function is meant to be called by multiprocessing.Process
742
 
    
743
 
    This function runs func(*args, **kwargs), and writes the resulting
744
 
    return value on the provided multiprocessing.Connection.
745
 
    """
746
 
    connection.send(func(*args, **kwargs))
747
 
    connection.close()
748
409
 
749
410
class Client(object):
750
411
    """A representation of a client host served by this server.
756
417
    checker:    subprocess.Popen(); a running checker process used
757
418
                                    to see if the client lives.
758
419
                                    'None' if no process is running.
759
 
    checker_callback_tag: a GLib event source tag, or None
 
420
    checker_callback_tag: a gobject event source tag, or None
760
421
    checker_command: string; External command which is run to check
761
422
                     if client lives.  %() expansions are done at
762
423
                     runtime with vars(self) as dict, so that for
763
424
                     instance %(name)s can be used in the command.
764
 
    checker_initiator_tag: a GLib event source tag, or None
 
425
    checker_initiator_tag: a gobject event source tag, or None
765
426
    created:    datetime.datetime(); (UTC) object creation
766
427
    client_structure: Object describing what attributes a client has
767
428
                      and is used for storing the client at exit
768
429
    current_checker_command: string; current running checker_command
769
 
    disable_initiator_tag: a GLib event source tag, or None
 
430
    disable_initiator_tag: a gobject event source tag, or None
770
431
    enabled:    bool()
771
432
    fingerprint: string (40 or 32 hexadecimal digits); used to
772
433
                 uniquely identify the client
777
438
    last_checker_status: integer between 0 and 255 reflecting exit
778
439
                         status of last checker. -1 reflects crashed
779
440
                         checker, -2 means no checker completed yet.
780
 
    last_checker_signal: The signal which killed the last checker, if
781
 
                         last_checker_status is -1
782
441
    last_enabled: datetime.datetime(); (UTC) or None
783
442
    name:       string; from the config file, used in log messages and
784
443
                        D-Bus identifiers
797
456
                          "fingerprint", "host", "interval",
798
457
                          "last_approval_request", "last_checked_ok",
799
458
                          "last_enabled", "name", "timeout")
800
 
    client_defaults = {
801
 
        "timeout": "PT5M",
802
 
        "extended_timeout": "PT15M",
803
 
        "interval": "PT2M",
804
 
        "checker": "fping -q -- %%(host)s",
805
 
        "host": "",
806
 
        "approval_delay": "PT0S",
807
 
        "approval_duration": "PT1S",
808
 
        "approved_by_default": "True",
809
 
        "enabled": "True",
810
 
    }
 
459
    client_defaults = { "timeout": "PT5M",
 
460
                        "extended_timeout": "PT15M",
 
461
                        "interval": "PT2M",
 
462
                        "checker": "fping -q -- %%(host)s",
 
463
                        "host": "",
 
464
                        "approval_delay": "PT0S",
 
465
                        "approval_duration": "PT1S",
 
466
                        "approved_by_default": "True",
 
467
                        "enabled": "True",
 
468
                        }
811
469
    
812
470
    @staticmethod
813
471
    def config_parser(config):
835
493
            client["fingerprint"] = (section["fingerprint"].upper()
836
494
                                     .replace(" ", ""))
837
495
            if "secret" in section:
838
 
                client["secret"] = codecs.decode(section["secret"]
839
 
                                                 .encode("utf-8"),
840
 
                                                 "base64")
 
496
                client["secret"] = section["secret"].decode("base64")
841
497
            elif "secfile" in section:
842
498
                with open(os.path.expanduser(os.path.expandvars
843
499
                                             (section["secfile"])),
893
549
        self.current_checker_command = None
894
550
        self.approved = None
895
551
        self.approvals_pending = 0
896
 
        self.changedstate = multiprocessing_manager.Condition(
897
 
            multiprocessing_manager.Lock())
898
 
        self.client_structure = [attr
899
 
                                 for attr in self.__dict__.keys()
 
552
        self.changedstate = (multiprocessing_manager
 
553
                             .Condition(multiprocessing_manager
 
554
                                        .Lock()))
 
555
        self.client_structure = [attr for attr in
 
556
                                 self.__dict__.iterkeys()
900
557
                                 if not attr.startswith("_")]
901
558
        self.client_structure.append("client_structure")
902
559
        
903
 
        for name, t in inspect.getmembers(
904
 
                type(self), lambda obj: isinstance(obj, property)):
 
560
        for name, t in inspect.getmembers(type(self),
 
561
                                          lambda obj:
 
562
                                              isinstance(obj,
 
563
                                                         property)):
905
564
            if not name.startswith("_"):
906
565
                self.client_structure.append(name)
907
566
    
928
587
        if not quiet:
929
588
            logger.info("Disabling client %s", self.name)
930
589
        if getattr(self, "disable_initiator_tag", None) is not None:
931
 
            GLib.source_remove(self.disable_initiator_tag)
 
590
            gobject.source_remove(self.disable_initiator_tag)
932
591
            self.disable_initiator_tag = None
933
592
        self.expires = None
934
593
        if getattr(self, "checker_initiator_tag", None) is not None:
935
 
            GLib.source_remove(self.checker_initiator_tag)
 
594
            gobject.source_remove(self.checker_initiator_tag)
936
595
            self.checker_initiator_tag = None
937
596
        self.stop_checker()
938
597
        self.enabled = False
939
598
        if not quiet:
940
599
            self.send_changedstate()
941
 
        # Do not run this again if called by a GLib.timeout_add
 
600
        # Do not run this again if called by a gobject.timeout_add
942
601
        return False
943
602
    
944
603
    def __del__(self):
948
607
        # Schedule a new checker to be started an 'interval' from now,
949
608
        # and every interval from then on.
950
609
        if self.checker_initiator_tag is not None:
951
 
            GLib.source_remove(self.checker_initiator_tag)
952
 
        self.checker_initiator_tag = GLib.timeout_add(
953
 
            int(self.interval.total_seconds() * 1000),
954
 
            self.start_checker)
 
610
            gobject.source_remove(self.checker_initiator_tag)
 
611
        self.checker_initiator_tag = (gobject.timeout_add
 
612
                                      (int(self.interval
 
613
                                           .total_seconds() * 1000),
 
614
                                       self.start_checker))
955
615
        # Schedule a disable() when 'timeout' has passed
956
616
        if self.disable_initiator_tag is not None:
957
 
            GLib.source_remove(self.disable_initiator_tag)
958
 
        self.disable_initiator_tag = GLib.timeout_add(
959
 
            int(self.timeout.total_seconds() * 1000), self.disable)
 
617
            gobject.source_remove(self.disable_initiator_tag)
 
618
        self.disable_initiator_tag = (gobject.timeout_add
 
619
                                      (int(self.timeout
 
620
                                           .total_seconds() * 1000),
 
621
                                       self.disable))
960
622
        # Also start a new checker *right now*.
961
623
        self.start_checker()
962
624
    
963
 
    def checker_callback(self, source, condition, connection,
964
 
                         command):
 
625
    def checker_callback(self, pid, condition, command):
965
626
        """The checker has completed, so take appropriate actions."""
966
627
        self.checker_callback_tag = None
967
628
        self.checker = None
968
 
        # Read return code from connection (see call_pipe)
969
 
        returncode = connection.recv()
970
 
        connection.close()
971
 
        
972
 
        if returncode >= 0:
973
 
            self.last_checker_status = returncode
974
 
            self.last_checker_signal = None
 
629
        if os.WIFEXITED(condition):
 
630
            self.last_checker_status = os.WEXITSTATUS(condition)
975
631
            if self.last_checker_status == 0:
976
632
                logger.info("Checker for %(name)s succeeded",
977
633
                            vars(self))
978
634
                self.checked_ok()
979
635
            else:
980
 
                logger.info("Checker for %(name)s failed", vars(self))
 
636
                logger.info("Checker for %(name)s failed",
 
637
                            vars(self))
981
638
        else:
982
639
            self.last_checker_status = -1
983
 
            self.last_checker_signal = -returncode
984
640
            logger.warning("Checker for %(name)s crashed?",
985
641
                           vars(self))
986
 
        return False
987
642
    
988
643
    def checked_ok(self):
989
644
        """Assert that the client has been seen, alive and well."""
990
645
        self.last_checked_ok = datetime.datetime.utcnow()
991
646
        self.last_checker_status = 0
992
 
        self.last_checker_signal = None
993
647
        self.bump_timeout()
994
648
    
995
649
    def bump_timeout(self, timeout=None):
997
651
        if timeout is None:
998
652
            timeout = self.timeout
999
653
        if self.disable_initiator_tag is not None:
1000
 
            GLib.source_remove(self.disable_initiator_tag)
 
654
            gobject.source_remove(self.disable_initiator_tag)
1001
655
            self.disable_initiator_tag = None
1002
656
        if getattr(self, "enabled", False):
1003
 
            self.disable_initiator_tag = GLib.timeout_add(
1004
 
                int(timeout.total_seconds() * 1000), self.disable)
 
657
            self.disable_initiator_tag = (gobject.timeout_add
 
658
                                          (int(timeout.total_seconds()
 
659
                                               * 1000), self.disable))
1005
660
            self.expires = datetime.datetime.utcnow() + timeout
1006
661
    
1007
662
    def need_approval(self):
1021
676
        # than 'timeout' for the client to be disabled, which is as it
1022
677
        # should be.
1023
678
        
1024
 
        if self.checker is not None and not self.checker.is_alive():
1025
 
            logger.warning("Checker was not alive; joining")
1026
 
            self.checker.join()
1027
 
            self.checker = None
 
679
        # If a checker exists, make sure it is not a zombie
 
680
        try:
 
681
            pid, status = os.waitpid(self.checker.pid, os.WNOHANG)
 
682
        except AttributeError:
 
683
            pass
 
684
        except OSError as error:
 
685
            if error.errno != errno.ECHILD:
 
686
                raise
 
687
        else:
 
688
            if pid:
 
689
                logger.warning("Checker was a zombie")
 
690
                gobject.source_remove(self.checker_callback_tag)
 
691
                self.checker_callback(pid, status,
 
692
                                      self.current_checker_command)
1028
693
        # Start a new checker if needed
1029
694
        if self.checker is None:
1030
695
            # Escape attributes for the shell
1031
 
            escaped_attrs = {
1032
 
                attr: re.escape(str(getattr(self, attr)))
1033
 
                for attr in self.runtime_expansions }
 
696
            escaped_attrs = { attr:
 
697
                                  re.escape(str(getattr(self, attr)))
 
698
                              for attr in self.runtime_expansions }
1034
699
            try:
1035
700
                command = self.checker_command % escaped_attrs
1036
701
            except TypeError as error:
1037
702
                logger.error('Could not format string "%s"',
1038
 
                             self.checker_command,
 
703
                             self.checker_command, exc_info=error)
 
704
                return True # Try again later
 
705
            self.current_checker_command = command
 
706
            try:
 
707
                logger.info("Starting checker %r for %s",
 
708
                            command, self.name)
 
709
                # We don't need to redirect stdout and stderr, since
 
710
                # in normal mode, that is already done by daemon(),
 
711
                # and in debug mode we don't want to.  (Stdin is
 
712
                # always replaced by /dev/null.)
 
713
                # The exception is when not debugging but nevertheless
 
714
                # running in the foreground; use the previously
 
715
                # created wnull.
 
716
                popen_args = {}
 
717
                if (not self.server_settings["debug"]
 
718
                    and self.server_settings["foreground"]):
 
719
                    popen_args.update({"stdout": wnull,
 
720
                                       "stderr": wnull })
 
721
                self.checker = subprocess.Popen(command,
 
722
                                                close_fds=True,
 
723
                                                shell=True, cwd="/",
 
724
                                                **popen_args)
 
725
            except OSError as error:
 
726
                logger.error("Failed to start subprocess",
1039
727
                             exc_info=error)
1040
 
                return True     # Try again later
1041
 
            self.current_checker_command = command
1042
 
            logger.info("Starting checker %r for %s", command,
1043
 
                        self.name)
1044
 
            # We don't need to redirect stdout and stderr, since
1045
 
            # in normal mode, that is already done by daemon(),
1046
 
            # and in debug mode we don't want to.  (Stdin is
1047
 
            # always replaced by /dev/null.)
1048
 
            # The exception is when not debugging but nevertheless
1049
 
            # running in the foreground; use the previously
1050
 
            # created wnull.
1051
 
            popen_args = { "close_fds": True,
1052
 
                           "shell": True,
1053
 
                           "cwd": "/" }
1054
 
            if (not self.server_settings["debug"]
1055
 
                and self.server_settings["foreground"]):
1056
 
                popen_args.update({"stdout": wnull,
1057
 
                                   "stderr": wnull })
1058
 
            pipe = multiprocessing.Pipe(duplex = False)
1059
 
            self.checker = multiprocessing.Process(
1060
 
                target = call_pipe,
1061
 
                args = (pipe[1], subprocess.call, command),
1062
 
                kwargs = popen_args)
1063
 
            self.checker.start()
1064
 
            self.checker_callback_tag = GLib.io_add_watch(
1065
 
                pipe[0].fileno(), GLib.IO_IN,
1066
 
                self.checker_callback, pipe[0], command)
1067
 
        # Re-run this periodically if run by GLib.timeout_add
 
728
                return True
 
729
            self.checker_callback_tag = (gobject.child_watch_add
 
730
                                         (self.checker.pid,
 
731
                                          self.checker_callback,
 
732
                                          data=command))
 
733
            # The checker may have completed before the gobject
 
734
            # watch was added.  Check for this.
 
735
            try:
 
736
                pid, status = os.waitpid(self.checker.pid, os.WNOHANG)
 
737
            except OSError as error:
 
738
                if error.errno == errno.ECHILD:
 
739
                    # This should never happen
 
740
                    logger.error("Child process vanished",
 
741
                                 exc_info=error)
 
742
                    return True
 
743
                raise
 
744
            if pid:
 
745
                gobject.source_remove(self.checker_callback_tag)
 
746
                self.checker_callback(pid, status, command)
 
747
        # Re-run this periodically if run by gobject.timeout_add
1068
748
        return True
1069
749
    
1070
750
    def stop_checker(self):
1071
751
        """Force the checker process, if any, to stop."""
1072
752
        if self.checker_callback_tag:
1073
 
            GLib.source_remove(self.checker_callback_tag)
 
753
            gobject.source_remove(self.checker_callback_tag)
1074
754
            self.checker_callback_tag = None
1075
755
        if getattr(self, "checker", None) is None:
1076
756
            return
1077
757
        logger.debug("Stopping checker for %(name)s", vars(self))
1078
 
        self.checker.terminate()
 
758
        try:
 
759
            self.checker.terminate()
 
760
            #time.sleep(0.5)
 
761
            #if self.checker.poll() is None:
 
762
            #    self.checker.kill()
 
763
        except OSError as error:
 
764
            if error.errno != errno.ESRCH: # No such process
 
765
                raise
1079
766
        self.checker = None
1080
767
 
1081
768
 
1082
 
def dbus_service_property(dbus_interface,
1083
 
                          signature="v",
1084
 
                          access="readwrite",
1085
 
                          byte_arrays=False):
 
769
def dbus_service_property(dbus_interface, signature="v",
 
770
                          access="readwrite", byte_arrays=False):
1086
771
    """Decorators for marking methods of a DBusObjectWithProperties to
1087
772
    become properties on the D-Bus.
1088
773
    
1098
783
    if byte_arrays and signature != "ay":
1099
784
        raise ValueError("Byte arrays not supported for non-'ay'"
1100
785
                         " signature {!r}".format(signature))
1101
 
    
1102
786
    def decorator(func):
1103
787
        func._dbus_is_property = True
1104
788
        func._dbus_interface = dbus_interface
1109
793
            func._dbus_name = func._dbus_name[:-14]
1110
794
        func._dbus_get_args_options = {'byte_arrays': byte_arrays }
1111
795
        return func
1112
 
    
1113
796
    return decorator
1114
797
 
1115
798
 
1124
807
                "org.freedesktop.DBus.Property.EmitsChangedSignal":
1125
808
                    "false"}
1126
809
    """
1127
 
    
1128
810
    def decorator(func):
1129
811
        func._dbus_is_interface = True
1130
812
        func._dbus_interface = dbus_interface
1131
813
        func._dbus_name = dbus_interface
1132
814
        return func
1133
 
    
1134
815
    return decorator
1135
816
 
1136
817
 
1145
826
                           access="r")
1146
827
    def Property_dbus_property(self):
1147
828
        return dbus.Boolean(False)
1148
 
    
1149
 
    See also the DBusObjectWithAnnotations class.
1150
829
    """
1151
 
    
1152
830
    def decorator(func):
1153
831
        func._dbus_annotations = annotations
1154
832
        return func
1155
 
    
1156
833
    return decorator
1157
834
 
1158
835
 
1161
838
    """
1162
839
    pass
1163
840
 
1164
 
 
1165
841
class DBusPropertyAccessException(DBusPropertyException):
1166
842
    """A property's access permissions disallows an operation.
1167
843
    """
1174
850
    pass
1175
851
 
1176
852
 
1177
 
class DBusObjectWithAnnotations(dbus.service.Object):
1178
 
    """A D-Bus object with annotations.
 
853
class DBusObjectWithProperties(dbus.service.Object):
 
854
    """A D-Bus object with properties.
1179
855
    
1180
 
    Classes inheriting from this can use the dbus_annotations
1181
 
    decorator to add annotations to methods or signals.
 
856
    Classes inheriting from this can use the dbus_service_property
 
857
    decorator to expose methods as D-Bus properties.  It exposes the
 
858
    standard Get(), Set(), and GetAll() methods on the D-Bus.
1182
859
    """
1183
860
    
1184
861
    @staticmethod
1194
871
    def _get_all_dbus_things(self, thing):
1195
872
        """Returns a generator of (name, attribute) pairs
1196
873
        """
1197
 
        return ((getattr(athing.__get__(self), "_dbus_name", name),
 
874
        return ((getattr(athing.__get__(self), "_dbus_name",
 
875
                         name),
1198
876
                 athing.__get__(self))
1199
877
                for cls in self.__class__.__mro__
1200
878
                for name, athing in
1201
 
                inspect.getmembers(cls, self._is_dbus_thing(thing)))
1202
 
    
1203
 
    @dbus.service.method(dbus.INTROSPECTABLE_IFACE,
1204
 
                         out_signature = "s",
1205
 
                         path_keyword = 'object_path',
1206
 
                         connection_keyword = 'connection')
1207
 
    def Introspect(self, object_path, connection):
1208
 
        """Overloading of standard D-Bus method.
1209
 
        
1210
 
        Inserts annotation tags on methods and signals.
1211
 
        """
1212
 
        xmlstring = dbus.service.Object.Introspect(self, object_path,
1213
 
                                                   connection)
1214
 
        try:
1215
 
            document = xml.dom.minidom.parseString(xmlstring)
1216
 
            
1217
 
            for if_tag in document.getElementsByTagName("interface"):
1218
 
                # Add annotation tags
1219
 
                for typ in ("method", "signal"):
1220
 
                    for tag in if_tag.getElementsByTagName(typ):
1221
 
                        annots = dict()
1222
 
                        for name, prop in (self.
1223
 
                                           _get_all_dbus_things(typ)):
1224
 
                            if (name == tag.getAttribute("name")
1225
 
                                and prop._dbus_interface
1226
 
                                == if_tag.getAttribute("name")):
1227
 
                                annots.update(getattr(
1228
 
                                    prop, "_dbus_annotations", {}))
1229
 
                        for name, value in annots.items():
1230
 
                            ann_tag = document.createElement(
1231
 
                                "annotation")
1232
 
                            ann_tag.setAttribute("name", name)
1233
 
                            ann_tag.setAttribute("value", value)
1234
 
                            tag.appendChild(ann_tag)
1235
 
                # Add interface annotation tags
1236
 
                for annotation, value in dict(
1237
 
                    itertools.chain.from_iterable(
1238
 
                        annotations().items()
1239
 
                        for name, annotations
1240
 
                        in self._get_all_dbus_things("interface")
1241
 
                        if name == if_tag.getAttribute("name")
1242
 
                        )).items():
1243
 
                    ann_tag = document.createElement("annotation")
1244
 
                    ann_tag.setAttribute("name", annotation)
1245
 
                    ann_tag.setAttribute("value", value)
1246
 
                    if_tag.appendChild(ann_tag)
1247
 
                # Fix argument name for the Introspect method itself
1248
 
                if (if_tag.getAttribute("name")
1249
 
                                == dbus.INTROSPECTABLE_IFACE):
1250
 
                    for cn in if_tag.getElementsByTagName("method"):
1251
 
                        if cn.getAttribute("name") == "Introspect":
1252
 
                            for arg in cn.getElementsByTagName("arg"):
1253
 
                                if (arg.getAttribute("direction")
1254
 
                                    == "out"):
1255
 
                                    arg.setAttribute("name",
1256
 
                                                     "xml_data")
1257
 
            xmlstring = document.toxml("utf-8")
1258
 
            document.unlink()
1259
 
        except (AttributeError, xml.dom.DOMException,
1260
 
                xml.parsers.expat.ExpatError) as error:
1261
 
            logger.error("Failed to override Introspection method",
1262
 
                         exc_info=error)
1263
 
        return xmlstring
1264
 
 
1265
 
 
1266
 
class DBusObjectWithProperties(DBusObjectWithAnnotations):
1267
 
    """A D-Bus object with properties.
1268
 
    
1269
 
    Classes inheriting from this can use the dbus_service_property
1270
 
    decorator to expose methods as D-Bus properties.  It exposes the
1271
 
    standard Get(), Set(), and GetAll() methods on the D-Bus.
1272
 
    """
 
879
                inspect.getmembers(cls,
 
880
                                   self._is_dbus_thing(thing)))
1273
881
    
1274
882
    def _get_dbus_property(self, interface_name, property_name):
1275
883
        """Returns a bound method if one exists which is a D-Bus
1276
884
        property with the specified name and interface.
1277
885
        """
1278
 
        for cls in self.__class__.__mro__:
1279
 
            for name, value in inspect.getmembers(
1280
 
                    cls, self._is_dbus_thing("property")):
 
886
        for cls in  self.__class__.__mro__:
 
887
            for name, value in (inspect.getmembers
 
888
                                (cls,
 
889
                                 self._is_dbus_thing("property"))):
1281
890
                if (value._dbus_name == property_name
1282
891
                    and value._dbus_interface == interface_name):
1283
892
                    return value.__get__(self)
1284
893
        
1285
894
        # No such property
1286
 
        raise DBusPropertyNotFound("{}:{}.{}".format(
1287
 
            self.dbus_object_path, interface_name, property_name))
1288
 
    
1289
 
    @classmethod
1290
 
    def _get_all_interface_names(cls):
1291
 
        """Get a sequence of all interfaces supported by an object"""
1292
 
        return (name for name in set(getattr(getattr(x, attr),
1293
 
                                             "_dbus_interface", None)
1294
 
                                     for x in (inspect.getmro(cls))
1295
 
                                     for attr in dir(x))
1296
 
                if name is not None)
1297
 
    
1298
 
    @dbus.service.method(dbus.PROPERTIES_IFACE,
1299
 
                         in_signature="ss",
 
895
        raise DBusPropertyNotFound(self.dbus_object_path + ":"
 
896
                                   + interface_name + "."
 
897
                                   + property_name)
 
898
    
 
899
    @dbus.service.method(dbus.PROPERTIES_IFACE, in_signature="ss",
1300
900
                         out_signature="v")
1301
901
    def Get(self, interface_name, property_name):
1302
902
        """Standard D-Bus property Get() method, see D-Bus standard.
1327
927
                                            for byte in value))
1328
928
        prop(value)
1329
929
    
1330
 
    @dbus.service.method(dbus.PROPERTIES_IFACE,
1331
 
                         in_signature="s",
 
930
    @dbus.service.method(dbus.PROPERTIES_IFACE, in_signature="s",
1332
931
                         out_signature="a{sv}")
1333
932
    def GetAll(self, interface_name):
1334
933
        """Standard D-Bus property GetAll() method, see D-Bus
1349
948
            if not hasattr(value, "variant_level"):
1350
949
                properties[name] = value
1351
950
                continue
1352
 
            properties[name] = type(value)(
1353
 
                value, variant_level = value.variant_level + 1)
 
951
            properties[name] = type(value)(value, variant_level=
 
952
                                           value.variant_level+1)
1354
953
        return dbus.Dictionary(properties, signature="sv")
1355
954
    
1356
955
    @dbus.service.signal(dbus.PROPERTIES_IFACE, signature="sa{sv}as")
1370
969
        
1371
970
        Inserts property tags and interface annotation tags.
1372
971
        """
1373
 
        xmlstring = DBusObjectWithAnnotations.Introspect(self,
1374
 
                                                         object_path,
1375
 
                                                         connection)
 
972
        xmlstring = dbus.service.Object.Introspect(self, object_path,
 
973
                                                   connection)
1376
974
        try:
1377
975
            document = xml.dom.minidom.parseString(xmlstring)
1378
 
            
1379
976
            def make_tag(document, name, prop):
1380
977
                e = document.createElement("property")
1381
978
                e.setAttribute("name", name)
1382
979
                e.setAttribute("type", prop._dbus_signature)
1383
980
                e.setAttribute("access", prop._dbus_access)
1384
981
                return e
1385
 
            
1386
982
            for if_tag in document.getElementsByTagName("interface"):
1387
983
                # Add property tags
1388
984
                for tag in (make_tag(document, name, prop)
1391
987
                            if prop._dbus_interface
1392
988
                            == if_tag.getAttribute("name")):
1393
989
                    if_tag.appendChild(tag)
1394
 
                # Add annotation tags for properties
1395
 
                for tag in if_tag.getElementsByTagName("property"):
1396
 
                    annots = dict()
1397
 
                    for name, prop in self._get_all_dbus_things(
1398
 
                            "property"):
1399
 
                        if (name == tag.getAttribute("name")
1400
 
                            and prop._dbus_interface
1401
 
                            == if_tag.getAttribute("name")):
1402
 
                            annots.update(getattr(
1403
 
                                prop, "_dbus_annotations", {}))
1404
 
                    for name, value in annots.items():
1405
 
                        ann_tag = document.createElement(
1406
 
                            "annotation")
1407
 
                        ann_tag.setAttribute("name", name)
1408
 
                        ann_tag.setAttribute("value", value)
1409
 
                        tag.appendChild(ann_tag)
 
990
                # Add annotation tags
 
991
                for typ in ("method", "signal", "property"):
 
992
                    for tag in if_tag.getElementsByTagName(typ):
 
993
                        annots = dict()
 
994
                        for name, prop in (self.
 
995
                                           _get_all_dbus_things(typ)):
 
996
                            if (name == tag.getAttribute("name")
 
997
                                and prop._dbus_interface
 
998
                                == if_tag.getAttribute("name")):
 
999
                                annots.update(getattr
 
1000
                                              (prop,
 
1001
                                               "_dbus_annotations",
 
1002
                                               {}))
 
1003
                        for name, value in annots.items():
 
1004
                            ann_tag = document.createElement(
 
1005
                                "annotation")
 
1006
                            ann_tag.setAttribute("name", name)
 
1007
                            ann_tag.setAttribute("value", value)
 
1008
                            tag.appendChild(ann_tag)
 
1009
                # Add interface annotation tags
 
1010
                for annotation, value in dict(
 
1011
                    itertools.chain.from_iterable(
 
1012
                        annotations().items()
 
1013
                        for name, annotations in
 
1014
                        self._get_all_dbus_things("interface")
 
1015
                        if name == if_tag.getAttribute("name")
 
1016
                        )).items():
 
1017
                    ann_tag = document.createElement("annotation")
 
1018
                    ann_tag.setAttribute("name", annotation)
 
1019
                    ann_tag.setAttribute("value", value)
 
1020
                    if_tag.appendChild(ann_tag)
1410
1021
                # Add the names to the return values for the
1411
1022
                # "org.freedesktop.DBus.Properties" methods
1412
1023
                if (if_tag.getAttribute("name")
1430
1041
                         exc_info=error)
1431
1042
        return xmlstring
1432
1043
 
1433
 
try:
1434
 
    dbus.OBJECT_MANAGER_IFACE
1435
 
except AttributeError:
1436
 
    dbus.OBJECT_MANAGER_IFACE = "org.freedesktop.DBus.ObjectManager"
1437
 
 
1438
 
class DBusObjectWithObjectManager(DBusObjectWithAnnotations):
1439
 
    """A D-Bus object with an ObjectManager.
1440
 
    
1441
 
    Classes inheriting from this exposes the standard
1442
 
    GetManagedObjects call and the InterfacesAdded and
1443
 
    InterfacesRemoved signals on the standard
1444
 
    "org.freedesktop.DBus.ObjectManager" interface.
1445
 
    
1446
 
    Note: No signals are sent automatically; they must be sent
1447
 
    manually.
1448
 
    """
1449
 
    @dbus.service.method(dbus.OBJECT_MANAGER_IFACE,
1450
 
                         out_signature = "a{oa{sa{sv}}}")
1451
 
    def GetManagedObjects(self):
1452
 
        """This function must be overridden"""
1453
 
        raise NotImplementedError()
1454
 
    
1455
 
    @dbus.service.signal(dbus.OBJECT_MANAGER_IFACE,
1456
 
                         signature = "oa{sa{sv}}")
1457
 
    def InterfacesAdded(self, object_path, interfaces_and_properties):
1458
 
        pass
1459
 
    
1460
 
    @dbus.service.signal(dbus.OBJECT_MANAGER_IFACE, signature = "oas")
1461
 
    def InterfacesRemoved(self, object_path, interfaces):
1462
 
        pass
1463
 
    
1464
 
    @dbus.service.method(dbus.INTROSPECTABLE_IFACE,
1465
 
                         out_signature = "s",
1466
 
                         path_keyword = 'object_path',
1467
 
                         connection_keyword = 'connection')
1468
 
    def Introspect(self, object_path, connection):
1469
 
        """Overloading of standard D-Bus method.
1470
 
        
1471
 
        Override return argument name of GetManagedObjects to be
1472
 
        "objpath_interfaces_and_properties"
1473
 
        """
1474
 
        xmlstring = DBusObjectWithAnnotations.Introspect(self,
1475
 
                                                         object_path,
1476
 
                                                         connection)
1477
 
        try:
1478
 
            document = xml.dom.minidom.parseString(xmlstring)
1479
 
            
1480
 
            for if_tag in document.getElementsByTagName("interface"):
1481
 
                # Fix argument name for the GetManagedObjects method
1482
 
                if (if_tag.getAttribute("name")
1483
 
                                == dbus.OBJECT_MANAGER_IFACE):
1484
 
                    for cn in if_tag.getElementsByTagName("method"):
1485
 
                        if (cn.getAttribute("name")
1486
 
                            == "GetManagedObjects"):
1487
 
                            for arg in cn.getElementsByTagName("arg"):
1488
 
                                if (arg.getAttribute("direction")
1489
 
                                    == "out"):
1490
 
                                    arg.setAttribute(
1491
 
                                        "name",
1492
 
                                        "objpath_interfaces"
1493
 
                                        "_and_properties")
1494
 
            xmlstring = document.toxml("utf-8")
1495
 
            document.unlink()
1496
 
        except (AttributeError, xml.dom.DOMException,
1497
 
                xml.parsers.expat.ExpatError) as error:
1498
 
            logger.error("Failed to override Introspection method",
1499
 
                         exc_info = error)
1500
 
        return xmlstring
1501
1044
 
1502
1045
def datetime_to_dbus(dt, variant_level=0):
1503
1046
    """Convert a UTC datetime.datetime() to a D-Bus type."""
1504
1047
    if dt is None:
1505
1048
        return dbus.String("", variant_level = variant_level)
1506
 
    return dbus.String(dt.isoformat(), variant_level=variant_level)
 
1049
    return dbus.String(dt.isoformat(),
 
1050
                       variant_level=variant_level)
1507
1051
 
1508
1052
 
1509
1053
def alternate_dbus_interfaces(alt_interface_names, deprecate=True):
1529
1073
    (from DBusObjectWithProperties) and interfaces (from the
1530
1074
    dbus_interface_annotations decorator).
1531
1075
    """
1532
 
    
1533
1076
    def wrapper(cls):
1534
1077
        for orig_interface_name, alt_interface_name in (
1535
 
                alt_interface_names.items()):
 
1078
            alt_interface_names.items()):
1536
1079
            attr = {}
1537
1080
            interface_names = set()
1538
1081
            # Go though all attributes of the class
1540
1083
                # Ignore non-D-Bus attributes, and D-Bus attributes
1541
1084
                # with the wrong interface name
1542
1085
                if (not hasattr(attribute, "_dbus_interface")
1543
 
                    or not attribute._dbus_interface.startswith(
1544
 
                        orig_interface_name)):
 
1086
                    or not attribute._dbus_interface
 
1087
                    .startswith(orig_interface_name)):
1545
1088
                    continue
1546
1089
                # Create an alternate D-Bus interface name based on
1547
1090
                # the current name
1548
 
                alt_interface = attribute._dbus_interface.replace(
1549
 
                    orig_interface_name, alt_interface_name)
 
1091
                alt_interface = (attribute._dbus_interface
 
1092
                                 .replace(orig_interface_name,
 
1093
                                          alt_interface_name))
1550
1094
                interface_names.add(alt_interface)
1551
1095
                # Is this a D-Bus signal?
1552
1096
                if getattr(attribute, "_dbus_is_signal", False):
1553
1097
                    # Extract the original non-method undecorated
1554
1098
                    # function by black magic
1555
 
                    if sys.version_info.major == 2:
1556
 
                        nonmethod_func = (dict(
 
1099
                    nonmethod_func = (dict(
1557
1100
                            zip(attribute.func_code.co_freevars,
1558
 
                                attribute.__closure__))
1559
 
                                          ["func"].cell_contents)
1560
 
                    else:
1561
 
                        nonmethod_func = (dict(
1562
 
                            zip(attribute.__code__.co_freevars,
1563
 
                                attribute.__closure__))
1564
 
                                          ["func"].cell_contents)
 
1101
                                attribute.__closure__))["func"]
 
1102
                                      .cell_contents)
1565
1103
                    # Create a new, but exactly alike, function
1566
1104
                    # object, and decorate it to be a new D-Bus signal
1567
1105
                    # with the alternate D-Bus interface name
1568
 
                    new_function = copy_function(nonmethod_func)
1569
 
                    new_function = (dbus.service.signal(
1570
 
                        alt_interface,
1571
 
                        attribute._dbus_signature)(new_function))
 
1106
                    new_function = (dbus.service.signal
 
1107
                                    (alt_interface,
 
1108
                                     attribute._dbus_signature)
 
1109
                                    (types.FunctionType(
 
1110
                                nonmethod_func.func_code,
 
1111
                                nonmethod_func.func_globals,
 
1112
                                nonmethod_func.func_name,
 
1113
                                nonmethod_func.func_defaults,
 
1114
                                nonmethod_func.func_closure)))
1572
1115
                    # Copy annotations, if any
1573
1116
                    try:
1574
 
                        new_function._dbus_annotations = dict(
1575
 
                            attribute._dbus_annotations)
 
1117
                        new_function._dbus_annotations = (
 
1118
                            dict(attribute._dbus_annotations))
1576
1119
                    except AttributeError:
1577
1120
                        pass
1578
1121
                    # Define a creator of a function to call both the
1583
1126
                        """This function is a scope container to pass
1584
1127
                        func1 and func2 to the "call_both" function
1585
1128
                        outside of its arguments"""
1586
 
                        
1587
 
                        @functools.wraps(func2)
1588
1129
                        def call_both(*args, **kwargs):
1589
1130
                            """This function will emit two D-Bus
1590
1131
                            signals by calling func1 and func2"""
1591
1132
                            func1(*args, **kwargs)
1592
1133
                            func2(*args, **kwargs)
1593
 
                        # Make wrapper function look like a D-Bus signal
1594
 
                        for name, attr in inspect.getmembers(func2):
1595
 
                            if name.startswith("_dbus_"):
1596
 
                                setattr(call_both, name, attr)
1597
 
                        
1598
1134
                        return call_both
1599
1135
                    # Create the "call_both" function and add it to
1600
1136
                    # the class
1605
1141
                    # object.  Decorate it to be a new D-Bus method
1606
1142
                    # with the alternate D-Bus interface name.  Add it
1607
1143
                    # to the class.
1608
 
                    attr[attrname] = (
1609
 
                        dbus.service.method(
1610
 
                            alt_interface,
1611
 
                            attribute._dbus_in_signature,
1612
 
                            attribute._dbus_out_signature)
1613
 
                        (copy_function(attribute)))
 
1144
                    attr[attrname] = (dbus.service.method
 
1145
                                      (alt_interface,
 
1146
                                       attribute._dbus_in_signature,
 
1147
                                       attribute._dbus_out_signature)
 
1148
                                      (types.FunctionType
 
1149
                                       (attribute.func_code,
 
1150
                                        attribute.func_globals,
 
1151
                                        attribute.func_name,
 
1152
                                        attribute.func_defaults,
 
1153
                                        attribute.func_closure)))
1614
1154
                    # Copy annotations, if any
1615
1155
                    try:
1616
 
                        attr[attrname]._dbus_annotations = dict(
1617
 
                            attribute._dbus_annotations)
 
1156
                        attr[attrname]._dbus_annotations = (
 
1157
                            dict(attribute._dbus_annotations))
1618
1158
                    except AttributeError:
1619
1159
                        pass
1620
1160
                # Is this a D-Bus property?
1623
1163
                    # object, and decorate it to be a new D-Bus
1624
1164
                    # property with the alternate D-Bus interface
1625
1165
                    # name.  Add it to the class.
1626
 
                    attr[attrname] = (dbus_service_property(
1627
 
                        alt_interface, attribute._dbus_signature,
1628
 
                        attribute._dbus_access,
1629
 
                        attribute._dbus_get_args_options
1630
 
                        ["byte_arrays"])
1631
 
                                      (copy_function(attribute)))
 
1166
                    attr[attrname] = (dbus_service_property
 
1167
                                      (alt_interface,
 
1168
                                       attribute._dbus_signature,
 
1169
                                       attribute._dbus_access,
 
1170
                                       attribute
 
1171
                                       ._dbus_get_args_options
 
1172
                                       ["byte_arrays"])
 
1173
                                      (types.FunctionType
 
1174
                                       (attribute.func_code,
 
1175
                                        attribute.func_globals,
 
1176
                                        attribute.func_name,
 
1177
                                        attribute.func_defaults,
 
1178
                                        attribute.func_closure)))
1632
1179
                    # Copy annotations, if any
1633
1180
                    try:
1634
 
                        attr[attrname]._dbus_annotations = dict(
1635
 
                            attribute._dbus_annotations)
 
1181
                        attr[attrname]._dbus_annotations = (
 
1182
                            dict(attribute._dbus_annotations))
1636
1183
                    except AttributeError:
1637
1184
                        pass
1638
1185
                # Is this a D-Bus interface?
1641
1188
                    # object.  Decorate it to be a new D-Bus interface
1642
1189
                    # with the alternate D-Bus interface name.  Add it
1643
1190
                    # to the class.
1644
 
                    attr[attrname] = (
1645
 
                        dbus_interface_annotations(alt_interface)
1646
 
                        (copy_function(attribute)))
 
1191
                    attr[attrname] = (dbus_interface_annotations
 
1192
                                      (alt_interface)
 
1193
                                      (types.FunctionType
 
1194
                                       (attribute.func_code,
 
1195
                                        attribute.func_globals,
 
1196
                                        attribute.func_name,
 
1197
                                        attribute.func_defaults,
 
1198
                                        attribute.func_closure)))
1647
1199
            if deprecate:
1648
1200
                # Deprecate all alternate interfaces
1649
1201
                iname="_AlternateDBusNames_interface_annotation{}"
1650
1202
                for interface_name in interface_names:
1651
 
                    
1652
1203
                    @dbus_interface_annotations(interface_name)
1653
1204
                    def func(self):
1654
1205
                        return { "org.freedesktop.DBus.Deprecated":
1655
 
                                 "true" }
 
1206
                                     "true" }
1656
1207
                    # Find an unused name
1657
1208
                    for aname in (iname.format(i)
1658
1209
                                  for i in itertools.count()):
1662
1213
            if interface_names:
1663
1214
                # Replace the class with a new subclass of it with
1664
1215
                # methods, signals, etc. as created above.
1665
 
                if sys.version_info.major == 2:
1666
 
                    cls = type(b"{}Alternate".format(cls.__name__),
1667
 
                               (cls, ), attr)
1668
 
                else:
1669
 
                    cls = type("{}Alternate".format(cls.__name__),
1670
 
                               (cls, ), attr)
 
1216
                cls = type(b"{}Alternate".format(cls.__name__),
 
1217
                           (cls,), attr)
1671
1218
        return cls
1672
 
    
1673
1219
    return wrapper
1674
1220
 
1675
1221
 
1676
1222
@alternate_dbus_interfaces({"se.recompile.Mandos":
1677
 
                            "se.bsnet.fukt.Mandos"})
 
1223
                                "se.bsnet.fukt.Mandos"})
1678
1224
class ClientDBus(Client, DBusObjectWithProperties):
1679
1225
    """A Client class using D-Bus
1680
1226
    
1684
1230
    """
1685
1231
    
1686
1232
    runtime_expansions = (Client.runtime_expansions
1687
 
                          + ("dbus_object_path", ))
 
1233
                          + ("dbus_object_path",))
1688
1234
    
1689
1235
    _interface = "se.recompile.Mandos.Client"
1690
1236
    
1698
1244
        client_object_name = str(self.name).translate(
1699
1245
            {ord("."): ord("_"),
1700
1246
             ord("-"): ord("_")})
1701
 
        self.dbus_object_path = dbus.ObjectPath(
1702
 
            "/clients/" + client_object_name)
 
1247
        self.dbus_object_path = (dbus.ObjectPath
 
1248
                                 ("/clients/" + client_object_name))
1703
1249
        DBusObjectWithProperties.__init__(self, self.bus,
1704
1250
                                          self.dbus_object_path)
1705
1251
    
1706
 
    def notifychangeproperty(transform_func, dbus_name,
1707
 
                             type_func=lambda x: x,
1708
 
                             variant_level=1,
1709
 
                             invalidate_only=False,
 
1252
    def notifychangeproperty(transform_func,
 
1253
                             dbus_name, type_func=lambda x: x,
 
1254
                             variant_level=1, invalidate_only=False,
1710
1255
                             _interface=_interface):
1711
1256
        """ Modify a variable so that it's a property which announces
1712
1257
        its changes to DBus.
1719
1264
        variant_level: D-Bus variant level.  Default: 1
1720
1265
        """
1721
1266
        attrname = "_{}".format(dbus_name)
1722
 
        
1723
1267
        def setter(self, value):
1724
1268
            if hasattr(self, "dbus_object_path"):
1725
1269
                if (not hasattr(self, attrname) or
1726
1270
                    type_func(getattr(self, attrname, None))
1727
1271
                    != type_func(value)):
1728
1272
                    if invalidate_only:
1729
 
                        self.PropertiesChanged(
1730
 
                            _interface, dbus.Dictionary(),
1731
 
                            dbus.Array((dbus_name, )))
 
1273
                        self.PropertiesChanged(_interface,
 
1274
                                               dbus.Dictionary(),
 
1275
                                               dbus.Array
 
1276
                                               ((dbus_name,)))
1732
1277
                    else:
1733
 
                        dbus_value = transform_func(
1734
 
                            type_func(value),
1735
 
                            variant_level = variant_level)
 
1278
                        dbus_value = transform_func(type_func(value),
 
1279
                                                    variant_level
 
1280
                                                    =variant_level)
1736
1281
                        self.PropertyChanged(dbus.String(dbus_name),
1737
1282
                                             dbus_value)
1738
 
                        self.PropertiesChanged(
1739
 
                            _interface,
1740
 
                            dbus.Dictionary({ dbus.String(dbus_name):
1741
 
                                              dbus_value }),
1742
 
                            dbus.Array())
 
1283
                        self.PropertiesChanged(_interface,
 
1284
                                               dbus.Dictionary({
 
1285
                                    dbus.String(dbus_name):
 
1286
                                        dbus_value }), dbus.Array())
1743
1287
            setattr(self, attrname, value)
1744
1288
        
1745
1289
        return property(lambda self: getattr(self, attrname), setter)
1751
1295
    enabled = notifychangeproperty(dbus.Boolean, "Enabled")
1752
1296
    last_enabled = notifychangeproperty(datetime_to_dbus,
1753
1297
                                        "LastEnabled")
1754
 
    checker = notifychangeproperty(
1755
 
        dbus.Boolean, "CheckerRunning",
1756
 
        type_func = lambda checker: checker is not None)
 
1298
    checker = notifychangeproperty(dbus.Boolean, "CheckerRunning",
 
1299
                                   type_func = lambda checker:
 
1300
                                       checker is not None)
1757
1301
    last_checked_ok = notifychangeproperty(datetime_to_dbus,
1758
1302
                                           "LastCheckedOK")
1759
1303
    last_checker_status = notifychangeproperty(dbus.Int16,
1762
1306
        datetime_to_dbus, "LastApprovalRequest")
1763
1307
    approved_by_default = notifychangeproperty(dbus.Boolean,
1764
1308
                                               "ApprovedByDefault")
1765
 
    approval_delay = notifychangeproperty(
1766
 
        dbus.UInt64, "ApprovalDelay",
1767
 
        type_func = lambda td: td.total_seconds() * 1000)
 
1309
    approval_delay = notifychangeproperty(dbus.UInt64,
 
1310
                                          "ApprovalDelay",
 
1311
                                          type_func =
 
1312
                                          lambda td: td.total_seconds()
 
1313
                                          * 1000)
1768
1314
    approval_duration = notifychangeproperty(
1769
1315
        dbus.UInt64, "ApprovalDuration",
1770
1316
        type_func = lambda td: td.total_seconds() * 1000)
1771
1317
    host = notifychangeproperty(dbus.String, "Host")
1772
 
    timeout = notifychangeproperty(
1773
 
        dbus.UInt64, "Timeout",
1774
 
        type_func = lambda td: td.total_seconds() * 1000)
 
1318
    timeout = notifychangeproperty(dbus.UInt64, "Timeout",
 
1319
                                   type_func = lambda td:
 
1320
                                       td.total_seconds() * 1000)
1775
1321
    extended_timeout = notifychangeproperty(
1776
1322
        dbus.UInt64, "ExtendedTimeout",
1777
1323
        type_func = lambda td: td.total_seconds() * 1000)
1778
 
    interval = notifychangeproperty(
1779
 
        dbus.UInt64, "Interval",
1780
 
        type_func = lambda td: td.total_seconds() * 1000)
 
1324
    interval = notifychangeproperty(dbus.UInt64,
 
1325
                                    "Interval",
 
1326
                                    type_func =
 
1327
                                    lambda td: td.total_seconds()
 
1328
                                    * 1000)
1781
1329
    checker_command = notifychangeproperty(dbus.String, "Checker")
1782
1330
    secret = notifychangeproperty(dbus.ByteArray, "Secret",
1783
1331
                                  invalidate_only=True)
1793
1341
            DBusObjectWithProperties.__del__(self, *args, **kwargs)
1794
1342
        Client.__del__(self, *args, **kwargs)
1795
1343
    
1796
 
    def checker_callback(self, source, condition,
1797
 
                         connection, command, *args, **kwargs):
1798
 
        ret = Client.checker_callback(self, source, condition,
1799
 
                                      connection, command, *args,
1800
 
                                      **kwargs)
1801
 
        exitstatus = self.last_checker_status
1802
 
        if exitstatus >= 0:
 
1344
    def checker_callback(self, pid, condition, command,
 
1345
                         *args, **kwargs):
 
1346
        self.checker_callback_tag = None
 
1347
        self.checker = None
 
1348
        if os.WIFEXITED(condition):
 
1349
            exitstatus = os.WEXITSTATUS(condition)
1803
1350
            # Emit D-Bus signal
1804
1351
            self.CheckerCompleted(dbus.Int16(exitstatus),
1805
 
                                  # This is specific to GNU libC
1806
 
                                  dbus.Int64(exitstatus << 8),
 
1352
                                  dbus.Int64(condition),
1807
1353
                                  dbus.String(command))
1808
1354
        else:
1809
1355
            # Emit D-Bus signal
1810
1356
            self.CheckerCompleted(dbus.Int16(-1),
1811
 
                                  dbus.Int64(
1812
 
                                      # This is specific to GNU libC
1813
 
                                      (exitstatus << 8)
1814
 
                                      | self.last_checker_signal),
 
1357
                                  dbus.Int64(condition),
1815
1358
                                  dbus.String(command))
1816
 
        return ret
 
1359
        
 
1360
        return Client.checker_callback(self, pid, condition, command,
 
1361
                                       *args, **kwargs)
1817
1362
    
1818
1363
    def start_checker(self, *args, **kwargs):
1819
1364
        old_checker_pid = getattr(self.checker, "pid", None)
1831
1376
    
1832
1377
    def approve(self, value=True):
1833
1378
        self.approved = value
1834
 
        GLib.timeout_add(int(self.approval_duration.total_seconds()
1835
 
                             * 1000), self._reset_approved)
 
1379
        gobject.timeout_add(int(self.approval_duration.total_seconds()
 
1380
                                * 1000), self._reset_approved)
1836
1381
        self.send_changedstate()
1837
1382
    
1838
1383
    ## D-Bus methods, signals & properties
1894
1439
        self.checked_ok()
1895
1440
    
1896
1441
    # Enable - method
1897
 
    @dbus_annotations({"org.freedesktop.DBus.Deprecated": "true"})
1898
1442
    @dbus.service.method(_interface)
1899
1443
    def Enable(self):
1900
1444
        "D-Bus method"
1901
1445
        self.enable()
1902
1446
    
1903
1447
    # StartChecker - method
1904
 
    @dbus_annotations({"org.freedesktop.DBus.Deprecated": "true"})
1905
1448
    @dbus.service.method(_interface)
1906
1449
    def StartChecker(self):
1907
1450
        "D-Bus method"
1908
1451
        self.start_checker()
1909
1452
    
1910
1453
    # Disable - method
1911
 
    @dbus_annotations({"org.freedesktop.DBus.Deprecated": "true"})
1912
1454
    @dbus.service.method(_interface)
1913
1455
    def Disable(self):
1914
1456
        "D-Bus method"
1915
1457
        self.disable()
1916
1458
    
1917
1459
    # StopChecker - method
1918
 
    @dbus_annotations({"org.freedesktop.DBus.Deprecated": "true"})
1919
1460
    @dbus.service.method(_interface)
1920
1461
    def StopChecker(self):
1921
1462
        self.stop_checker()
1928
1469
        return dbus.Boolean(bool(self.approvals_pending))
1929
1470
    
1930
1471
    # ApprovedByDefault - property
1931
 
    @dbus_service_property(_interface,
1932
 
                           signature="b",
 
1472
    @dbus_service_property(_interface, signature="b",
1933
1473
                           access="readwrite")
1934
1474
    def ApprovedByDefault_dbus_property(self, value=None):
1935
1475
        if value is None:       # get
1937
1477
        self.approved_by_default = bool(value)
1938
1478
    
1939
1479
    # ApprovalDelay - property
1940
 
    @dbus_service_property(_interface,
1941
 
                           signature="t",
 
1480
    @dbus_service_property(_interface, signature="t",
1942
1481
                           access="readwrite")
1943
1482
    def ApprovalDelay_dbus_property(self, value=None):
1944
1483
        if value is None:       # get
1947
1486
        self.approval_delay = datetime.timedelta(0, 0, 0, value)
1948
1487
    
1949
1488
    # ApprovalDuration - property
1950
 
    @dbus_service_property(_interface,
1951
 
                           signature="t",
 
1489
    @dbus_service_property(_interface, signature="t",
1952
1490
                           access="readwrite")
1953
1491
    def ApprovalDuration_dbus_property(self, value=None):
1954
1492
        if value is None:       # get
1957
1495
        self.approval_duration = datetime.timedelta(0, 0, 0, value)
1958
1496
    
1959
1497
    # Name - property
1960
 
    @dbus_annotations(
1961
 
        {"org.freedesktop.DBus.Property.EmitsChangedSignal": "const"})
1962
1498
    @dbus_service_property(_interface, signature="s", access="read")
1963
1499
    def Name_dbus_property(self):
1964
1500
        return dbus.String(self.name)
1965
1501
    
1966
1502
    # Fingerprint - property
1967
 
    @dbus_annotations(
1968
 
        {"org.freedesktop.DBus.Property.EmitsChangedSignal": "const"})
1969
1503
    @dbus_service_property(_interface, signature="s", access="read")
1970
1504
    def Fingerprint_dbus_property(self):
1971
1505
        return dbus.String(self.fingerprint)
1972
1506
    
1973
1507
    # Host - property
1974
 
    @dbus_service_property(_interface,
1975
 
                           signature="s",
 
1508
    @dbus_service_property(_interface, signature="s",
1976
1509
                           access="readwrite")
1977
1510
    def Host_dbus_property(self, value=None):
1978
1511
        if value is None:       # get
1980
1513
        self.host = str(value)
1981
1514
    
1982
1515
    # Created - property
1983
 
    @dbus_annotations(
1984
 
        {"org.freedesktop.DBus.Property.EmitsChangedSignal": "const"})
1985
1516
    @dbus_service_property(_interface, signature="s", access="read")
1986
1517
    def Created_dbus_property(self):
1987
1518
        return datetime_to_dbus(self.created)
1992
1523
        return datetime_to_dbus(self.last_enabled)
1993
1524
    
1994
1525
    # Enabled - property
1995
 
    @dbus_service_property(_interface,
1996
 
                           signature="b",
 
1526
    @dbus_service_property(_interface, signature="b",
1997
1527
                           access="readwrite")
1998
1528
    def Enabled_dbus_property(self, value=None):
1999
1529
        if value is None:       # get
2004
1534
            self.disable()
2005
1535
    
2006
1536
    # LastCheckedOK - property
2007
 
    @dbus_service_property(_interface,
2008
 
                           signature="s",
 
1537
    @dbus_service_property(_interface, signature="s",
2009
1538
                           access="readwrite")
2010
1539
    def LastCheckedOK_dbus_property(self, value=None):
2011
1540
        if value is not None:
2014
1543
        return datetime_to_dbus(self.last_checked_ok)
2015
1544
    
2016
1545
    # LastCheckerStatus - property
2017
 
    @dbus_service_property(_interface, signature="n", access="read")
 
1546
    @dbus_service_property(_interface, signature="n",
 
1547
                           access="read")
2018
1548
    def LastCheckerStatus_dbus_property(self):
2019
1549
        return dbus.Int16(self.last_checker_status)
2020
1550
    
2029
1559
        return datetime_to_dbus(self.last_approval_request)
2030
1560
    
2031
1561
    # Timeout - property
2032
 
    @dbus_service_property(_interface,
2033
 
                           signature="t",
 
1562
    @dbus_service_property(_interface, signature="t",
2034
1563
                           access="readwrite")
2035
1564
    def Timeout_dbus_property(self, value=None):
2036
1565
        if value is None:       # get
2048
1577
                if (getattr(self, "disable_initiator_tag", None)
2049
1578
                    is None):
2050
1579
                    return
2051
 
                GLib.source_remove(self.disable_initiator_tag)
2052
 
                self.disable_initiator_tag = GLib.timeout_add(
2053
 
                    int((self.expires - now).total_seconds() * 1000),
2054
 
                    self.disable)
 
1580
                gobject.source_remove(self.disable_initiator_tag)
 
1581
                self.disable_initiator_tag = (
 
1582
                    gobject.timeout_add(
 
1583
                        int((self.expires - now).total_seconds()
 
1584
                            * 1000), self.disable))
2055
1585
    
2056
1586
    # ExtendedTimeout - property
2057
 
    @dbus_service_property(_interface,
2058
 
                           signature="t",
 
1587
    @dbus_service_property(_interface, signature="t",
2059
1588
                           access="readwrite")
2060
1589
    def ExtendedTimeout_dbus_property(self, value=None):
2061
1590
        if value is None:       # get
2064
1593
        self.extended_timeout = datetime.timedelta(0, 0, 0, value)
2065
1594
    
2066
1595
    # Interval - property
2067
 
    @dbus_service_property(_interface,
2068
 
                           signature="t",
 
1596
    @dbus_service_property(_interface, signature="t",
2069
1597
                           access="readwrite")
2070
1598
    def Interval_dbus_property(self, value=None):
2071
1599
        if value is None:       # get
2075
1603
            return
2076
1604
        if self.enabled:
2077
1605
            # Reschedule checker run
2078
 
            GLib.source_remove(self.checker_initiator_tag)
2079
 
            self.checker_initiator_tag = GLib.timeout_add(
2080
 
                value, self.start_checker)
2081
 
            self.start_checker() # Start one now, too
 
1606
            gobject.source_remove(self.checker_initiator_tag)
 
1607
            self.checker_initiator_tag = (gobject.timeout_add
 
1608
                                          (value, self.start_checker))
 
1609
            self.start_checker()    # Start one now, too
2082
1610
    
2083
1611
    # Checker - property
2084
 
    @dbus_service_property(_interface,
2085
 
                           signature="s",
 
1612
    @dbus_service_property(_interface, signature="s",
2086
1613
                           access="readwrite")
2087
1614
    def Checker_dbus_property(self, value=None):
2088
1615
        if value is None:       # get
2090
1617
        self.checker_command = str(value)
2091
1618
    
2092
1619
    # CheckerRunning - property
2093
 
    @dbus_service_property(_interface,
2094
 
                           signature="b",
 
1620
    @dbus_service_property(_interface, signature="b",
2095
1621
                           access="readwrite")
2096
1622
    def CheckerRunning_dbus_property(self, value=None):
2097
1623
        if value is None:       # get
2102
1628
            self.stop_checker()
2103
1629
    
2104
1630
    # ObjectPath - property
2105
 
    @dbus_annotations(
2106
 
        {"org.freedesktop.DBus.Property.EmitsChangedSignal": "const",
2107
 
         "org.freedesktop.DBus.Deprecated": "true"})
2108
1631
    @dbus_service_property(_interface, signature="o", access="read")
2109
1632
    def ObjectPath_dbus_property(self):
2110
1633
        return self.dbus_object_path # is already a dbus.ObjectPath
2111
1634
    
2112
1635
    # Secret = property
2113
 
    @dbus_annotations(
2114
 
        {"org.freedesktop.DBus.Property.EmitsChangedSignal":
2115
 
         "invalidates"})
2116
 
    @dbus_service_property(_interface,
2117
 
                           signature="ay",
2118
 
                           access="write",
2119
 
                           byte_arrays=True)
 
1636
    @dbus_service_property(_interface, signature="ay",
 
1637
                           access="write", byte_arrays=True)
2120
1638
    def Secret_dbus_property(self, value):
2121
1639
        self.secret = bytes(value)
2122
1640
    
2128
1646
        self._pipe = child_pipe
2129
1647
        self._pipe.send(('init', fpr, address))
2130
1648
        if not self._pipe.recv():
2131
 
            raise KeyError(fpr)
 
1649
            raise KeyError()
2132
1650
    
2133
1651
    def __getattribute__(self, name):
2134
1652
        if name == '_pipe':
2138
1656
        if data[0] == 'data':
2139
1657
            return data[1]
2140
1658
        if data[0] == 'function':
2141
 
            
2142
1659
            def func(*args, **kwargs):
2143
1660
                self._pipe.send(('funcall', name, args, kwargs))
2144
1661
                return self._pipe.recv()[1]
2145
 
            
2146
1662
            return func
2147
1663
    
2148
1664
    def __setattr__(self, name, value):
2164
1680
            logger.debug("Pipe FD: %d",
2165
1681
                         self.server.child_pipe.fileno())
2166
1682
            
2167
 
            session = gnutls.ClientSession(self.request)
 
1683
            session = (gnutls.connection
 
1684
                       .ClientSession(self.request,
 
1685
                                      gnutls.connection
 
1686
                                      .X509Credentials()))
 
1687
            
 
1688
            # Note: gnutls.connection.X509Credentials is really a
 
1689
            # generic GnuTLS certificate credentials object so long as
 
1690
            # no X.509 keys are added to it.  Therefore, we can use it
 
1691
            # here despite using OpenPGP certificates.
2168
1692
            
2169
1693
            #priority = ':'.join(("NONE", "+VERS-TLS1.1",
2170
1694
            #                      "+AES-256-CBC", "+SHA1",
2174
1698
            priority = self.server.gnutls_priority
2175
1699
            if priority is None:
2176
1700
                priority = "NORMAL"
2177
 
            gnutls.priority_set_direct(session._c_object,
2178
 
                                       priority.encode("utf-8"),
2179
 
                                       None)
 
1701
            (gnutls.library.functions
 
1702
             .gnutls_priority_set_direct(session._c_object,
 
1703
                                         priority, None))
2180
1704
            
2181
1705
            # Start communication using the Mandos protocol
2182
1706
            # Get protocol number
2192
1716
            # Start GnuTLS connection
2193
1717
            try:
2194
1718
                session.handshake()
2195
 
            except gnutls.Error as error:
 
1719
            except gnutls.errors.GNUTLSError as error:
2196
1720
                logger.warning("Handshake failed: %s", error)
2197
1721
                # Do not run session.bye() here: the session is not
2198
1722
                # established.  Just abandon the request.
2202
1726
            approval_required = False
2203
1727
            try:
2204
1728
                try:
2205
 
                    fpr = self.fingerprint(
2206
 
                        self.peer_certificate(session))
2207
 
                except (TypeError, gnutls.Error) as error:
 
1729
                    fpr = self.fingerprint(self.peer_certificate
 
1730
                                           (session))
 
1731
                except (TypeError,
 
1732
                        gnutls.errors.GNUTLSError) as error:
2208
1733
                    logger.warning("Bad certificate: %s", error)
2209
1734
                    return
2210
1735
                logger.debug("Fingerprint: %s", fpr)
2223
1748
                while True:
2224
1749
                    if not client.enabled:
2225
1750
                        logger.info("Client %s is disabled",
2226
 
                                    client.name)
 
1751
                                       client.name)
2227
1752
                        if self.server.use_dbus:
2228
1753
                            # Emit D-Bus signal
2229
1754
                            client.Rejected("Disabled")
2268
1793
                    else:
2269
1794
                        delay -= time2 - time
2270
1795
                
2271
 
                try:
2272
 
                    session.send(client.secret)
2273
 
                except gnutls.Error as error:
2274
 
                    logger.warning("gnutls send failed",
2275
 
                                   exc_info = error)
2276
 
                    return
 
1796
                sent_size = 0
 
1797
                while sent_size < len(client.secret):
 
1798
                    try:
 
1799
                        sent = session.send(client.secret[sent_size:])
 
1800
                    except gnutls.errors.GNUTLSError as error:
 
1801
                        logger.warning("gnutls send failed",
 
1802
                                       exc_info=error)
 
1803
                        return
 
1804
                    logger.debug("Sent: %d, remaining: %d",
 
1805
                                 sent, len(client.secret)
 
1806
                                 - (sent_size + sent))
 
1807
                    sent_size += sent
2277
1808
                
2278
1809
                logger.info("Sending secret to %s", client.name)
2279
1810
                # bump the timeout using extended_timeout
2287
1818
                    client.approvals_pending -= 1
2288
1819
                try:
2289
1820
                    session.bye()
2290
 
                except gnutls.Error as error:
 
1821
                except gnutls.errors.GNUTLSError as error:
2291
1822
                    logger.warning("GnuTLS bye failed",
2292
1823
                                   exc_info=error)
2293
1824
    
2295
1826
    def peer_certificate(session):
2296
1827
        "Return the peer's OpenPGP certificate as a bytestring"
2297
1828
        # If not an OpenPGP certificate...
2298
 
        if (gnutls.certificate_type_get(session._c_object)
2299
 
            != gnutls.CRT_OPENPGP):
2300
 
            # ...return invalid data
2301
 
            return b""
 
1829
        if (gnutls.library.functions
 
1830
            .gnutls_certificate_type_get(session._c_object)
 
1831
            != gnutls.library.constants.GNUTLS_CRT_OPENPGP):
 
1832
            # ...do the normal thing
 
1833
            return session.peer_certificate
2302
1834
        list_size = ctypes.c_uint(1)
2303
 
        cert_list = (gnutls.certificate_get_peers
 
1835
        cert_list = (gnutls.library.functions
 
1836
                     .gnutls_certificate_get_peers
2304
1837
                     (session._c_object, ctypes.byref(list_size)))
2305
1838
        if not bool(cert_list) and list_size.value != 0:
2306
 
            raise gnutls.Error("error getting peer certificate")
 
1839
            raise gnutls.errors.GNUTLSError("error getting peer"
 
1840
                                            " certificate")
2307
1841
        if list_size.value == 0:
2308
1842
            return None
2309
1843
        cert = cert_list[0]
2313
1847
    def fingerprint(openpgp):
2314
1848
        "Convert an OpenPGP bytestring to a hexdigit fingerprint"
2315
1849
        # New GnuTLS "datum" with the OpenPGP public key
2316
 
        datum = gnutls.datum_t(
2317
 
            ctypes.cast(ctypes.c_char_p(openpgp),
2318
 
                        ctypes.POINTER(ctypes.c_ubyte)),
2319
 
            ctypes.c_uint(len(openpgp)))
 
1850
        datum = (gnutls.library.types
 
1851
                 .gnutls_datum_t(ctypes.cast(ctypes.c_char_p(openpgp),
 
1852
                                             ctypes.POINTER
 
1853
                                             (ctypes.c_ubyte)),
 
1854
                                 ctypes.c_uint(len(openpgp))))
2320
1855
        # New empty GnuTLS certificate
2321
 
        crt = gnutls.openpgp_crt_t()
2322
 
        gnutls.openpgp_crt_init(ctypes.byref(crt))
 
1856
        crt = gnutls.library.types.gnutls_openpgp_crt_t()
 
1857
        (gnutls.library.functions
 
1858
         .gnutls_openpgp_crt_init(ctypes.byref(crt)))
2323
1859
        # Import the OpenPGP public key into the certificate
2324
 
        gnutls.openpgp_crt_import(crt, ctypes.byref(datum),
2325
 
                                  gnutls.OPENPGP_FMT_RAW)
 
1860
        (gnutls.library.functions
 
1861
         .gnutls_openpgp_crt_import(crt, ctypes.byref(datum),
 
1862
                                    gnutls.library.constants
 
1863
                                    .GNUTLS_OPENPGP_FMT_RAW))
2326
1864
        # Verify the self signature in the key
2327
1865
        crtverify = ctypes.c_uint()
2328
 
        gnutls.openpgp_crt_verify_self(crt, 0,
2329
 
                                       ctypes.byref(crtverify))
 
1866
        (gnutls.library.functions
 
1867
         .gnutls_openpgp_crt_verify_self(crt, 0,
 
1868
                                         ctypes.byref(crtverify)))
2330
1869
        if crtverify.value != 0:
2331
 
            gnutls.openpgp_crt_deinit(crt)
2332
 
            raise gnutls.CertificateSecurityError("Verify failed")
 
1870
            gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
 
1871
            raise (gnutls.errors.CertificateSecurityError
 
1872
                   ("Verify failed"))
2333
1873
        # New buffer for the fingerprint
2334
1874
        buf = ctypes.create_string_buffer(20)
2335
1875
        buf_len = ctypes.c_size_t()
2336
1876
        # Get the fingerprint from the certificate into the buffer
2337
 
        gnutls.openpgp_crt_get_fingerprint(crt, ctypes.byref(buf),
2338
 
                                           ctypes.byref(buf_len))
 
1877
        (gnutls.library.functions
 
1878
         .gnutls_openpgp_crt_get_fingerprint(crt, ctypes.byref(buf),
 
1879
                                             ctypes.byref(buf_len)))
2339
1880
        # Deinit the certificate
2340
 
        gnutls.openpgp_crt_deinit(crt)
 
1881
        gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
2341
1882
        # Convert the buffer to a Python bytestring
2342
1883
        fpr = ctypes.string_at(buf, buf_len.value)
2343
1884
        # Convert the bytestring to hexadecimal notation
2347
1888
 
2348
1889
class MultiprocessingMixIn(object):
2349
1890
    """Like socketserver.ThreadingMixIn, but with multiprocessing"""
2350
 
    
2351
1891
    def sub_process_main(self, request, address):
2352
1892
        try:
2353
1893
            self.finish_request(request, address)
2365
1905
 
2366
1906
class MultiprocessingMixInWithPipe(MultiprocessingMixIn, object):
2367
1907
    """ adds a pipe to the MixIn """
2368
 
    
2369
1908
    def process_request(self, request, client_address):
2370
1909
        """Overrides and wraps the original process_request().
2371
1910
        
2392
1931
        interface:      None or a network interface name (string)
2393
1932
        use_ipv6:       Boolean; to use IPv6 or not
2394
1933
    """
2395
 
    
2396
1934
    def __init__(self, server_address, RequestHandlerClass,
2397
 
                 interface=None,
2398
 
                 use_ipv6=True,
2399
 
                 socketfd=None):
 
1935
                 interface=None, use_ipv6=True, socketfd=None):
2400
1936
        """If socketfd is set, use that file descriptor instead of
2401
1937
        creating a new one with socket.socket().
2402
1938
        """
2443
1979
                             self.interface)
2444
1980
            else:
2445
1981
                try:
2446
 
                    self.socket.setsockopt(
2447
 
                        socket.SOL_SOCKET, SO_BINDTODEVICE,
2448
 
                        (self.interface + "\0").encode("utf-8"))
 
1982
                    self.socket.setsockopt(socket.SOL_SOCKET,
 
1983
                                           SO_BINDTODEVICE,
 
1984
                                           (self.interface + "\0")
 
1985
                                           .encode("utf-8"))
2449
1986
                except socket.error as error:
2450
1987
                    if error.errno == errno.EPERM:
2451
1988
                        logger.error("No permission to bind to"
2469
2006
                self.server_address = (any_address,
2470
2007
                                       self.server_address[1])
2471
2008
            elif not self.server_address[1]:
2472
 
                self.server_address = (self.server_address[0], 0)
 
2009
                self.server_address = (self.server_address[0],
 
2010
                                       0)
2473
2011
#                 if self.interface:
2474
2012
#                     self.server_address = (self.server_address[0],
2475
2013
#                                            0, # port
2487
2025
        gnutls_priority GnuTLS priority string
2488
2026
        use_dbus:       Boolean; to emit D-Bus signals or not
2489
2027
    
2490
 
    Assumes a GLib.MainLoop event loop.
 
2028
    Assumes a gobject.MainLoop event loop.
2491
2029
    """
2492
 
    
2493
2030
    def __init__(self, server_address, RequestHandlerClass,
2494
 
                 interface=None,
2495
 
                 use_ipv6=True,
2496
 
                 clients=None,
2497
 
                 gnutls_priority=None,
2498
 
                 use_dbus=True,
2499
 
                 socketfd=None):
 
2031
                 interface=None, use_ipv6=True, clients=None,
 
2032
                 gnutls_priority=None, use_dbus=True, socketfd=None):
2500
2033
        self.enabled = False
2501
2034
        self.clients = clients
2502
2035
        if self.clients is None:
2508
2041
                                interface = interface,
2509
2042
                                use_ipv6 = use_ipv6,
2510
2043
                                socketfd = socketfd)
2511
 
    
2512
2044
    def server_activate(self):
2513
2045
        if self.enabled:
2514
2046
            return socketserver.TCPServer.server_activate(self)
2518
2050
    
2519
2051
    def add_pipe(self, parent_pipe, proc):
2520
2052
        # Call "handle_ipc" for both data and EOF events
2521
 
        GLib.io_add_watch(
2522
 
            parent_pipe.fileno(),
2523
 
            GLib.IO_IN | GLib.IO_HUP,
2524
 
            functools.partial(self.handle_ipc,
2525
 
                              parent_pipe = parent_pipe,
2526
 
                              proc = proc))
 
2053
        gobject.io_add_watch(parent_pipe.fileno(),
 
2054
                             gobject.IO_IN | gobject.IO_HUP,
 
2055
                             functools.partial(self.handle_ipc,
 
2056
                                               parent_pipe =
 
2057
                                               parent_pipe,
 
2058
                                               proc = proc))
2527
2059
    
2528
 
    def handle_ipc(self, source, condition,
2529
 
                   parent_pipe=None,
2530
 
                   proc = None,
2531
 
                   client_object=None):
 
2060
    def handle_ipc(self, source, condition, parent_pipe=None,
 
2061
                   proc = None, client_object=None):
2532
2062
        # error, or the other end of multiprocessing.Pipe has closed
2533
 
        if condition & (GLib.IO_ERR | GLib.IO_HUP):
 
2063
        if condition & (gobject.IO_ERR | gobject.IO_HUP):
2534
2064
            # Wait for other process to exit
2535
2065
            proc.join()
2536
2066
            return False
2543
2073
            fpr = request[1]
2544
2074
            address = request[2]
2545
2075
            
2546
 
            for c in self.clients.values():
 
2076
            for c in self.clients.itervalues():
2547
2077
                if c.fingerprint == fpr:
2548
2078
                    client = c
2549
2079
                    break
2557
2087
                parent_pipe.send(False)
2558
2088
                return False
2559
2089
            
2560
 
            GLib.io_add_watch(
2561
 
                parent_pipe.fileno(),
2562
 
                GLib.IO_IN | GLib.IO_HUP,
2563
 
                functools.partial(self.handle_ipc,
2564
 
                                  parent_pipe = parent_pipe,
2565
 
                                  proc = proc,
2566
 
                                  client_object = client))
 
2090
            gobject.io_add_watch(parent_pipe.fileno(),
 
2091
                                 gobject.IO_IN | gobject.IO_HUP,
 
2092
                                 functools.partial(self.handle_ipc,
 
2093
                                                   parent_pipe =
 
2094
                                                   parent_pipe,
 
2095
                                                   proc = proc,
 
2096
                                                   client_object =
 
2097
                                                   client))
2567
2098
            parent_pipe.send(True)
2568
2099
            # remove the old hook in favor of the new above hook on
2569
2100
            # same fileno
2575
2106
            
2576
2107
            parent_pipe.send(('data', getattr(client_object,
2577
2108
                                              funcname)(*args,
2578
 
                                                        **kwargs)))
 
2109
                                                         **kwargs)))
2579
2110
        
2580
2111
        if command == 'getattr':
2581
2112
            attrname = request[1]
2582
 
            if isinstance(client_object.__getattribute__(attrname),
2583
 
                          collections.Callable):
2584
 
                parent_pipe.send(('function', ))
 
2113
            if callable(client_object.__getattribute__(attrname)):
 
2114
                parent_pipe.send(('function',))
2585
2115
            else:
2586
 
                parent_pipe.send((
2587
 
                    'data', client_object.__getattribute__(attrname)))
 
2116
                parent_pipe.send(('data', client_object
 
2117
                                  .__getattribute__(attrname)))
2588
2118
        
2589
2119
        if command == 'setattr':
2590
2120
            attrname = request[1]
2621
2151
    # avoid excessive use of external libraries.
2622
2152
    
2623
2153
    # New type for defining tokens, syntax, and semantics all-in-one
2624
 
    Token = collections.namedtuple("Token", (
2625
 
        "regexp",  # To match token; if "value" is not None, must have
2626
 
                   # a "group" containing digits
2627
 
        "value",   # datetime.timedelta or None
2628
 
        "followers"))           # Tokens valid after this token
 
2154
    Token = collections.namedtuple("Token",
 
2155
                                   ("regexp", # To match token; if
 
2156
                                              # "value" is not None,
 
2157
                                              # must have a "group"
 
2158
                                              # containing digits
 
2159
                                    "value",  # datetime.timedelta or
 
2160
                                              # None
 
2161
                                    "followers")) # Tokens valid after
 
2162
                                                  # this token
2629
2163
    # RFC 3339 "duration" tokens, syntax, and semantics; taken from
2630
2164
    # the "duration" ABNF definition in RFC 3339, Appendix A.
2631
2165
    token_end = Token(re.compile(r"$"), None, frozenset())
2632
2166
    token_second = Token(re.compile(r"(\d+)S"),
2633
2167
                         datetime.timedelta(seconds=1),
2634
 
                         frozenset((token_end, )))
 
2168
                         frozenset((token_end,)))
2635
2169
    token_minute = Token(re.compile(r"(\d+)M"),
2636
2170
                         datetime.timedelta(minutes=1),
2637
2171
                         frozenset((token_second, token_end)))
2653
2187
                       frozenset((token_month, token_end)))
2654
2188
    token_week = Token(re.compile(r"(\d+)W"),
2655
2189
                       datetime.timedelta(weeks=1),
2656
 
                       frozenset((token_end, )))
 
2190
                       frozenset((token_end,)))
2657
2191
    token_duration = Token(re.compile(r"P"), None,
2658
2192
                           frozenset((token_year, token_month,
2659
2193
                                      token_day, token_time,
2661
2195
    # Define starting values
2662
2196
    value = datetime.timedelta() # Value so far
2663
2197
    found_token = None
2664
 
    followers = frozenset((token_duration, )) # Following valid tokens
 
2198
    followers = frozenset((token_duration,)) # Following valid tokens
2665
2199
    s = duration                # String left to parse
2666
2200
    # Loop until end token is found
2667
2201
    while found_token is not token_end:
2684
2218
                break
2685
2219
        else:
2686
2220
            # No currently valid tokens were found
2687
 
            raise ValueError("Invalid RFC 3339 duration: {!r}"
2688
 
                             .format(duration))
 
2221
            raise ValueError("Invalid RFC 3339 duration")
2689
2222
    # End token found
2690
2223
    return value
2691
2224
 
2728
2261
            elif suffix == "w":
2729
2262
                delta = datetime.timedelta(0, 0, 0, 0, 0, 0, value)
2730
2263
            else:
2731
 
                raise ValueError("Unknown suffix {!r}".format(suffix))
 
2264
                raise ValueError("Unknown suffix {!r}"
 
2265
                                 .format(suffix))
2732
2266
        except IndexError as e:
2733
2267
            raise ValueError(*(e.args))
2734
2268
        timevalue += delta
2750
2284
        # Close all standard open file descriptors
2751
2285
        null = os.open(os.devnull, os.O_NOCTTY | os.O_RDWR)
2752
2286
        if not stat.S_ISCHR(os.fstat(null).st_mode):
2753
 
            raise OSError(errno.ENODEV,
2754
 
                          "{} not a character device"
 
2287
            raise OSError(errno.ENODEV, "{} not a character device"
2755
2288
                          .format(os.devnull))
2756
2289
        os.dup2(null, sys.stdin.fileno())
2757
2290
        os.dup2(null, sys.stdout.fileno())
2824
2357
                        "debug": "False",
2825
2358
                        "priority":
2826
2359
                        "SECURE256:!CTYPE-X.509:+CTYPE-OPENPGP:!RSA"
2827
 
                        ":+SIGN-DSA-SHA256",
 
2360
                        ":+SIGN-RSA-SHA224:+SIGN-RSA-RMD160",
2828
2361
                        "servicename": "Mandos",
2829
2362
                        "use_dbus": "True",
2830
2363
                        "use_ipv6": "True",
2834
2367
                        "statedir": "/var/lib/mandos",
2835
2368
                        "foreground": "False",
2836
2369
                        "zeroconf": "True",
2837
 
                    }
 
2370
                        }
2838
2371
    
2839
2372
    # Parse config file for server-global settings
2840
2373
    server_config = configparser.SafeConfigParser(server_defaults)
2841
2374
    del server_defaults
2842
 
    server_config.read(os.path.join(options.configdir, "mandos.conf"))
 
2375
    server_config.read(os.path.join(options.configdir,
 
2376
                                    "mandos.conf"))
2843
2377
    # Convert the SafeConfigParser object to a dict
2844
2378
    server_settings = server_config.defaults()
2845
2379
    # Use the appropriate methods on the non-string config options
2863
2397
    # Override the settings from the config file with command line
2864
2398
    # options, if set.
2865
2399
    for option in ("interface", "address", "port", "debug",
2866
 
                   "priority", "servicename", "configdir", "use_dbus",
2867
 
                   "use_ipv6", "debuglevel", "restore", "statedir",
2868
 
                   "socket", "foreground", "zeroconf"):
 
2400
                   "priority", "servicename", "configdir",
 
2401
                   "use_dbus", "use_ipv6", "debuglevel", "restore",
 
2402
                   "statedir", "socket", "foreground", "zeroconf"):
2869
2403
        value = getattr(options, option)
2870
2404
        if value is not None:
2871
2405
            server_settings[option] = value
2886
2420
    
2887
2421
    ##################################################################
2888
2422
    
2889
 
    if (not server_settings["zeroconf"]
2890
 
        and not (server_settings["port"]
2891
 
                 or server_settings["socket"] != "")):
2892
 
        parser.error("Needs port or socket to work without Zeroconf")
 
2423
    if (not server_settings["zeroconf"] and
 
2424
        not (server_settings["port"]
 
2425
             or server_settings["socket"] != "")):
 
2426
            parser.error("Needs port or socket to work without"
 
2427
                         " Zeroconf")
2893
2428
    
2894
2429
    # For convenience
2895
2430
    debug = server_settings["debug"]
2911
2446
            initlogger(debug, level)
2912
2447
    
2913
2448
    if server_settings["servicename"] != "Mandos":
2914
 
        syslogger.setFormatter(
2915
 
            logging.Formatter('Mandos ({}) [%(process)d]:'
2916
 
                              ' %(levelname)s: %(message)s'.format(
2917
 
                                  server_settings["servicename"])))
 
2449
        syslogger.setFormatter(logging.Formatter
 
2450
                               ('Mandos ({}) [%(process)d]:'
 
2451
                                ' %(levelname)s: %(message)s'
 
2452
                                .format(server_settings
 
2453
                                        ["servicename"])))
2918
2454
    
2919
2455
    # Parse config file with clients
2920
2456
    client_config = configparser.SafeConfigParser(Client
2928
2464
    socketfd = None
2929
2465
    if server_settings["socket"] != "":
2930
2466
        socketfd = server_settings["socket"]
2931
 
    tcp_server = MandosServer(
2932
 
        (server_settings["address"], server_settings["port"]),
2933
 
        ClientHandler,
2934
 
        interface=(server_settings["interface"] or None),
2935
 
        use_ipv6=use_ipv6,
2936
 
        gnutls_priority=server_settings["priority"],
2937
 
        use_dbus=use_dbus,
2938
 
        socketfd=socketfd)
 
2467
    tcp_server = MandosServer((server_settings["address"],
 
2468
                               server_settings["port"]),
 
2469
                              ClientHandler,
 
2470
                              interface=(server_settings["interface"]
 
2471
                                         or None),
 
2472
                              use_ipv6=use_ipv6,
 
2473
                              gnutls_priority=
 
2474
                              server_settings["priority"],
 
2475
                              use_dbus=use_dbus,
 
2476
                              socketfd=socketfd)
2939
2477
    if not foreground:
2940
2478
        pidfilename = "/run/mandos.pid"
2941
2479
        if not os.path.isdir("/run/."):
2942
2480
            pidfilename = "/var/run/mandos.pid"
2943
2481
        pidfile = None
2944
2482
        try:
2945
 
            pidfile = codecs.open(pidfilename, "w", encoding="utf-8")
 
2483
            pidfile = open(pidfilename, "w")
2946
2484
        except IOError as e:
2947
2485
            logger.error("Could not open file %r", pidfilename,
2948
2486
                         exc_info=e)
2949
2487
    
2950
 
    for name, group in (("_mandos", "_mandos"),
2951
 
                        ("mandos", "mandos"),
2952
 
                        ("nobody", "nogroup")):
 
2488
    for name in ("_mandos", "mandos", "nobody"):
2953
2489
        try:
2954
2490
            uid = pwd.getpwnam(name).pw_uid
2955
 
            gid = pwd.getpwnam(group).pw_gid
 
2491
            gid = pwd.getpwnam(name).pw_gid
2956
2492
            break
2957
2493
        except KeyError:
2958
2494
            continue
2962
2498
    try:
2963
2499
        os.setgid(gid)
2964
2500
        os.setuid(uid)
2965
 
        if debug:
2966
 
            logger.debug("Did setuid/setgid to {}:{}".format(uid,
2967
 
                                                             gid))
2968
2501
    except OSError as error:
2969
 
        logger.warning("Failed to setuid/setgid to {}:{}: {}"
2970
 
                       .format(uid, gid, os.strerror(error.errno)))
2971
2502
        if error.errno != errno.EPERM:
2972
2503
            raise
2973
2504
    
2976
2507
        
2977
2508
        # "Use a log level over 10 to enable all debugging options."
2978
2509
        # - GnuTLS manual
2979
 
        gnutls.global_set_log_level(11)
 
2510
        gnutls.library.functions.gnutls_global_set_log_level(11)
2980
2511
        
2981
 
        @gnutls.log_func
 
2512
        @gnutls.library.types.gnutls_log_func
2982
2513
        def debug_gnutls(level, string):
2983
2514
            logger.debug("GnuTLS: %s", string[:-1])
2984
2515
        
2985
 
        gnutls.global_set_log_function(debug_gnutls)
 
2516
        (gnutls.library.functions
 
2517
         .gnutls_global_set_log_function(debug_gnutls))
2986
2518
        
2987
2519
        # Redirect stdin so all checkers get /dev/null
2988
2520
        null = os.open(os.devnull, os.O_NOCTTY | os.O_RDWR)
2995
2527
        # Close all input and output, do double fork, etc.
2996
2528
        daemon()
2997
2529
    
2998
 
    # multiprocessing will use threads, so before we use GLib we need
2999
 
    # to inform GLib that threads will be used.
3000
 
    GLib.threads_init()
 
2530
    # multiprocessing will use threads, so before we use gobject we
 
2531
    # need to inform gobject that threads will be used.
 
2532
    gobject.threads_init()
3001
2533
    
3002
2534
    global main_loop
3003
2535
    # From the Avahi example code
3004
2536
    DBusGMainLoop(set_as_default=True)
3005
 
    main_loop = GLib.MainLoop()
 
2537
    main_loop = gobject.MainLoop()
3006
2538
    bus = dbus.SystemBus()
3007
2539
    # End of Avahi example code
3008
2540
    if use_dbus:
3009
2541
        try:
3010
2542
            bus_name = dbus.service.BusName("se.recompile.Mandos",
3011
 
                                            bus,
3012
 
                                            do_not_queue=True)
3013
 
            old_bus_name = dbus.service.BusName(
3014
 
                "se.bsnet.fukt.Mandos", bus,
3015
 
                do_not_queue=True)
3016
 
        except dbus.exceptions.DBusException as e:
 
2543
                                            bus, do_not_queue=True)
 
2544
            old_bus_name = (dbus.service.BusName
 
2545
                            ("se.bsnet.fukt.Mandos", bus,
 
2546
                             do_not_queue=True))
 
2547
        except dbus.exceptions.NameExistsException as e:
3017
2548
            logger.error("Disabling D-Bus:", exc_info=e)
3018
2549
            use_dbus = False
3019
2550
            server_settings["use_dbus"] = False
3020
2551
            tcp_server.use_dbus = False
3021
2552
    if zeroconf:
3022
2553
        protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
3023
 
        service = AvahiServiceToSyslog(
3024
 
            name = server_settings["servicename"],
3025
 
            servicetype = "_mandos._tcp",
3026
 
            protocol = protocol,
3027
 
            bus = bus)
 
2554
        service = AvahiServiceToSyslog(name =
 
2555
                                       server_settings["servicename"],
 
2556
                                       servicetype = "_mandos._tcp",
 
2557
                                       protocol = protocol, bus = bus)
3028
2558
        if server_settings["interface"]:
3029
 
            service.interface = if_nametoindex(
3030
 
                server_settings["interface"].encode("utf-8"))
 
2559
            service.interface = (if_nametoindex
 
2560
                                 (server_settings["interface"]
 
2561
                                  .encode("utf-8")))
3031
2562
    
3032
2563
    global multiprocessing_manager
3033
2564
    multiprocessing_manager = multiprocessing.Manager()
3052
2583
    if server_settings["restore"]:
3053
2584
        try:
3054
2585
            with open(stored_state_path, "rb") as stored_state:
3055
 
                if sys.version_info.major == 2:                
3056
 
                    clients_data, old_client_settings = pickle.load(
3057
 
                        stored_state)
3058
 
                else:
3059
 
                    bytes_clients_data, bytes_old_client_settings = (
3060
 
                        pickle.load(stored_state, encoding = "bytes"))
3061
 
                    ### Fix bytes to strings
3062
 
                    ## clients_data
3063
 
                    # .keys()
3064
 
                    clients_data = { (key.decode("utf-8")
3065
 
                                      if isinstance(key, bytes)
3066
 
                                      else key): value
3067
 
                                     for key, value in
3068
 
                                     bytes_clients_data.items() }
3069
 
                    del bytes_clients_data
3070
 
                    for key in clients_data:
3071
 
                        value = { (k.decode("utf-8")
3072
 
                                   if isinstance(k, bytes) else k): v
3073
 
                                  for k, v in
3074
 
                                  clients_data[key].items() }
3075
 
                        clients_data[key] = value
3076
 
                        # .client_structure
3077
 
                        value["client_structure"] = [
3078
 
                            (s.decode("utf-8")
3079
 
                             if isinstance(s, bytes)
3080
 
                             else s) for s in
3081
 
                            value["client_structure"] ]
3082
 
                        # .name & .host
3083
 
                        for k in ("name", "host"):
3084
 
                            if isinstance(value[k], bytes):
3085
 
                                value[k] = value[k].decode("utf-8")
3086
 
                    ## old_client_settings
3087
 
                    # .keys()
3088
 
                    old_client_settings = {
3089
 
                        (key.decode("utf-8")
3090
 
                         if isinstance(key, bytes)
3091
 
                         else key): value
3092
 
                        for key, value in
3093
 
                        bytes_old_client_settings.items() }
3094
 
                    del bytes_old_client_settings
3095
 
                    # .host
3096
 
                    for value in old_client_settings.values():
3097
 
                        if isinstance(value["host"], bytes):
3098
 
                            value["host"] = (value["host"]
3099
 
                                             .decode("utf-8"))
 
2586
                clients_data, old_client_settings = (pickle.load
 
2587
                                                     (stored_state))
3100
2588
            os.remove(stored_state_path)
3101
2589
        except IOError as e:
3102
2590
            if e.errno == errno.ENOENT:
3103
 
                logger.warning("Could not load persistent state:"
3104
 
                               " {}".format(os.strerror(e.errno)))
 
2591
                logger.warning("Could not load persistent state: {}"
 
2592
                                .format(os.strerror(e.errno)))
3105
2593
            else:
3106
2594
                logger.critical("Could not load persistent state:",
3107
2595
                                exc_info=e)
3108
2596
                raise
3109
2597
        except EOFError as e:
3110
2598
            logger.warning("Could not load persistent state: "
3111
 
                           "EOFError:",
3112
 
                           exc_info=e)
 
2599
                           "EOFError:", exc_info=e)
3113
2600
    
3114
2601
    with PGPEngine() as pgp:
3115
2602
        for client_name, client in clients_data.items():
3127
2614
                    # For each value in new config, check if it
3128
2615
                    # differs from the old config value (Except for
3129
2616
                    # the "secret" attribute)
3130
 
                    if (name != "secret"
3131
 
                        and (value !=
3132
 
                             old_client_settings[client_name][name])):
 
2617
                    if (name != "secret" and
 
2618
                        value != old_client_settings[client_name]
 
2619
                        [name]):
3133
2620
                        client[name] = value
3134
2621
                except KeyError:
3135
2622
                    pass
3136
2623
            
3137
2624
            # Clients who has passed its expire date can still be
3138
 
            # enabled if its last checker was successful.  A Client
 
2625
            # enabled if its last checker was successful.  Clients
3139
2626
            # whose checker succeeded before we stored its state is
3140
2627
            # assumed to have successfully run all checkers during
3141
2628
            # downtime.
3144
2631
                    if not client["last_checked_ok"]:
3145
2632
                        logger.warning(
3146
2633
                            "disabling client {} - Client never "
3147
 
                            "performed a successful checker".format(
3148
 
                                client_name))
 
2634
                            "performed a successful checker"
 
2635
                            .format(client_name))
3149
2636
                        client["enabled"] = False
3150
2637
                    elif client["last_checker_status"] != 0:
3151
2638
                        logger.warning(
3152
2639
                            "disabling client {} - Client last"
3153
 
                            " checker failed with error code"
3154
 
                            " {}".format(
3155
 
                                client_name,
3156
 
                                client["last_checker_status"]))
 
2640
                            " checker failed with error code {}"
 
2641
                            .format(client_name,
 
2642
                                    client["last_checker_status"]))
3157
2643
                        client["enabled"] = False
3158
2644
                    else:
3159
 
                        client["expires"] = (
3160
 
                            datetime.datetime.utcnow()
3161
 
                            + client["timeout"])
 
2645
                        client["expires"] = (datetime.datetime
 
2646
                                             .utcnow()
 
2647
                                             + client["timeout"])
3162
2648
                        logger.debug("Last checker succeeded,"
3163
 
                                     " keeping {} enabled".format(
3164
 
                                         client_name))
 
2649
                                     " keeping {} enabled"
 
2650
                                     .format(client_name))
3165
2651
            try:
3166
 
                client["secret"] = pgp.decrypt(
3167
 
                    client["encrypted_secret"],
3168
 
                    client_settings[client_name]["secret"])
 
2652
                client["secret"] = (
 
2653
                    pgp.decrypt(client["encrypted_secret"],
 
2654
                                client_settings[client_name]
 
2655
                                ["secret"]))
3169
2656
            except PGPError:
3170
2657
                # If decryption fails, we use secret from new settings
3171
 
                logger.debug("Failed to decrypt {} old secret".format(
3172
 
                    client_name))
3173
 
                client["secret"] = (client_settings[client_name]
3174
 
                                    ["secret"])
 
2658
                logger.debug("Failed to decrypt {} old secret"
 
2659
                             .format(client_name))
 
2660
                client["secret"] = (
 
2661
                    client_settings[client_name]["secret"])
3175
2662
    
3176
2663
    # Add/remove clients based on new changes made to config
3177
2664
    for client_name in (set(old_client_settings)
3184
2671
    # Create all client objects
3185
2672
    for client_name, client in clients_data.items():
3186
2673
        tcp_server.clients[client_name] = client_class(
3187
 
            name = client_name,
3188
 
            settings = client,
 
2674
            name = client_name, settings = client,
3189
2675
            server_settings = server_settings)
3190
2676
    
3191
2677
    if not tcp_server.clients:
3193
2679
    
3194
2680
    if not foreground:
3195
2681
        if pidfile is not None:
3196
 
            pid = os.getpid()
3197
2682
            try:
3198
2683
                with pidfile:
3199
 
                    print(pid, file=pidfile)
 
2684
                    pid = os.getpid()
 
2685
                    pidfile.write("{}\n".format(pid).encode("utf-8"))
3200
2686
            except IOError:
3201
2687
                logger.error("Could not write to file %r with PID %d",
3202
2688
                             pidfilename, pid)
3203
2689
        del pidfile
3204
2690
        del pidfilename
3205
2691
    
3206
 
    for termsig in (signal.SIGHUP, signal.SIGTERM):
3207
 
        GLib.unix_signal_add(GLib.PRIORITY_HIGH, termsig,
3208
 
                             lambda: main_loop.quit() and False)
 
2692
    signal.signal(signal.SIGHUP, lambda signum, frame: sys.exit())
 
2693
    signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit())
3209
2694
    
3210
2695
    if use_dbus:
3211
 
        
3212
 
        @alternate_dbus_interfaces(
3213
 
            { "se.recompile.Mandos": "se.bsnet.fukt.Mandos" })
3214
 
        class MandosDBusService(DBusObjectWithObjectManager):
 
2696
        @alternate_dbus_interfaces({"se.recompile.Mandos":
 
2697
                                        "se.bsnet.fukt.Mandos"})
 
2698
        class MandosDBusService(DBusObjectWithProperties):
3215
2699
            """A D-Bus proxy object"""
3216
 
            
3217
2700
            def __init__(self):
3218
2701
                dbus.service.Object.__init__(self, bus, "/")
3219
 
            
3220
2702
            _interface = "se.recompile.Mandos"
3221
2703
            
 
2704
            @dbus_interface_annotations(_interface)
 
2705
            def _foo(self):
 
2706
                return { "org.freedesktop.DBus.Property"
 
2707
                         ".EmitsChangedSignal":
 
2708
                             "false"}
 
2709
            
3222
2710
            @dbus.service.signal(_interface, signature="o")
3223
2711
            def ClientAdded(self, objpath):
3224
2712
                "D-Bus signal"
3229
2717
                "D-Bus signal"
3230
2718
                pass
3231
2719
            
3232
 
            @dbus_annotations({"org.freedesktop.DBus.Deprecated":
3233
 
                               "true"})
3234
2720
            @dbus.service.signal(_interface, signature="os")
3235
2721
            def ClientRemoved(self, objpath, name):
3236
2722
                "D-Bus signal"
3237
2723
                pass
3238
2724
            
3239
 
            @dbus_annotations({"org.freedesktop.DBus.Deprecated":
3240
 
                               "true"})
3241
2725
            @dbus.service.method(_interface, out_signature="ao")
3242
2726
            def GetAllClients(self):
3243
2727
                "D-Bus method"
3244
 
                return dbus.Array(c.dbus_object_path for c in
3245
 
                                  tcp_server.clients.values())
 
2728
                return dbus.Array(c.dbus_object_path
 
2729
                                  for c in
 
2730
                                  tcp_server.clients.itervalues())
3246
2731
            
3247
 
            @dbus_annotations({"org.freedesktop.DBus.Deprecated":
3248
 
                               "true"})
3249
2732
            @dbus.service.method(_interface,
3250
2733
                                 out_signature="a{oa{sv}}")
3251
2734
            def GetAllClientsWithProperties(self):
3252
2735
                "D-Bus method"
3253
2736
                return dbus.Dictionary(
3254
 
                    { c.dbus_object_path: c.GetAll(
3255
 
                        "se.recompile.Mandos.Client")
3256
 
                      for c in tcp_server.clients.values() },
 
2737
                    { c.dbus_object_path: c.GetAll("")
 
2738
                      for c in tcp_server.clients.itervalues() },
3257
2739
                    signature="oa{sv}")
3258
2740
            
3259
2741
            @dbus.service.method(_interface, in_signature="o")
3260
2742
            def RemoveClient(self, object_path):
3261
2743
                "D-Bus method"
3262
 
                for c in tcp_server.clients.values():
 
2744
                for c in tcp_server.clients.itervalues():
3263
2745
                    if c.dbus_object_path == object_path:
3264
2746
                        del tcp_server.clients[c.name]
3265
2747
                        c.remove_from_connection()
3266
 
                        # Don't signal the disabling
 
2748
                        # Don't signal anything except ClientRemoved
3267
2749
                        c.disable(quiet=True)
3268
 
                        # Emit D-Bus signal for removal
3269
 
                        self.client_removed_signal(c)
 
2750
                        # Emit D-Bus signal
 
2751
                        self.ClientRemoved(object_path, c.name)
3270
2752
                        return
3271
2753
                raise KeyError(object_path)
3272
2754
            
3273
2755
            del _interface
3274
 
            
3275
 
            @dbus.service.method(dbus.OBJECT_MANAGER_IFACE,
3276
 
                                 out_signature = "a{oa{sa{sv}}}")
3277
 
            def GetManagedObjects(self):
3278
 
                """D-Bus method"""
3279
 
                return dbus.Dictionary(
3280
 
                    { client.dbus_object_path:
3281
 
                      dbus.Dictionary(
3282
 
                          { interface: client.GetAll(interface)
3283
 
                            for interface in
3284
 
                                 client._get_all_interface_names()})
3285
 
                      for client in tcp_server.clients.values()})
3286
 
            
3287
 
            def client_added_signal(self, client):
3288
 
                """Send the new standard signal and the old signal"""
3289
 
                if use_dbus:
3290
 
                    # New standard signal
3291
 
                    self.InterfacesAdded(
3292
 
                        client.dbus_object_path,
3293
 
                        dbus.Dictionary(
3294
 
                            { interface: client.GetAll(interface)
3295
 
                              for interface in
3296
 
                              client._get_all_interface_names()}))
3297
 
                    # Old signal
3298
 
                    self.ClientAdded(client.dbus_object_path)
3299
 
            
3300
 
            def client_removed_signal(self, client):
3301
 
                """Send the new standard signal and the old signal"""
3302
 
                if use_dbus:
3303
 
                    # New standard signal
3304
 
                    self.InterfacesRemoved(
3305
 
                        client.dbus_object_path,
3306
 
                        client._get_all_interface_names())
3307
 
                    # Old signal
3308
 
                    self.ClientRemoved(client.dbus_object_path,
3309
 
                                       client.name)
3310
2756
        
3311
2757
        mandos_dbus_service = MandosDBusService()
3312
2758
    
3313
 
    # Save modules to variables to exempt the modules from being
3314
 
    # unloaded before the function registered with atexit() is run.
3315
 
    mp = multiprocessing
3316
 
    wn = wnull
3317
2759
    def cleanup():
3318
2760
        "Cleanup function; run on exit"
3319
2761
        if zeroconf:
3320
2762
            service.cleanup()
3321
2763
        
3322
 
        mp.active_children()
3323
 
        wn.close()
 
2764
        multiprocessing.active_children()
 
2765
        wnull.close()
3324
2766
        if not (tcp_server.clients or client_settings):
3325
2767
            return
3326
2768
        
3329
2771
        # removed/edited, old secret will thus be unrecovable.
3330
2772
        clients = {}
3331
2773
        with PGPEngine() as pgp:
3332
 
            for client in tcp_server.clients.values():
 
2774
            for client in tcp_server.clients.itervalues():
3333
2775
                key = client_settings[client.name]["secret"]
3334
2776
                client.encrypted_secret = pgp.encrypt(client.secret,
3335
2777
                                                      key)
3339
2781
                # + secret.
3340
2782
                exclude = { "bus", "changedstate", "secret",
3341
2783
                            "checker", "server_settings" }
3342
 
                for name, typ in inspect.getmembers(dbus.service
3343
 
                                                    .Object):
 
2784
                for name, typ in (inspect.getmembers
 
2785
                                  (dbus.service.Object)):
3344
2786
                    exclude.add(name)
3345
2787
                
3346
2788
                client_dict["encrypted_secret"] = (client
3353
2795
                del client_settings[client.name]["secret"]
3354
2796
        
3355
2797
        try:
3356
 
            with tempfile.NamedTemporaryFile(
3357
 
                    mode='wb',
3358
 
                    suffix=".pickle",
3359
 
                    prefix='clients-',
3360
 
                    dir=os.path.dirname(stored_state_path),
3361
 
                    delete=False) as stored_state:
3362
 
                pickle.dump((clients, client_settings), stored_state,
3363
 
                            protocol = 2)
3364
 
                tempname = stored_state.name
 
2798
            with (tempfile.NamedTemporaryFile
 
2799
                  (mode='wb', suffix=".pickle", prefix='clients-',
 
2800
                   dir=os.path.dirname(stored_state_path),
 
2801
                   delete=False)) as stored_state:
 
2802
                pickle.dump((clients, client_settings), stored_state)
 
2803
                tempname=stored_state.name
3365
2804
            os.rename(tempname, stored_state_path)
3366
2805
        except (IOError, OSError) as e:
3367
2806
            if not debug:
3382
2821
            name, client = tcp_server.clients.popitem()
3383
2822
            if use_dbus:
3384
2823
                client.remove_from_connection()
3385
 
            # Don't signal the disabling
 
2824
            # Don't signal anything except ClientRemoved
3386
2825
            client.disable(quiet=True)
3387
 
            # Emit D-Bus signal for removal
3388
2826
            if use_dbus:
3389
 
                mandos_dbus_service.client_removed_signal(client)
 
2827
                # Emit D-Bus signal
 
2828
                mandos_dbus_service.ClientRemoved(client
 
2829
                                                  .dbus_object_path,
 
2830
                                                  client.name)
3390
2831
        client_settings.clear()
3391
2832
    
3392
2833
    atexit.register(cleanup)
3393
2834
    
3394
 
    for client in tcp_server.clients.values():
 
2835
    for client in tcp_server.clients.itervalues():
3395
2836
        if use_dbus:
3396
 
            # Emit D-Bus signal for adding
3397
 
            mandos_dbus_service.client_added_signal(client)
 
2837
            # Emit D-Bus signal
 
2838
            mandos_dbus_service.ClientAdded(client.dbus_object_path)
3398
2839
        # Need to initiate checking of clients
3399
2840
        if client.enabled:
3400
2841
            client.init_checker()
3426
2867
                sys.exit(1)
3427
2868
            # End of Avahi example code
3428
2869
        
3429
 
        GLib.io_add_watch(tcp_server.fileno(), GLib.IO_IN,
3430
 
                          lambda *args, **kwargs:
3431
 
                          (tcp_server.handle_request
3432
 
                           (*args[2:], **kwargs) or True))
 
2870
        gobject.io_add_watch(tcp_server.fileno(), gobject.IO_IN,
 
2871
                             lambda *args, **kwargs:
 
2872
                             (tcp_server.handle_request
 
2873
                              (*args[2:], **kwargs) or True))
3433
2874
        
3434
2875
        logger.debug("Starting main loop")
3435
2876
        main_loop.run()
3445
2886
    # Must run before the D-Bus bus name gets deregistered
3446
2887
    cleanup()
3447
2888
 
3448
 
 
3449
2889
if __name__ == '__main__':
3450
2890
    main()