/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-08-02 16:57:09 UTC
  • Revision ID: teddy@recompile.se-20150802165709-k0vuxe3vjph3n5ss
Deprecate the D-Bus property "se.recompile.Mandos.Client.ObjectPath".

The D-Bus property "se.recompile.Mandos.Client.ObjectPath" is
unnecessary - is not used by mandos-monitor or mandos-ctl, and I
cannot see it being useful for anyone.

* DBUS-API (se.recompile.Mandos.Client.ObjectPath): Remove;
                                                    deprecated.
* mandos (ClientDBus.ObjectPath_dbus_property): Annotate as
                                                deprecated.

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.
5
 
#
 
5
6
6
# This program is partly derived from an example program for an Avahi
7
7
# service publisher, downloaded from
8
8
# <http://avahi.org/wiki/PythonPublishExample>.  This includes the
9
9
# methods "add", "remove", "server_state_changed",
10
10
# "entry_group_state_changed", "cleanup", and "activate" in the
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
16
 
#
 
14
# Copyright © 2008-2015 Teddy Hogeborn
 
15
# Copyright © 2008-2015 Björn Påhlsson
 
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
19
19
# the Free Software Foundation, either version 3 of the License, or
23
23
#     but WITHOUT ANY WARRANTY; without even the implied warranty of
24
24
#     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
25
25
#     GNU General Public License for more details.
26
 
#
 
26
27
27
# You should have received a copy of the GNU General Public License
28
28
# along with this program.  If not, see
29
29
# <http://www.gnu.org/licenses/>.
30
 
#
 
30
31
31
# Contact the authors at <mandos@recompile.se>.
32
 
#
 
32
33
33
 
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
39
try:
43
40
    import SocketServer as socketserver
47
44
import argparse
48
45
import datetime
49
46
import errno
 
47
import gnutls.crypto
 
48
import gnutls.connection
 
49
import gnutls.errors
 
50
import gnutls.library.functions
 
51
import gnutls.library.constants
 
52
import gnutls.library.types
50
53
try:
51
54
    import ConfigParser as configparser
52
55
except ImportError:
79
82
 
80
83
import dbus
81
84
import dbus.service
82
 
from gi.repository import GLib
 
85
try:
 
86
    import gobject
 
87
except ImportError:
 
88
    from gi.repository import GObject as gobject
 
89
import avahi
83
90
from dbus.mainloop.glib import DBusGMainLoop
84
91
import ctypes
85
92
import ctypes.util
86
93
import xml.dom.minidom
87
94
import inspect
88
95
 
89
 
# Try to find the value of SO_BINDTODEVICE:
90
96
try:
91
 
    # This is where SO_BINDTODEVICE is in Python 3.3 (or 3.4?) and
92
 
    # newer, and it is also the most natural place for it:
93
97
    SO_BINDTODEVICE = socket.SO_BINDTODEVICE
94
98
except AttributeError:
95
99
    try:
96
 
        # This is where SO_BINDTODEVICE was up to and including Python
97
 
        # 2.6, and also 3.2:
98
100
        from IN import SO_BINDTODEVICE
99
101
    except ImportError:
100
 
        # In Python 2.7 it seems to have been removed entirely.
101
 
        # Try running the C preprocessor:
102
 
        try:
103
 
            cc = subprocess.Popen(["cc", "--language=c", "-E",
104
 
                                   "/dev/stdin"],
105
 
                                  stdin=subprocess.PIPE,
106
 
                                  stdout=subprocess.PIPE)
107
 
            stdout = cc.communicate(
108
 
                "#include <sys/socket.h>\nSO_BINDTODEVICE\n")[0]
109
 
            SO_BINDTODEVICE = int(stdout.splitlines()[-1])
110
 
        except (OSError, ValueError, IndexError):
111
 
            # No value found
112
 
            SO_BINDTODEVICE = None
 
102
        SO_BINDTODEVICE = None
113
103
 
114
104
if sys.version_info.major == 2:
115
105
    str = unicode
116
106
 
117
 
version = "1.7.10"
 
107
version = "1.6.9"
118
108
stored_state_file = "clients.pickle"
119
109
 
120
110
logger = logging.getLogger()
124
114
    if_nametoindex = ctypes.cdll.LoadLibrary(
125
115
        ctypes.util.find_library("c")).if_nametoindex
126
116
except (OSError, AttributeError):
127
 
 
 
117
    
128
118
    def if_nametoindex(interface):
129
119
        "Get an interface index the hard way, i.e. using fcntl()"
130
120
        SIOCGIFINDEX = 0x8933  # From /usr/include/linux/sockios.h
135
125
        return interface_index
136
126
 
137
127
 
138
 
def copy_function(func):
139
 
    """Make a copy of a function"""
140
 
    if sys.version_info.major == 2:
141
 
        return types.FunctionType(func.func_code,
142
 
                                  func.func_globals,
143
 
                                  func.func_name,
144
 
                                  func.func_defaults,
145
 
                                  func.func_closure)
146
 
    else:
147
 
        return types.FunctionType(func.__code__,
148
 
                                  func.__globals__,
149
 
                                  func.__name__,
150
 
                                  func.__defaults__,
151
 
                                  func.__closure__)
152
 
 
153
 
 
154
128
def initlogger(debug, level=logging.WARNING):
155
129
    """init logger and add loglevel"""
156
 
 
 
130
    
157
131
    global syslogger
158
132
    syslogger = (logging.handlers.SysLogHandler(
159
 
        facility=logging.handlers.SysLogHandler.LOG_DAEMON,
160
 
        address="/dev/log"))
 
133
        facility = logging.handlers.SysLogHandler.LOG_DAEMON,
 
134
        address = "/dev/log"))
161
135
    syslogger.setFormatter(logging.Formatter
162
136
                           ('Mandos [%(process)d]: %(levelname)s:'
163
137
                            ' %(message)s'))
164
138
    logger.addHandler(syslogger)
165
 
 
 
139
    
166
140
    if debug:
167
141
        console = logging.StreamHandler()
168
142
        console.setFormatter(logging.Formatter('%(asctime)s %(name)s'
180
154
 
181
155
class PGPEngine(object):
182
156
    """A simple class for OpenPGP symmetric encryption & decryption"""
183
 
 
 
157
    
184
158
    def __init__(self):
185
159
        self.tempdir = tempfile.mkdtemp(prefix="mandos-")
186
 
        self.gpg = "gpg"
187
 
        try:
188
 
            output = subprocess.check_output(["gpgconf"])
189
 
            for line in output.splitlines():
190
 
                name, text, path = line.split(b":")
191
 
                if name == "gpg":
192
 
                    self.gpg = path
193
 
                    break
194
 
        except OSError as e:
195
 
            if e.errno != errno.ENOENT:
196
 
                raise
197
160
        self.gnupgargs = ['--batch',
198
 
                          '--homedir', self.tempdir,
 
161
                          '--home', self.tempdir,
199
162
                          '--force-mdc',
200
 
                          '--quiet']
201
 
        # Only GPG version 1 has the --no-use-agent option.
202
 
        if self.gpg == "gpg" or self.gpg.endswith("/gpg"):
203
 
            self.gnupgargs.append("--no-use-agent")
204
 
 
 
163
                          '--quiet',
 
164
                          '--no-use-agent']
 
165
    
205
166
    def __enter__(self):
206
167
        return self
207
 
 
 
168
    
208
169
    def __exit__(self, exc_type, exc_value, traceback):
209
170
        self._cleanup()
210
171
        return False
211
 
 
 
172
    
212
173
    def __del__(self):
213
174
        self._cleanup()
214
 
 
 
175
    
215
176
    def _cleanup(self):
216
177
        if self.tempdir is not None:
217
178
            # Delete contents of tempdir
218
179
            for root, dirs, files in os.walk(self.tempdir,
219
 
                                             topdown=False):
 
180
                                             topdown = False):
220
181
                for filename in files:
221
182
                    os.remove(os.path.join(root, filename))
222
183
                for dirname in dirs:
224
185
            # Remove tempdir
225
186
            os.rmdir(self.tempdir)
226
187
            self.tempdir = None
227
 
 
 
188
    
228
189
    def password_encode(self, password):
229
190
        # Passphrase can not be empty and can not contain newlines or
230
191
        # NUL bytes.  So we prefix it and hex encode it.
235
196
                       .replace(b"\n", b"\\n")
236
197
                       .replace(b"\0", b"\\x00"))
237
198
        return encoded
238
 
 
 
199
    
239
200
    def encrypt(self, data, password):
240
201
        passphrase = self.password_encode(password)
241
202
        with tempfile.NamedTemporaryFile(
242
203
                dir=self.tempdir) as passfile:
243
204
            passfile.write(passphrase)
244
205
            passfile.flush()
245
 
            proc = subprocess.Popen([self.gpg, '--symmetric',
 
206
            proc = subprocess.Popen(['gpg', '--symmetric',
246
207
                                     '--passphrase-file',
247
208
                                     passfile.name]
248
209
                                    + self.gnupgargs,
249
 
                                    stdin=subprocess.PIPE,
250
 
                                    stdout=subprocess.PIPE,
251
 
                                    stderr=subprocess.PIPE)
252
 
            ciphertext, err = proc.communicate(input=data)
 
210
                                    stdin = subprocess.PIPE,
 
211
                                    stdout = subprocess.PIPE,
 
212
                                    stderr = subprocess.PIPE)
 
213
            ciphertext, err = proc.communicate(input = data)
253
214
        if proc.returncode != 0:
254
215
            raise PGPError(err)
255
216
        return ciphertext
256
 
 
 
217
    
257
218
    def decrypt(self, data, password):
258
219
        passphrase = self.password_encode(password)
259
220
        with tempfile.NamedTemporaryFile(
260
 
                dir=self.tempdir) as passfile:
 
221
                dir = self.tempdir) as passfile:
261
222
            passfile.write(passphrase)
262
223
            passfile.flush()
263
 
            proc = subprocess.Popen([self.gpg, '--decrypt',
 
224
            proc = subprocess.Popen(['gpg', '--decrypt',
264
225
                                     '--passphrase-file',
265
226
                                     passfile.name]
266
227
                                    + self.gnupgargs,
267
 
                                    stdin=subprocess.PIPE,
268
 
                                    stdout=subprocess.PIPE,
269
 
                                    stderr=subprocess.PIPE)
270
 
            decrypted_plaintext, err = proc.communicate(input=data)
 
228
                                    stdin = subprocess.PIPE,
 
229
                                    stdout = subprocess.PIPE,
 
230
                                    stderr = subprocess.PIPE)
 
231
            decrypted_plaintext, err = proc.communicate(input = data)
271
232
        if proc.returncode != 0:
272
233
            raise PGPError(err)
273
234
        return decrypted_plaintext
274
235
 
275
236
 
276
 
# Pretend that we have an Avahi module
277
 
class Avahi(object):
278
 
    """This isn't so much a class as it is a module-like namespace.
279
 
    It is instantiated once, and simulates having an Avahi module."""
280
 
    IF_UNSPEC = -1               # avahi-common/address.h
281
 
    PROTO_UNSPEC = -1            # avahi-common/address.h
282
 
    PROTO_INET = 0               # avahi-common/address.h
283
 
    PROTO_INET6 = 1              # avahi-common/address.h
284
 
    DBUS_NAME = "org.freedesktop.Avahi"
285
 
    DBUS_INTERFACE_ENTRY_GROUP = DBUS_NAME + ".EntryGroup"
286
 
    DBUS_INTERFACE_SERVER = DBUS_NAME + ".Server"
287
 
    DBUS_PATH_SERVER = "/"
288
 
 
289
 
    def string_array_to_txt_array(self, t):
290
 
        return dbus.Array((dbus.ByteArray(s.encode("utf-8"))
291
 
                           for s in t), signature="ay")
292
 
    ENTRY_GROUP_ESTABLISHED = 2  # avahi-common/defs.h
293
 
    ENTRY_GROUP_COLLISION = 3    # avahi-common/defs.h
294
 
    ENTRY_GROUP_FAILURE = 4      # avahi-common/defs.h
295
 
    SERVER_INVALID = 0           # avahi-common/defs.h
296
 
    SERVER_REGISTERING = 1       # avahi-common/defs.h
297
 
    SERVER_RUNNING = 2           # avahi-common/defs.h
298
 
    SERVER_COLLISION = 3         # avahi-common/defs.h
299
 
    SERVER_FAILURE = 4           # avahi-common/defs.h
300
 
avahi = Avahi()
301
 
 
302
 
 
303
237
class AvahiError(Exception):
304
238
    def __init__(self, value, *args, **kwargs):
305
239
        self.value = value
317
251
 
318
252
class AvahiService(object):
319
253
    """An Avahi (Zeroconf) service.
320
 
 
 
254
    
321
255
    Attributes:
322
256
    interface: integer; avahi.IF_UNSPEC or an interface index.
323
257
               Used to optionally bind to the specified interface.
335
269
    server: D-Bus Server
336
270
    bus: dbus.SystemBus()
337
271
    """
338
 
 
 
272
    
339
273
    def __init__(self,
340
 
                 interface=avahi.IF_UNSPEC,
341
 
                 name=None,
342
 
                 servicetype=None,
343
 
                 port=None,
344
 
                 TXT=None,
345
 
                 domain="",
346
 
                 host="",
347
 
                 max_renames=32768,
348
 
                 protocol=avahi.PROTO_UNSPEC,
349
 
                 bus=None):
 
274
                 interface = avahi.IF_UNSPEC,
 
275
                 name = None,
 
276
                 servicetype = None,
 
277
                 port = None,
 
278
                 TXT = None,
 
279
                 domain = "",
 
280
                 host = "",
 
281
                 max_renames = 32768,
 
282
                 protocol = avahi.PROTO_UNSPEC,
 
283
                 bus = None):
350
284
        self.interface = interface
351
285
        self.name = name
352
286
        self.type = servicetype
361
295
        self.server = None
362
296
        self.bus = bus
363
297
        self.entry_group_state_changed_match = None
364
 
 
 
298
    
365
299
    def rename(self, remove=True):
366
300
        """Derived from the Avahi example code"""
367
301
        if self.rename_count >= self.max_renames:
387
321
                logger.critical("D-Bus Exception", exc_info=error)
388
322
                self.cleanup()
389
323
                os._exit(1)
390
 
 
 
324
    
391
325
    def remove(self):
392
326
        """Derived from the Avahi example code"""
393
327
        if self.entry_group_state_changed_match is not None:
395
329
            self.entry_group_state_changed_match = None
396
330
        if self.group is not None:
397
331
            self.group.Reset()
398
 
 
 
332
    
399
333
    def add(self):
400
334
        """Derived from the Avahi example code"""
401
335
        self.remove()
418
352
            dbus.UInt16(self.port),
419
353
            avahi.string_array_to_txt_array(self.TXT))
420
354
        self.group.Commit()
421
 
 
 
355
    
422
356
    def entry_group_state_changed(self, state, error):
423
357
        """Derived from the Avahi example code"""
424
358
        logger.debug("Avahi entry group state change: %i", state)
425
 
 
 
359
        
426
360
        if state == avahi.ENTRY_GROUP_ESTABLISHED:
427
361
            logger.debug("Zeroconf service established.")
428
362
        elif state == avahi.ENTRY_GROUP_COLLISION:
432
366
            logger.critical("Avahi: Error in group state changed %s",
433
367
                            str(error))
434
368
            raise AvahiGroupError("State changed: {!s}".format(error))
435
 
 
 
369
    
436
370
    def cleanup(self):
437
371
        """Derived from the Avahi example code"""
438
372
        if self.group is not None:
443
377
                pass
444
378
            self.group = None
445
379
        self.remove()
446
 
 
 
380
    
447
381
    def server_state_changed(self, state, error=None):
448
382
        """Derived from the Avahi example code"""
449
383
        logger.debug("Avahi server state change: %i", state)
478
412
                logger.debug("Unknown state: %r", state)
479
413
            else:
480
414
                logger.debug("Unknown state: %r: %r", state, error)
481
 
 
 
415
    
482
416
    def activate(self):
483
417
        """Derived from the Avahi example code"""
484
418
        if self.server is None:
501
435
            .format(self.name)))
502
436
        return ret
503
437
 
504
 
 
505
 
# Pretend that we have a GnuTLS module
506
 
class GnuTLS(object):
507
 
    """This isn't so much a class as it is a module-like namespace.
508
 
    It is instantiated once, and simulates having a GnuTLS module."""
509
 
 
510
 
    _library = ctypes.cdll.LoadLibrary(
511
 
        ctypes.util.find_library("gnutls"))
512
 
    _need_version = b"3.3.0"
513
 
 
514
 
    def __init__(self):
515
 
        # Need to use class name "GnuTLS" here, since this method is
516
 
        # called before the assignment to the "gnutls" global variable
517
 
        # happens.
518
 
        if GnuTLS.check_version(self._need_version) is None:
519
 
            raise GnuTLS.Error("Needs GnuTLS {} or later"
520
 
                               .format(self._need_version))
521
 
 
522
 
    # Unless otherwise indicated, the constants and types below are
523
 
    # all from the gnutls/gnutls.h C header file.
524
 
 
525
 
    # Constants
526
 
    E_SUCCESS = 0
527
 
    E_INTERRUPTED = -52
528
 
    E_AGAIN = -28
529
 
    CRT_OPENPGP = 2
530
 
    CLIENT = 2
531
 
    SHUT_RDWR = 0
532
 
    CRD_CERTIFICATE = 1
533
 
    E_NO_CERTIFICATE_FOUND = -49
534
 
    OPENPGP_FMT_RAW = 0         # gnutls/openpgp.h
535
 
 
536
 
    # Types
537
 
    class session_int(ctypes.Structure):
538
 
        _fields_ = []
539
 
    session_t = ctypes.POINTER(session_int)
540
 
 
541
 
    class certificate_credentials_st(ctypes.Structure):
542
 
        _fields_ = []
543
 
    certificate_credentials_t = ctypes.POINTER(
544
 
        certificate_credentials_st)
545
 
    certificate_type_t = ctypes.c_int
546
 
 
547
 
    class datum_t(ctypes.Structure):
548
 
        _fields_ = [('data', ctypes.POINTER(ctypes.c_ubyte)),
549
 
                    ('size', ctypes.c_uint)]
550
 
 
551
 
    class openpgp_crt_int(ctypes.Structure):
552
 
        _fields_ = []
553
 
    openpgp_crt_t = ctypes.POINTER(openpgp_crt_int)
554
 
    openpgp_crt_fmt_t = ctypes.c_int  # gnutls/openpgp.h
555
 
    log_func = ctypes.CFUNCTYPE(None, ctypes.c_int, ctypes.c_char_p)
556
 
    credentials_type_t = ctypes.c_int
557
 
    transport_ptr_t = ctypes.c_void_p
558
 
    close_request_t = ctypes.c_int
559
 
 
560
 
    # Exceptions
561
 
    class Error(Exception):
562
 
        # We need to use the class name "GnuTLS" here, since this
563
 
        # exception might be raised from within GnuTLS.__init__,
564
 
        # which is called before the assignment to the "gnutls"
565
 
        # global variable has happened.
566
 
        def __init__(self, message=None, code=None, args=()):
567
 
            # Default usage is by a message string, but if a return
568
 
            # code is passed, convert it to a string with
569
 
            # gnutls.strerror()
570
 
            self.code = code
571
 
            if message is None and code is not None:
572
 
                message = GnuTLS.strerror(code)
573
 
            return super(GnuTLS.Error, self).__init__(
574
 
                message, *args)
575
 
 
576
 
    class CertificateSecurityError(Error):
577
 
        pass
578
 
 
579
 
    # Classes
580
 
    class Credentials(object):
581
 
        def __init__(self):
582
 
            self._c_object = gnutls.certificate_credentials_t()
583
 
            gnutls.certificate_allocate_credentials(
584
 
                ctypes.byref(self._c_object))
585
 
            self.type = gnutls.CRD_CERTIFICATE
586
 
 
587
 
        def __del__(self):
588
 
            gnutls.certificate_free_credentials(self._c_object)
589
 
 
590
 
    class ClientSession(object):
591
 
        def __init__(self, socket, credentials=None):
592
 
            self._c_object = gnutls.session_t()
593
 
            gnutls.init(ctypes.byref(self._c_object), gnutls.CLIENT)
594
 
            gnutls.set_default_priority(self._c_object)
595
 
            gnutls.transport_set_ptr(self._c_object, socket.fileno())
596
 
            gnutls.handshake_set_private_extensions(self._c_object,
597
 
                                                    True)
598
 
            self.socket = socket
599
 
            if credentials is None:
600
 
                credentials = gnutls.Credentials()
601
 
            gnutls.credentials_set(self._c_object, credentials.type,
602
 
                                   ctypes.cast(credentials._c_object,
603
 
                                               ctypes.c_void_p))
604
 
            self.credentials = credentials
605
 
 
606
 
        def __del__(self):
607
 
            gnutls.deinit(self._c_object)
608
 
 
609
 
        def handshake(self):
610
 
            return gnutls.handshake(self._c_object)
611
 
 
612
 
        def send(self, data):
613
 
            data = bytes(data)
614
 
            data_len = len(data)
615
 
            while data_len > 0:
616
 
                data_len -= gnutls.record_send(self._c_object,
617
 
                                               data[-data_len:],
618
 
                                               data_len)
619
 
 
620
 
        def bye(self):
621
 
            return gnutls.bye(self._c_object, gnutls.SHUT_RDWR)
622
 
 
623
 
    # Error handling functions
624
 
    def _error_code(result):
625
 
        """A function to raise exceptions on errors, suitable
626
 
        for the 'restype' attribute on ctypes functions"""
627
 
        if result >= 0:
628
 
            return result
629
 
        if result == gnutls.E_NO_CERTIFICATE_FOUND:
630
 
            raise gnutls.CertificateSecurityError(code=result)
631
 
        raise gnutls.Error(code=result)
632
 
 
633
 
    def _retry_on_error(result, func, arguments):
634
 
        """A function to retry on some errors, suitable
635
 
        for the 'errcheck' attribute on ctypes functions"""
636
 
        while result < 0:
637
 
            if result not in (gnutls.E_INTERRUPTED, gnutls.E_AGAIN):
638
 
                return _error_code(result)
639
 
            result = func(*arguments)
640
 
        return result
641
 
 
642
 
    # Unless otherwise indicated, the function declarations below are
643
 
    # all from the gnutls/gnutls.h C header file.
644
 
 
645
 
    # Functions
646
 
    priority_set_direct = _library.gnutls_priority_set_direct
647
 
    priority_set_direct.argtypes = [session_t, ctypes.c_char_p,
648
 
                                    ctypes.POINTER(ctypes.c_char_p)]
649
 
    priority_set_direct.restype = _error_code
650
 
 
651
 
    init = _library.gnutls_init
652
 
    init.argtypes = [ctypes.POINTER(session_t), ctypes.c_int]
653
 
    init.restype = _error_code
654
 
 
655
 
    set_default_priority = _library.gnutls_set_default_priority
656
 
    set_default_priority.argtypes = [session_t]
657
 
    set_default_priority.restype = _error_code
658
 
 
659
 
    record_send = _library.gnutls_record_send
660
 
    record_send.argtypes = [session_t, ctypes.c_void_p,
661
 
                            ctypes.c_size_t]
662
 
    record_send.restype = ctypes.c_ssize_t
663
 
    record_send.errcheck = _retry_on_error
664
 
 
665
 
    certificate_allocate_credentials = (
666
 
        _library.gnutls_certificate_allocate_credentials)
667
 
    certificate_allocate_credentials.argtypes = [
668
 
        ctypes.POINTER(certificate_credentials_t)]
669
 
    certificate_allocate_credentials.restype = _error_code
670
 
 
671
 
    certificate_free_credentials = (
672
 
        _library.gnutls_certificate_free_credentials)
673
 
    certificate_free_credentials.argtypes = [
674
 
        certificate_credentials_t]
675
 
    certificate_free_credentials.restype = None
676
 
 
677
 
    handshake_set_private_extensions = (
678
 
        _library.gnutls_handshake_set_private_extensions)
679
 
    handshake_set_private_extensions.argtypes = [session_t,
680
 
                                                 ctypes.c_int]
681
 
    handshake_set_private_extensions.restype = None
682
 
 
683
 
    credentials_set = _library.gnutls_credentials_set
684
 
    credentials_set.argtypes = [session_t, credentials_type_t,
685
 
                                ctypes.c_void_p]
686
 
    credentials_set.restype = _error_code
687
 
 
688
 
    strerror = _library.gnutls_strerror
689
 
    strerror.argtypes = [ctypes.c_int]
690
 
    strerror.restype = ctypes.c_char_p
691
 
 
692
 
    certificate_type_get = _library.gnutls_certificate_type_get
693
 
    certificate_type_get.argtypes = [session_t]
694
 
    certificate_type_get.restype = _error_code
695
 
 
696
 
    certificate_get_peers = _library.gnutls_certificate_get_peers
697
 
    certificate_get_peers.argtypes = [session_t,
698
 
                                      ctypes.POINTER(ctypes.c_uint)]
699
 
    certificate_get_peers.restype = ctypes.POINTER(datum_t)
700
 
 
701
 
    global_set_log_level = _library.gnutls_global_set_log_level
702
 
    global_set_log_level.argtypes = [ctypes.c_int]
703
 
    global_set_log_level.restype = None
704
 
 
705
 
    global_set_log_function = _library.gnutls_global_set_log_function
706
 
    global_set_log_function.argtypes = [log_func]
707
 
    global_set_log_function.restype = None
708
 
 
709
 
    deinit = _library.gnutls_deinit
710
 
    deinit.argtypes = [session_t]
711
 
    deinit.restype = None
712
 
 
713
 
    handshake = _library.gnutls_handshake
714
 
    handshake.argtypes = [session_t]
715
 
    handshake.restype = _error_code
716
 
    handshake.errcheck = _retry_on_error
717
 
 
718
 
    transport_set_ptr = _library.gnutls_transport_set_ptr
719
 
    transport_set_ptr.argtypes = [session_t, transport_ptr_t]
720
 
    transport_set_ptr.restype = None
721
 
 
722
 
    bye = _library.gnutls_bye
723
 
    bye.argtypes = [session_t, close_request_t]
724
 
    bye.restype = _error_code
725
 
    bye.errcheck = _retry_on_error
726
 
 
727
 
    check_version = _library.gnutls_check_version
728
 
    check_version.argtypes = [ctypes.c_char_p]
729
 
    check_version.restype = ctypes.c_char_p
730
 
 
731
 
    # All the function declarations below are from gnutls/openpgp.h
732
 
 
733
 
    openpgp_crt_init = _library.gnutls_openpgp_crt_init
734
 
    openpgp_crt_init.argtypes = [ctypes.POINTER(openpgp_crt_t)]
735
 
    openpgp_crt_init.restype = _error_code
736
 
 
737
 
    openpgp_crt_import = _library.gnutls_openpgp_crt_import
738
 
    openpgp_crt_import.argtypes = [openpgp_crt_t,
739
 
                                   ctypes.POINTER(datum_t),
740
 
                                   openpgp_crt_fmt_t]
741
 
    openpgp_crt_import.restype = _error_code
742
 
 
743
 
    openpgp_crt_verify_self = _library.gnutls_openpgp_crt_verify_self
744
 
    openpgp_crt_verify_self.argtypes = [openpgp_crt_t, ctypes.c_uint,
745
 
                                        ctypes.POINTER(ctypes.c_uint)]
746
 
    openpgp_crt_verify_self.restype = _error_code
747
 
 
748
 
    openpgp_crt_deinit = _library.gnutls_openpgp_crt_deinit
749
 
    openpgp_crt_deinit.argtypes = [openpgp_crt_t]
750
 
    openpgp_crt_deinit.restype = None
751
 
 
752
 
    openpgp_crt_get_fingerprint = (
753
 
        _library.gnutls_openpgp_crt_get_fingerprint)
754
 
    openpgp_crt_get_fingerprint.argtypes = [openpgp_crt_t,
755
 
                                            ctypes.c_void_p,
756
 
                                            ctypes.POINTER(
757
 
                                                ctypes.c_size_t)]
758
 
    openpgp_crt_get_fingerprint.restype = _error_code
759
 
 
760
 
    # Remove non-public functions
761
 
    del _error_code, _retry_on_error
762
 
# Create the global "gnutls" object, simulating a module
763
 
gnutls = GnuTLS()
764
 
 
765
 
 
766
438
def call_pipe(connection,       # : multiprocessing.Connection
767
439
              func, *args, **kwargs):
768
440
    """This function is meant to be called by multiprocessing.Process
769
 
 
 
441
    
770
442
    This function runs func(*args, **kwargs), and writes the resulting
771
443
    return value on the provided multiprocessing.Connection.
772
444
    """
773
445
    connection.send(func(*args, **kwargs))
774
446
    connection.close()
775
447
 
776
 
 
777
448
class Client(object):
778
449
    """A representation of a client host served by this server.
779
 
 
 
450
    
780
451
    Attributes:
781
452
    approved:   bool(); 'None' if not yet approved/disapproved
782
453
    approval_delay: datetime.timedelta(); Time to wait for approval
784
455
    checker:    subprocess.Popen(); a running checker process used
785
456
                                    to see if the client lives.
786
457
                                    'None' if no process is running.
787
 
    checker_callback_tag: a GLib event source tag, or None
 
458
    checker_callback_tag: a gobject event source tag, or None
788
459
    checker_command: string; External command which is run to check
789
460
                     if client lives.  %() expansions are done at
790
461
                     runtime with vars(self) as dict, so that for
791
462
                     instance %(name)s can be used in the command.
792
 
    checker_initiator_tag: a GLib event source tag, or None
 
463
    checker_initiator_tag: a gobject event source tag, or None
793
464
    created:    datetime.datetime(); (UTC) object creation
794
465
    client_structure: Object describing what attributes a client has
795
466
                      and is used for storing the client at exit
796
467
    current_checker_command: string; current running checker_command
797
 
    disable_initiator_tag: a GLib event source tag, or None
 
468
    disable_initiator_tag: a gobject event source tag, or None
798
469
    enabled:    bool()
799
470
    fingerprint: string (40 or 32 hexadecimal digits); used to
800
471
                 uniquely identify the client
819
490
                disabled, or None
820
491
    server_settings: The server_settings dict from main()
821
492
    """
822
 
 
 
493
    
823
494
    runtime_expansions = ("approval_delay", "approval_duration",
824
495
                          "created", "enabled", "expires",
825
496
                          "fingerprint", "host", "interval",
836
507
        "approved_by_default": "True",
837
508
        "enabled": "True",
838
509
    }
839
 
 
 
510
    
840
511
    @staticmethod
841
512
    def config_parser(config):
842
513
        """Construct a new dict of client settings of this form:
849
520
        for client_name in config.sections():
850
521
            section = dict(config.items(client_name))
851
522
            client = settings[client_name] = {}
852
 
 
 
523
            
853
524
            client["host"] = section["host"]
854
525
            # Reformat values from string types to Python types
855
526
            client["approved_by_default"] = config.getboolean(
856
527
                client_name, "approved_by_default")
857
528
            client["enabled"] = config.getboolean(client_name,
858
529
                                                  "enabled")
859
 
 
 
530
            
860
531
            # Uppercase and remove spaces from fingerprint for later
861
532
            # comparison purposes with return value from the
862
533
            # fingerprint() function
863
534
            client["fingerprint"] = (section["fingerprint"].upper()
864
535
                                     .replace(" ", ""))
865
536
            if "secret" in section:
866
 
                client["secret"] = codecs.decode(section["secret"]
867
 
                                                 .encode("utf-8"),
868
 
                                                 "base64")
 
537
                client["secret"] = section["secret"].decode("base64")
869
538
            elif "secfile" in section:
870
539
                with open(os.path.expanduser(os.path.expandvars
871
540
                                             (section["secfile"])),
886
555
            client["last_approval_request"] = None
887
556
            client["last_checked_ok"] = None
888
557
            client["last_checker_status"] = -2
889
 
 
 
558
        
890
559
        return settings
891
 
 
892
 
    def __init__(self, settings, name=None, server_settings=None):
 
560
    
 
561
    def __init__(self, settings, name = None, server_settings=None):
893
562
        self.name = name
894
563
        if server_settings is None:
895
564
            server_settings = {}
897
566
        # adding all client settings
898
567
        for setting, value in settings.items():
899
568
            setattr(self, setting, value)
900
 
 
 
569
        
901
570
        if self.enabled:
902
571
            if not hasattr(self, "last_enabled"):
903
572
                self.last_enabled = datetime.datetime.utcnow()
907
576
        else:
908
577
            self.last_enabled = None
909
578
            self.expires = None
910
 
 
 
579
        
911
580
        logger.debug("Creating client %r", self.name)
912
581
        logger.debug("  Fingerprint: %s", self.fingerprint)
913
582
        self.created = settings.get("created",
914
583
                                    datetime.datetime.utcnow())
915
 
 
 
584
        
916
585
        # attributes specific for this server instance
917
586
        self.checker = None
918
587
        self.checker_initiator_tag = None
924
593
        self.changedstate = multiprocessing_manager.Condition(
925
594
            multiprocessing_manager.Lock())
926
595
        self.client_structure = [attr
927
 
                                 for attr in self.__dict__.keys()
 
596
                                 for attr in self.__dict__.iterkeys()
928
597
                                 if not attr.startswith("_")]
929
598
        self.client_structure.append("client_structure")
930
 
 
 
599
        
931
600
        for name, t in inspect.getmembers(
932
601
                type(self), lambda obj: isinstance(obj, property)):
933
602
            if not name.startswith("_"):
934
603
                self.client_structure.append(name)
935
 
 
 
604
    
936
605
    # Send notice to process children that client state has changed
937
606
    def send_changedstate(self):
938
607
        with self.changedstate:
939
608
            self.changedstate.notify_all()
940
 
 
 
609
    
941
610
    def enable(self):
942
611
        """Start this client's checker and timeout hooks"""
943
612
        if getattr(self, "enabled", False):
948
617
        self.last_enabled = datetime.datetime.utcnow()
949
618
        self.init_checker()
950
619
        self.send_changedstate()
951
 
 
 
620
    
952
621
    def disable(self, quiet=True):
953
622
        """Disable this client."""
954
623
        if not getattr(self, "enabled", False):
956
625
        if not quiet:
957
626
            logger.info("Disabling client %s", self.name)
958
627
        if getattr(self, "disable_initiator_tag", None) is not None:
959
 
            GLib.source_remove(self.disable_initiator_tag)
 
628
            gobject.source_remove(self.disable_initiator_tag)
960
629
            self.disable_initiator_tag = None
961
630
        self.expires = None
962
631
        if getattr(self, "checker_initiator_tag", None) is not None:
963
 
            GLib.source_remove(self.checker_initiator_tag)
 
632
            gobject.source_remove(self.checker_initiator_tag)
964
633
            self.checker_initiator_tag = None
965
634
        self.stop_checker()
966
635
        self.enabled = False
967
636
        if not quiet:
968
637
            self.send_changedstate()
969
 
        # Do not run this again if called by a GLib.timeout_add
 
638
        # Do not run this again if called by a gobject.timeout_add
970
639
        return False
971
 
 
 
640
    
972
641
    def __del__(self):
973
642
        self.disable()
974
 
 
 
643
    
975
644
    def init_checker(self):
976
645
        # Schedule a new checker to be started an 'interval' from now,
977
646
        # and every interval from then on.
978
647
        if self.checker_initiator_tag is not None:
979
 
            GLib.source_remove(self.checker_initiator_tag)
980
 
        self.checker_initiator_tag = GLib.timeout_add(
 
648
            gobject.source_remove(self.checker_initiator_tag)
 
649
        self.checker_initiator_tag = gobject.timeout_add(
981
650
            int(self.interval.total_seconds() * 1000),
982
651
            self.start_checker)
983
652
        # Schedule a disable() when 'timeout' has passed
984
653
        if self.disable_initiator_tag is not None:
985
 
            GLib.source_remove(self.disable_initiator_tag)
986
 
        self.disable_initiator_tag = GLib.timeout_add(
 
654
            gobject.source_remove(self.disable_initiator_tag)
 
655
        self.disable_initiator_tag = gobject.timeout_add(
987
656
            int(self.timeout.total_seconds() * 1000), self.disable)
988
657
        # Also start a new checker *right now*.
989
658
        self.start_checker()
990
 
 
 
659
    
991
660
    def checker_callback(self, source, condition, connection,
992
661
                         command):
993
662
        """The checker has completed, so take appropriate actions."""
996
665
        # Read return code from connection (see call_pipe)
997
666
        returncode = connection.recv()
998
667
        connection.close()
999
 
 
 
668
        
1000
669
        if returncode >= 0:
1001
670
            self.last_checker_status = returncode
1002
671
            self.last_checker_signal = None
1012
681
            logger.warning("Checker for %(name)s crashed?",
1013
682
                           vars(self))
1014
683
        return False
1015
 
 
 
684
    
1016
685
    def checked_ok(self):
1017
686
        """Assert that the client has been seen, alive and well."""
1018
687
        self.last_checked_ok = datetime.datetime.utcnow()
1019
688
        self.last_checker_status = 0
1020
689
        self.last_checker_signal = None
1021
690
        self.bump_timeout()
1022
 
 
 
691
    
1023
692
    def bump_timeout(self, timeout=None):
1024
693
        """Bump up the timeout for this client."""
1025
694
        if timeout is None:
1026
695
            timeout = self.timeout
1027
696
        if self.disable_initiator_tag is not None:
1028
 
            GLib.source_remove(self.disable_initiator_tag)
 
697
            gobject.source_remove(self.disable_initiator_tag)
1029
698
            self.disable_initiator_tag = None
1030
699
        if getattr(self, "enabled", False):
1031
 
            self.disable_initiator_tag = GLib.timeout_add(
 
700
            self.disable_initiator_tag = gobject.timeout_add(
1032
701
                int(timeout.total_seconds() * 1000), self.disable)
1033
702
            self.expires = datetime.datetime.utcnow() + timeout
1034
 
 
 
703
    
1035
704
    def need_approval(self):
1036
705
        self.last_approval_request = datetime.datetime.utcnow()
1037
 
 
 
706
    
1038
707
    def start_checker(self):
1039
708
        """Start a new checker subprocess if one is not running.
1040
 
 
 
709
        
1041
710
        If a checker already exists, leave it running and do
1042
711
        nothing."""
1043
712
        # The reason for not killing a running checker is that if we
1048
717
        # checkers alone, the checker would have to take more time
1049
718
        # than 'timeout' for the client to be disabled, which is as it
1050
719
        # should be.
1051
 
 
 
720
        
1052
721
        if self.checker is not None and not self.checker.is_alive():
1053
722
            logger.warning("Checker was not alive; joining")
1054
723
            self.checker.join()
1058
727
            # Escape attributes for the shell
1059
728
            escaped_attrs = {
1060
729
                attr: re.escape(str(getattr(self, attr)))
1061
 
                for attr in self.runtime_expansions}
 
730
                for attr in self.runtime_expansions }
1062
731
            try:
1063
732
                command = self.checker_command % escaped_attrs
1064
733
            except TypeError as error:
1076
745
            # The exception is when not debugging but nevertheless
1077
746
            # running in the foreground; use the previously
1078
747
            # created wnull.
1079
 
            popen_args = {"close_fds": True,
1080
 
                          "shell": True,
1081
 
                          "cwd": "/"}
 
748
            popen_args = { "close_fds": True,
 
749
                           "shell": True,
 
750
                           "cwd": "/" }
1082
751
            if (not self.server_settings["debug"]
1083
752
                and self.server_settings["foreground"]):
1084
753
                popen_args.update({"stdout": wnull,
1085
 
                                   "stderr": wnull})
1086
 
            pipe = multiprocessing.Pipe(duplex=False)
 
754
                                   "stderr": wnull })
 
755
            pipe = multiprocessing.Pipe(duplex = False)
1087
756
            self.checker = multiprocessing.Process(
1088
 
                target=call_pipe,
1089
 
                args=(pipe[1], subprocess.call, command),
1090
 
                kwargs=popen_args)
 
757
                target = call_pipe,
 
758
                args = (pipe[1], subprocess.call, command),
 
759
                kwargs = popen_args)
1091
760
            self.checker.start()
1092
 
            self.checker_callback_tag = GLib.io_add_watch(
1093
 
                pipe[0].fileno(), GLib.IO_IN,
 
761
            self.checker_callback_tag = gobject.io_add_watch(
 
762
                pipe[0].fileno(), gobject.IO_IN,
1094
763
                self.checker_callback, pipe[0], command)
1095
 
        # Re-run this periodically if run by GLib.timeout_add
 
764
        # Re-run this periodically if run by gobject.timeout_add
1096
765
        return True
1097
 
 
 
766
    
1098
767
    def stop_checker(self):
1099
768
        """Force the checker process, if any, to stop."""
1100
769
        if self.checker_callback_tag:
1101
 
            GLib.source_remove(self.checker_callback_tag)
 
770
            gobject.source_remove(self.checker_callback_tag)
1102
771
            self.checker_callback_tag = None
1103
772
        if getattr(self, "checker", None) is None:
1104
773
            return
1113
782
                          byte_arrays=False):
1114
783
    """Decorators for marking methods of a DBusObjectWithProperties to
1115
784
    become properties on the D-Bus.
1116
 
 
 
785
    
1117
786
    The decorated method will be called with no arguments by "Get"
1118
787
    and with one argument by "Set".
1119
 
 
 
788
    
1120
789
    The parameters, where they are supported, are the same as
1121
790
    dbus.service.method, except there is only "signature", since the
1122
791
    type from Get() and the type sent to Set() is the same.
1126
795
    if byte_arrays and signature != "ay":
1127
796
        raise ValueError("Byte arrays not supported for non-'ay'"
1128
797
                         " signature {!r}".format(signature))
1129
 
 
 
798
    
1130
799
    def decorator(func):
1131
800
        func._dbus_is_property = True
1132
801
        func._dbus_interface = dbus_interface
1135
804
        func._dbus_name = func.__name__
1136
805
        if func._dbus_name.endswith("_dbus_property"):
1137
806
            func._dbus_name = func._dbus_name[:-14]
1138
 
        func._dbus_get_args_options = {'byte_arrays': byte_arrays}
 
807
        func._dbus_get_args_options = {'byte_arrays': byte_arrays }
1139
808
        return func
1140
 
 
 
809
    
1141
810
    return decorator
1142
811
 
1143
812
 
1144
813
def dbus_interface_annotations(dbus_interface):
1145
814
    """Decorator for marking functions returning interface annotations
1146
 
 
 
815
    
1147
816
    Usage:
1148
 
 
 
817
    
1149
818
    @dbus_interface_annotations("org.example.Interface")
1150
819
    def _foo(self):  # Function name does not matter
1151
820
        return {"org.freedesktop.DBus.Deprecated": "true",
1152
821
                "org.freedesktop.DBus.Property.EmitsChangedSignal":
1153
822
                    "false"}
1154
823
    """
1155
 
 
 
824
    
1156
825
    def decorator(func):
1157
826
        func._dbus_is_interface = True
1158
827
        func._dbus_interface = dbus_interface
1159
828
        func._dbus_name = dbus_interface
1160
829
        return func
1161
 
 
 
830
    
1162
831
    return decorator
1163
832
 
1164
833
 
1165
834
def dbus_annotations(annotations):
1166
835
    """Decorator to annotate D-Bus methods, signals or properties
1167
836
    Usage:
1168
 
 
 
837
    
1169
838
    @dbus_annotations({"org.freedesktop.DBus.Deprecated": "true",
1170
839
                       "org.freedesktop.DBus.Property."
1171
840
                       "EmitsChangedSignal": "false"})
1173
842
                           access="r")
1174
843
    def Property_dbus_property(self):
1175
844
        return dbus.Boolean(False)
1176
 
 
1177
 
    See also the DBusObjectWithAnnotations class.
1178
845
    """
1179
 
 
 
846
    
1180
847
    def decorator(func):
1181
848
        func._dbus_annotations = annotations
1182
849
        return func
1183
 
 
 
850
    
1184
851
    return decorator
1185
852
 
1186
853
 
1202
869
    pass
1203
870
 
1204
871
 
1205
 
class DBusObjectWithAnnotations(dbus.service.Object):
1206
 
    """A D-Bus object with annotations.
1207
 
 
1208
 
    Classes inheriting from this can use the dbus_annotations
1209
 
    decorator to add annotations to methods or signals.
 
872
class DBusObjectWithProperties(dbus.service.Object):
 
873
    """A D-Bus object with properties.
 
874
    
 
875
    Classes inheriting from this can use the dbus_service_property
 
876
    decorator to expose methods as D-Bus properties.  It exposes the
 
877
    standard Get(), Set(), and GetAll() methods on the D-Bus.
1210
878
    """
1211
 
 
 
879
    
1212
880
    @staticmethod
1213
881
    def _is_dbus_thing(thing):
1214
882
        """Returns a function testing if an attribute is a D-Bus thing
1215
 
 
 
883
        
1216
884
        If called like _is_dbus_thing("method") it returns a function
1217
885
        suitable for use as predicate to inspect.getmembers().
1218
886
        """
1219
887
        return lambda obj: getattr(obj, "_dbus_is_{}".format(thing),
1220
888
                                   False)
1221
 
 
 
889
    
1222
890
    def _get_all_dbus_things(self, thing):
1223
891
        """Returns a generator of (name, attribute) pairs
1224
892
        """
1227
895
                for cls in self.__class__.__mro__
1228
896
                for name, athing in
1229
897
                inspect.getmembers(cls, self._is_dbus_thing(thing)))
1230
 
 
1231
 
    @dbus.service.method(dbus.INTROSPECTABLE_IFACE,
1232
 
                         out_signature="s",
1233
 
                         path_keyword='object_path',
1234
 
                         connection_keyword='connection')
1235
 
    def Introspect(self, object_path, connection):
1236
 
        """Overloading of standard D-Bus method.
1237
 
 
1238
 
        Inserts annotation tags on methods and signals.
1239
 
        """
1240
 
        xmlstring = dbus.service.Object.Introspect(self, object_path,
1241
 
                                                   connection)
1242
 
        try:
1243
 
            document = xml.dom.minidom.parseString(xmlstring)
1244
 
 
1245
 
            for if_tag in document.getElementsByTagName("interface"):
1246
 
                # Add annotation tags
1247
 
                for typ in ("method", "signal"):
1248
 
                    for tag in if_tag.getElementsByTagName(typ):
1249
 
                        annots = dict()
1250
 
                        for name, prop in (self.
1251
 
                                           _get_all_dbus_things(typ)):
1252
 
                            if (name == tag.getAttribute("name")
1253
 
                                and prop._dbus_interface
1254
 
                                == if_tag.getAttribute("name")):
1255
 
                                annots.update(getattr(
1256
 
                                    prop, "_dbus_annotations", {}))
1257
 
                        for name, value in annots.items():
1258
 
                            ann_tag = document.createElement(
1259
 
                                "annotation")
1260
 
                            ann_tag.setAttribute("name", name)
1261
 
                            ann_tag.setAttribute("value", value)
1262
 
                            tag.appendChild(ann_tag)
1263
 
                # Add interface annotation tags
1264
 
                for annotation, value in dict(
1265
 
                    itertools.chain.from_iterable(
1266
 
                        annotations().items()
1267
 
                        for name, annotations
1268
 
                        in self._get_all_dbus_things("interface")
1269
 
                        if name == if_tag.getAttribute("name")
1270
 
                        )).items():
1271
 
                    ann_tag = document.createElement("annotation")
1272
 
                    ann_tag.setAttribute("name", annotation)
1273
 
                    ann_tag.setAttribute("value", value)
1274
 
                    if_tag.appendChild(ann_tag)
1275
 
                # Fix argument name for the Introspect method itself
1276
 
                if (if_tag.getAttribute("name")
1277
 
                    == dbus.INTROSPECTABLE_IFACE):
1278
 
                    for cn in if_tag.getElementsByTagName("method"):
1279
 
                        if cn.getAttribute("name") == "Introspect":
1280
 
                            for arg in cn.getElementsByTagName("arg"):
1281
 
                                if (arg.getAttribute("direction")
1282
 
                                    == "out"):
1283
 
                                    arg.setAttribute("name",
1284
 
                                                     "xml_data")
1285
 
            xmlstring = document.toxml("utf-8")
1286
 
            document.unlink()
1287
 
        except (AttributeError, xml.dom.DOMException,
1288
 
                xml.parsers.expat.ExpatError) as error:
1289
 
            logger.error("Failed to override Introspection method",
1290
 
                         exc_info=error)
1291
 
        return xmlstring
1292
 
 
1293
 
 
1294
 
class DBusObjectWithProperties(DBusObjectWithAnnotations):
1295
 
    """A D-Bus object with properties.
1296
 
 
1297
 
    Classes inheriting from this can use the dbus_service_property
1298
 
    decorator to expose methods as D-Bus properties.  It exposes the
1299
 
    standard Get(), Set(), and GetAll() methods on the D-Bus.
1300
 
    """
1301
 
 
 
898
    
1302
899
    def _get_dbus_property(self, interface_name, property_name):
1303
900
        """Returns a bound method if one exists which is a D-Bus
1304
901
        property with the specified name and interface.
1309
906
                if (value._dbus_name == property_name
1310
907
                    and value._dbus_interface == interface_name):
1311
908
                    return value.__get__(self)
1312
 
 
 
909
        
1313
910
        # No such property
1314
911
        raise DBusPropertyNotFound("{}:{}.{}".format(
1315
912
            self.dbus_object_path, interface_name, property_name))
1316
 
 
1317
 
    @classmethod
1318
 
    def _get_all_interface_names(cls):
1319
 
        """Get a sequence of all interfaces supported by an object"""
1320
 
        return (name for name in set(getattr(getattr(x, attr),
1321
 
                                             "_dbus_interface", None)
1322
 
                                     for x in (inspect.getmro(cls))
1323
 
                                     for attr in dir(x))
1324
 
                if name is not None)
1325
 
 
 
913
    
1326
914
    @dbus.service.method(dbus.PROPERTIES_IFACE,
1327
915
                         in_signature="ss",
1328
916
                         out_signature="v")
1336
924
        if not hasattr(value, "variant_level"):
1337
925
            return value
1338
926
        return type(value)(value, variant_level=value.variant_level+1)
1339
 
 
 
927
    
1340
928
    @dbus.service.method(dbus.PROPERTIES_IFACE, in_signature="ssv")
1341
929
    def Set(self, interface_name, property_name, value):
1342
930
        """Standard D-Bus property Set() method, see D-Bus standard.
1354
942
            value = dbus.ByteArray(b''.join(chr(byte)
1355
943
                                            for byte in value))
1356
944
        prop(value)
1357
 
 
 
945
    
1358
946
    @dbus.service.method(dbus.PROPERTIES_IFACE,
1359
947
                         in_signature="s",
1360
948
                         out_signature="a{sv}")
1361
949
    def GetAll(self, interface_name):
1362
950
        """Standard D-Bus property GetAll() method, see D-Bus
1363
951
        standard.
1364
 
 
 
952
        
1365
953
        Note: Will not include properties with access="write".
1366
954
        """
1367
955
        properties = {}
1378
966
                properties[name] = value
1379
967
                continue
1380
968
            properties[name] = type(value)(
1381
 
                value, variant_level=value.variant_level + 1)
 
969
                value, variant_level = value.variant_level + 1)
1382
970
        return dbus.Dictionary(properties, signature="sv")
1383
 
 
 
971
    
1384
972
    @dbus.service.signal(dbus.PROPERTIES_IFACE, signature="sa{sv}as")
1385
973
    def PropertiesChanged(self, interface_name, changed_properties,
1386
974
                          invalidated_properties):
1388
976
        standard.
1389
977
        """
1390
978
        pass
1391
 
 
 
979
    
1392
980
    @dbus.service.method(dbus.INTROSPECTABLE_IFACE,
1393
981
                         out_signature="s",
1394
982
                         path_keyword='object_path',
1395
983
                         connection_keyword='connection')
1396
984
    def Introspect(self, object_path, connection):
1397
985
        """Overloading of standard D-Bus method.
1398
 
 
 
986
        
1399
987
        Inserts property tags and interface annotation tags.
1400
988
        """
1401
 
        xmlstring = DBusObjectWithAnnotations.Introspect(self,
1402
 
                                                         object_path,
1403
 
                                                         connection)
 
989
        xmlstring = dbus.service.Object.Introspect(self, object_path,
 
990
                                                   connection)
1404
991
        try:
1405
992
            document = xml.dom.minidom.parseString(xmlstring)
1406
 
 
 
993
            
1407
994
            def make_tag(document, name, prop):
1408
995
                e = document.createElement("property")
1409
996
                e.setAttribute("name", name)
1410
997
                e.setAttribute("type", prop._dbus_signature)
1411
998
                e.setAttribute("access", prop._dbus_access)
1412
999
                return e
1413
 
 
 
1000
            
1414
1001
            for if_tag in document.getElementsByTagName("interface"):
1415
1002
                # Add property tags
1416
1003
                for tag in (make_tag(document, name, prop)
1419
1006
                            if prop._dbus_interface
1420
1007
                            == if_tag.getAttribute("name")):
1421
1008
                    if_tag.appendChild(tag)
1422
 
                # Add annotation tags for properties
1423
 
                for tag in if_tag.getElementsByTagName("property"):
1424
 
                    annots = dict()
1425
 
                    for name, prop in self._get_all_dbus_things(
1426
 
                            "property"):
1427
 
                        if (name == tag.getAttribute("name")
1428
 
                            and prop._dbus_interface
1429
 
                            == if_tag.getAttribute("name")):
1430
 
                            annots.update(getattr(
1431
 
                                prop, "_dbus_annotations", {}))
1432
 
                    for name, value in annots.items():
1433
 
                        ann_tag = document.createElement(
1434
 
                            "annotation")
1435
 
                        ann_tag.setAttribute("name", name)
1436
 
                        ann_tag.setAttribute("value", value)
1437
 
                        tag.appendChild(ann_tag)
 
1009
                # Add annotation tags
 
1010
                for typ in ("method", "signal", "property"):
 
1011
                    for tag in if_tag.getElementsByTagName(typ):
 
1012
                        annots = dict()
 
1013
                        for name, prop in (self.
 
1014
                                           _get_all_dbus_things(typ)):
 
1015
                            if (name == tag.getAttribute("name")
 
1016
                                and prop._dbus_interface
 
1017
                                == if_tag.getAttribute("name")):
 
1018
                                annots.update(getattr(
 
1019
                                    prop, "_dbus_annotations", {}))
 
1020
                        for name, value in annots.items():
 
1021
                            ann_tag = document.createElement(
 
1022
                                "annotation")
 
1023
                            ann_tag.setAttribute("name", name)
 
1024
                            ann_tag.setAttribute("value", value)
 
1025
                            tag.appendChild(ann_tag)
 
1026
                # Add interface annotation tags
 
1027
                for annotation, value in dict(
 
1028
                    itertools.chain.from_iterable(
 
1029
                        annotations().items()
 
1030
                        for name, annotations
 
1031
                        in self._get_all_dbus_things("interface")
 
1032
                        if name == if_tag.getAttribute("name")
 
1033
                        )).items():
 
1034
                    ann_tag = document.createElement("annotation")
 
1035
                    ann_tag.setAttribute("name", annotation)
 
1036
                    ann_tag.setAttribute("value", value)
 
1037
                    if_tag.appendChild(ann_tag)
1438
1038
                # Add the names to the return values for the
1439
1039
                # "org.freedesktop.DBus.Properties" methods
1440
1040
                if (if_tag.getAttribute("name")
1458
1058
                         exc_info=error)
1459
1059
        return xmlstring
1460
1060
 
1461
 
try:
1462
 
    dbus.OBJECT_MANAGER_IFACE
1463
 
except AttributeError:
1464
 
    dbus.OBJECT_MANAGER_IFACE = "org.freedesktop.DBus.ObjectManager"
1465
 
 
1466
 
 
1467
 
class DBusObjectWithObjectManager(DBusObjectWithAnnotations):
1468
 
    """A D-Bus object with an ObjectManager.
1469
 
 
1470
 
    Classes inheriting from this exposes the standard
1471
 
    GetManagedObjects call and the InterfacesAdded and
1472
 
    InterfacesRemoved signals on the standard
1473
 
    "org.freedesktop.DBus.ObjectManager" interface.
1474
 
 
1475
 
    Note: No signals are sent automatically; they must be sent
1476
 
    manually.
1477
 
    """
1478
 
    @dbus.service.method(dbus.OBJECT_MANAGER_IFACE,
1479
 
                         out_signature="a{oa{sa{sv}}}")
1480
 
    def GetManagedObjects(self):
1481
 
        """This function must be overridden"""
1482
 
        raise NotImplementedError()
1483
 
 
1484
 
    @dbus.service.signal(dbus.OBJECT_MANAGER_IFACE,
1485
 
                         signature="oa{sa{sv}}")
1486
 
    def InterfacesAdded(self, object_path, interfaces_and_properties):
1487
 
        pass
1488
 
 
1489
 
    @dbus.service.signal(dbus.OBJECT_MANAGER_IFACE, signature="oas")
1490
 
    def InterfacesRemoved(self, object_path, interfaces):
1491
 
        pass
1492
 
 
1493
 
    @dbus.service.method(dbus.INTROSPECTABLE_IFACE,
1494
 
                         out_signature="s",
1495
 
                         path_keyword='object_path',
1496
 
                         connection_keyword='connection')
1497
 
    def Introspect(self, object_path, connection):
1498
 
        """Overloading of standard D-Bus method.
1499
 
 
1500
 
        Override return argument name of GetManagedObjects to be
1501
 
        "objpath_interfaces_and_properties"
1502
 
        """
1503
 
        xmlstring = DBusObjectWithAnnotations.Introspect(self,
1504
 
                                                         object_path,
1505
 
                                                         connection)
1506
 
        try:
1507
 
            document = xml.dom.minidom.parseString(xmlstring)
1508
 
 
1509
 
            for if_tag in document.getElementsByTagName("interface"):
1510
 
                # Fix argument name for the GetManagedObjects method
1511
 
                if (if_tag.getAttribute("name")
1512
 
                    == dbus.OBJECT_MANAGER_IFACE):
1513
 
                    for cn in if_tag.getElementsByTagName("method"):
1514
 
                        if (cn.getAttribute("name")
1515
 
                            == "GetManagedObjects"):
1516
 
                            for arg in cn.getElementsByTagName("arg"):
1517
 
                                if (arg.getAttribute("direction")
1518
 
                                    == "out"):
1519
 
                                    arg.setAttribute(
1520
 
                                        "name",
1521
 
                                        "objpath_interfaces"
1522
 
                                        "_and_properties")
1523
 
            xmlstring = document.toxml("utf-8")
1524
 
            document.unlink()
1525
 
        except (AttributeError, xml.dom.DOMException,
1526
 
                xml.parsers.expat.ExpatError) as error:
1527
 
            logger.error("Failed to override Introspection method",
1528
 
                         exc_info=error)
1529
 
        return xmlstring
1530
 
 
1531
1061
 
1532
1062
def datetime_to_dbus(dt, variant_level=0):
1533
1063
    """Convert a UTC datetime.datetime() to a D-Bus type."""
1534
1064
    if dt is None:
1535
 
        return dbus.String("", variant_level=variant_level)
 
1065
        return dbus.String("", variant_level = variant_level)
1536
1066
    return dbus.String(dt.isoformat(), variant_level=variant_level)
1537
1067
 
1538
1068
 
1541
1071
    dbus.service.Object, it will add alternate D-Bus attributes with
1542
1072
    interface names according to the "alt_interface_names" mapping.
1543
1073
    Usage:
1544
 
 
 
1074
    
1545
1075
    @alternate_dbus_interfaces({"org.example.Interface":
1546
1076
                                    "net.example.AlternateInterface"})
1547
1077
    class SampleDBusObject(dbus.service.Object):
1548
1078
        @dbus.service.method("org.example.Interface")
1549
1079
        def SampleDBusMethod():
1550
1080
            pass
1551
 
 
 
1081
    
1552
1082
    The above "SampleDBusMethod" on "SampleDBusObject" will be
1553
1083
    reachable via two interfaces: "org.example.Interface" and
1554
1084
    "net.example.AlternateInterface", the latter of which will have
1555
1085
    its D-Bus annotation "org.freedesktop.DBus.Deprecated" set to
1556
1086
    "true", unless "deprecate" is passed with a False value.
1557
 
 
 
1087
    
1558
1088
    This works for methods and signals, and also for D-Bus properties
1559
1089
    (from DBusObjectWithProperties) and interfaces (from the
1560
1090
    dbus_interface_annotations decorator).
1561
1091
    """
1562
 
 
 
1092
    
1563
1093
    def wrapper(cls):
1564
1094
        for orig_interface_name, alt_interface_name in (
1565
1095
                alt_interface_names.items()):
1580
1110
                interface_names.add(alt_interface)
1581
1111
                # Is this a D-Bus signal?
1582
1112
                if getattr(attribute, "_dbus_is_signal", False):
1583
 
                    # Extract the original non-method undecorated
1584
 
                    # function by black magic
1585
1113
                    if sys.version_info.major == 2:
 
1114
                        # Extract the original non-method undecorated
 
1115
                        # function by black magic
1586
1116
                        nonmethod_func = (dict(
1587
1117
                            zip(attribute.func_code.co_freevars,
1588
1118
                                attribute.__closure__))
1589
1119
                                          ["func"].cell_contents)
1590
1120
                    else:
1591
 
                        nonmethod_func = (dict(
1592
 
                            zip(attribute.__code__.co_freevars,
1593
 
                                attribute.__closure__))
1594
 
                                          ["func"].cell_contents)
 
1121
                        nonmethod_func = attribute
1595
1122
                    # Create a new, but exactly alike, function
1596
1123
                    # object, and decorate it to be a new D-Bus signal
1597
1124
                    # with the alternate D-Bus interface name
1598
 
                    new_function = copy_function(nonmethod_func)
 
1125
                    if sys.version_info.major == 2:
 
1126
                        new_function = types.FunctionType(
 
1127
                            nonmethod_func.func_code,
 
1128
                            nonmethod_func.func_globals,
 
1129
                            nonmethod_func.func_name,
 
1130
                            nonmethod_func.func_defaults,
 
1131
                            nonmethod_func.func_closure)
 
1132
                    else:
 
1133
                        new_function = types.FunctionType(
 
1134
                            nonmethod_func.__code__,
 
1135
                            nonmethod_func.__globals__,
 
1136
                            nonmethod_func.__name__,
 
1137
                            nonmethod_func.__defaults__,
 
1138
                            nonmethod_func.__closure__)
1599
1139
                    new_function = (dbus.service.signal(
1600
1140
                        alt_interface,
1601
1141
                        attribute._dbus_signature)(new_function))
1605
1145
                            attribute._dbus_annotations)
1606
1146
                    except AttributeError:
1607
1147
                        pass
1608
 
 
1609
1148
                    # Define a creator of a function to call both the
1610
1149
                    # original and alternate functions, so both the
1611
1150
                    # original and alternate signals gets sent when
1614
1153
                        """This function is a scope container to pass
1615
1154
                        func1 and func2 to the "call_both" function
1616
1155
                        outside of its arguments"""
1617
 
 
1618
 
                        @functools.wraps(func2)
 
1156
                        
1619
1157
                        def call_both(*args, **kwargs):
1620
1158
                            """This function will emit two D-Bus
1621
1159
                            signals by calling func1 and func2"""
1622
1160
                            func1(*args, **kwargs)
1623
1161
                            func2(*args, **kwargs)
1624
 
                        # Make wrapper function look like a D-Bus
1625
 
                        # signal
1626
 
                        for name, attr in inspect.getmembers(func2):
1627
 
                            if name.startswith("_dbus_"):
1628
 
                                setattr(call_both, name, attr)
1629
 
 
 
1162
                        
1630
1163
                        return call_both
1631
1164
                    # Create the "call_both" function and add it to
1632
1165
                    # the class
1642
1175
                            alt_interface,
1643
1176
                            attribute._dbus_in_signature,
1644
1177
                            attribute._dbus_out_signature)
1645
 
                        (copy_function(attribute)))
 
1178
                        (types.FunctionType(attribute.func_code,
 
1179
                                            attribute.func_globals,
 
1180
                                            attribute.func_name,
 
1181
                                            attribute.func_defaults,
 
1182
                                            attribute.func_closure)))
1646
1183
                    # Copy annotations, if any
1647
1184
                    try:
1648
1185
                        attr[attrname]._dbus_annotations = dict(
1660
1197
                        attribute._dbus_access,
1661
1198
                        attribute._dbus_get_args_options
1662
1199
                        ["byte_arrays"])
1663
 
                                      (copy_function(attribute)))
 
1200
                                      (types.FunctionType(
 
1201
                                          attribute.func_code,
 
1202
                                          attribute.func_globals,
 
1203
                                          attribute.func_name,
 
1204
                                          attribute.func_defaults,
 
1205
                                          attribute.func_closure)))
1664
1206
                    # Copy annotations, if any
1665
1207
                    try:
1666
1208
                        attr[attrname]._dbus_annotations = dict(
1675
1217
                    # to the class.
1676
1218
                    attr[attrname] = (
1677
1219
                        dbus_interface_annotations(alt_interface)
1678
 
                        (copy_function(attribute)))
 
1220
                        (types.FunctionType(attribute.func_code,
 
1221
                                            attribute.func_globals,
 
1222
                                            attribute.func_name,
 
1223
                                            attribute.func_defaults,
 
1224
                                            attribute.func_closure)))
1679
1225
            if deprecate:
1680
1226
                # Deprecate all alternate interfaces
1681
 
                iname = "_AlternateDBusNames_interface_annotation{}"
 
1227
                iname="_AlternateDBusNames_interface_annotation{}"
1682
1228
                for interface_name in interface_names:
1683
 
 
 
1229
                    
1684
1230
                    @dbus_interface_annotations(interface_name)
1685
1231
                    def func(self):
1686
 
                        return {"org.freedesktop.DBus.Deprecated":
1687
 
                                "true"}
 
1232
                        return { "org.freedesktop.DBus.Deprecated":
 
1233
                                 "true" }
1688
1234
                    # Find an unused name
1689
1235
                    for aname in (iname.format(i)
1690
1236
                                  for i in itertools.count()):
1694
1240
            if interface_names:
1695
1241
                # Replace the class with a new subclass of it with
1696
1242
                # methods, signals, etc. as created above.
1697
 
                if sys.version_info.major == 2:
1698
 
                    cls = type(b"{}Alternate".format(cls.__name__),
1699
 
                               (cls, ), attr)
1700
 
                else:
1701
 
                    cls = type("{}Alternate".format(cls.__name__),
1702
 
                               (cls, ), attr)
 
1243
                cls = type(b"{}Alternate".format(cls.__name__),
 
1244
                           (cls, ), attr)
1703
1245
        return cls
1704
 
 
 
1246
    
1705
1247
    return wrapper
1706
1248
 
1707
1249
 
1709
1251
                            "se.bsnet.fukt.Mandos"})
1710
1252
class ClientDBus(Client, DBusObjectWithProperties):
1711
1253
    """A Client class using D-Bus
1712
 
 
 
1254
    
1713
1255
    Attributes:
1714
1256
    dbus_object_path: dbus.ObjectPath
1715
1257
    bus: dbus.SystemBus()
1716
1258
    """
1717
 
 
 
1259
    
1718
1260
    runtime_expansions = (Client.runtime_expansions
1719
1261
                          + ("dbus_object_path", ))
1720
 
 
 
1262
    
1721
1263
    _interface = "se.recompile.Mandos.Client"
1722
 
 
 
1264
    
1723
1265
    # dbus.service.Object doesn't use super(), so we can't either.
1724
 
 
1725
 
    def __init__(self, bus=None, *args, **kwargs):
 
1266
    
 
1267
    def __init__(self, bus = None, *args, **kwargs):
1726
1268
        self.bus = bus
1727
1269
        Client.__init__(self, *args, **kwargs)
1728
1270
        # Only now, when this client is initialized, can it show up on
1734
1276
            "/clients/" + client_object_name)
1735
1277
        DBusObjectWithProperties.__init__(self, self.bus,
1736
1278
                                          self.dbus_object_path)
1737
 
 
 
1279
    
1738
1280
    def notifychangeproperty(transform_func, dbus_name,
1739
1281
                             type_func=lambda x: x,
1740
1282
                             variant_level=1,
1742
1284
                             _interface=_interface):
1743
1285
        """ Modify a variable so that it's a property which announces
1744
1286
        its changes to DBus.
1745
 
 
 
1287
        
1746
1288
        transform_fun: Function that takes a value and a variant_level
1747
1289
                       and transforms it to a D-Bus type.
1748
1290
        dbus_name: D-Bus name of the variable
1751
1293
        variant_level: D-Bus variant level.  Default: 1
1752
1294
        """
1753
1295
        attrname = "_{}".format(dbus_name)
1754
 
 
 
1296
        
1755
1297
        def setter(self, value):
1756
1298
            if hasattr(self, "dbus_object_path"):
1757
1299
                if (not hasattr(self, attrname) or
1764
1306
                    else:
1765
1307
                        dbus_value = transform_func(
1766
1308
                            type_func(value),
1767
 
                            variant_level=variant_level)
 
1309
                            variant_level = variant_level)
1768
1310
                        self.PropertyChanged(dbus.String(dbus_name),
1769
1311
                                             dbus_value)
1770
1312
                        self.PropertiesChanged(
1771
1313
                            _interface,
1772
 
                            dbus.Dictionary({dbus.String(dbus_name):
1773
 
                                             dbus_value}),
 
1314
                            dbus.Dictionary({ dbus.String(dbus_name):
 
1315
                                              dbus_value }),
1774
1316
                            dbus.Array())
1775
1317
            setattr(self, attrname, value)
1776
 
 
 
1318
        
1777
1319
        return property(lambda self: getattr(self, attrname), setter)
1778
 
 
 
1320
    
1779
1321
    expires = notifychangeproperty(datetime_to_dbus, "Expires")
1780
1322
    approvals_pending = notifychangeproperty(dbus.Boolean,
1781
1323
                                             "ApprovalPending",
1782
 
                                             type_func=bool)
 
1324
                                             type_func = bool)
1783
1325
    enabled = notifychangeproperty(dbus.Boolean, "Enabled")
1784
1326
    last_enabled = notifychangeproperty(datetime_to_dbus,
1785
1327
                                        "LastEnabled")
1786
1328
    checker = notifychangeproperty(
1787
1329
        dbus.Boolean, "CheckerRunning",
1788
 
        type_func=lambda checker: checker is not None)
 
1330
        type_func = lambda checker: checker is not None)
1789
1331
    last_checked_ok = notifychangeproperty(datetime_to_dbus,
1790
1332
                                           "LastCheckedOK")
1791
1333
    last_checker_status = notifychangeproperty(dbus.Int16,
1796
1338
                                               "ApprovedByDefault")
1797
1339
    approval_delay = notifychangeproperty(
1798
1340
        dbus.UInt64, "ApprovalDelay",
1799
 
        type_func=lambda td: td.total_seconds() * 1000)
 
1341
        type_func = lambda td: td.total_seconds() * 1000)
1800
1342
    approval_duration = notifychangeproperty(
1801
1343
        dbus.UInt64, "ApprovalDuration",
1802
 
        type_func=lambda td: td.total_seconds() * 1000)
 
1344
        type_func = lambda td: td.total_seconds() * 1000)
1803
1345
    host = notifychangeproperty(dbus.String, "Host")
1804
1346
    timeout = notifychangeproperty(
1805
1347
        dbus.UInt64, "Timeout",
1806
 
        type_func=lambda td: td.total_seconds() * 1000)
 
1348
        type_func = lambda td: td.total_seconds() * 1000)
1807
1349
    extended_timeout = notifychangeproperty(
1808
1350
        dbus.UInt64, "ExtendedTimeout",
1809
 
        type_func=lambda td: td.total_seconds() * 1000)
 
1351
        type_func = lambda td: td.total_seconds() * 1000)
1810
1352
    interval = notifychangeproperty(
1811
1353
        dbus.UInt64, "Interval",
1812
 
        type_func=lambda td: td.total_seconds() * 1000)
 
1354
        type_func = lambda td: td.total_seconds() * 1000)
1813
1355
    checker_command = notifychangeproperty(dbus.String, "Checker")
1814
1356
    secret = notifychangeproperty(dbus.ByteArray, "Secret",
1815
1357
                                  invalidate_only=True)
1816
 
 
 
1358
    
1817
1359
    del notifychangeproperty
1818
 
 
 
1360
    
1819
1361
    def __del__(self, *args, **kwargs):
1820
1362
        try:
1821
1363
            self.remove_from_connection()
1824
1366
        if hasattr(DBusObjectWithProperties, "__del__"):
1825
1367
            DBusObjectWithProperties.__del__(self, *args, **kwargs)
1826
1368
        Client.__del__(self, *args, **kwargs)
1827
 
 
 
1369
    
1828
1370
    def checker_callback(self, source, condition,
1829
1371
                         connection, command, *args, **kwargs):
1830
1372
        ret = Client.checker_callback(self, source, condition,
1834
1376
        if exitstatus >= 0:
1835
1377
            # Emit D-Bus signal
1836
1378
            self.CheckerCompleted(dbus.Int16(exitstatus),
1837
 
                                  # This is specific to GNU libC
1838
 
                                  dbus.Int64(exitstatus << 8),
 
1379
                                  dbus.Int64(0),
1839
1380
                                  dbus.String(command))
1840
1381
        else:
1841
1382
            # Emit D-Bus signal
1842
1383
            self.CheckerCompleted(dbus.Int16(-1),
1843
1384
                                  dbus.Int64(
1844
 
                                      # This is specific to GNU libC
1845
 
                                      (exitstatus << 8)
1846
 
                                      | self.last_checker_signal),
 
1385
                                      self.last_checker_signal),
1847
1386
                                  dbus.String(command))
1848
1387
        return ret
1849
 
 
 
1388
    
1850
1389
    def start_checker(self, *args, **kwargs):
1851
1390
        old_checker_pid = getattr(self.checker, "pid", None)
1852
1391
        r = Client.start_checker(self, *args, **kwargs)
1856
1395
            # Emit D-Bus signal
1857
1396
            self.CheckerStarted(self.current_checker_command)
1858
1397
        return r
1859
 
 
 
1398
    
1860
1399
    def _reset_approved(self):
1861
1400
        self.approved = None
1862
1401
        return False
1863
 
 
 
1402
    
1864
1403
    def approve(self, value=True):
1865
1404
        self.approved = value
1866
 
        GLib.timeout_add(int(self.approval_duration.total_seconds()
1867
 
                             * 1000), self._reset_approved)
 
1405
        gobject.timeout_add(int(self.approval_duration.total_seconds()
 
1406
                                * 1000), self._reset_approved)
1868
1407
        self.send_changedstate()
1869
 
 
1870
 
    #  D-Bus methods, signals & properties
1871
 
 
1872
 
    #  Interfaces
1873
 
 
1874
 
    #  Signals
1875
 
 
 
1408
    
 
1409
    ## D-Bus methods, signals & properties
 
1410
    
 
1411
    ## Interfaces
 
1412
    
 
1413
    ## Signals
 
1414
    
1876
1415
    # CheckerCompleted - signal
1877
1416
    @dbus.service.signal(_interface, signature="nxs")
1878
1417
    def CheckerCompleted(self, exitcode, waitstatus, command):
1879
1418
        "D-Bus signal"
1880
1419
        pass
1881
 
 
 
1420
    
1882
1421
    # CheckerStarted - signal
1883
1422
    @dbus.service.signal(_interface, signature="s")
1884
1423
    def CheckerStarted(self, command):
1885
1424
        "D-Bus signal"
1886
1425
        pass
1887
 
 
 
1426
    
1888
1427
    # PropertyChanged - signal
1889
1428
    @dbus_annotations({"org.freedesktop.DBus.Deprecated": "true"})
1890
1429
    @dbus.service.signal(_interface, signature="sv")
1891
1430
    def PropertyChanged(self, property, value):
1892
1431
        "D-Bus signal"
1893
1432
        pass
1894
 
 
 
1433
    
1895
1434
    # GotSecret - signal
1896
1435
    @dbus.service.signal(_interface)
1897
1436
    def GotSecret(self):
1900
1439
        server to mandos-client
1901
1440
        """
1902
1441
        pass
1903
 
 
 
1442
    
1904
1443
    # Rejected - signal
1905
1444
    @dbus.service.signal(_interface, signature="s")
1906
1445
    def Rejected(self, reason):
1907
1446
        "D-Bus signal"
1908
1447
        pass
1909
 
 
 
1448
    
1910
1449
    # NeedApproval - signal
1911
1450
    @dbus.service.signal(_interface, signature="tb")
1912
1451
    def NeedApproval(self, timeout, default):
1913
1452
        "D-Bus signal"
1914
1453
        return self.need_approval()
1915
 
 
1916
 
    #  Methods
1917
 
 
 
1454
    
 
1455
    ## Methods
 
1456
    
1918
1457
    # Approve - method
1919
1458
    @dbus.service.method(_interface, in_signature="b")
1920
1459
    def Approve(self, value):
1921
1460
        self.approve(value)
1922
 
 
 
1461
    
1923
1462
    # CheckedOK - method
1924
1463
    @dbus.service.method(_interface)
1925
1464
    def CheckedOK(self):
1926
1465
        self.checked_ok()
1927
 
 
 
1466
    
1928
1467
    # Enable - method
1929
1468
    @dbus_annotations({"org.freedesktop.DBus.Deprecated": "true"})
1930
1469
    @dbus.service.method(_interface)
1931
1470
    def Enable(self):
1932
1471
        "D-Bus method"
1933
1472
        self.enable()
1934
 
 
 
1473
    
1935
1474
    # StartChecker - method
1936
1475
    @dbus_annotations({"org.freedesktop.DBus.Deprecated": "true"})
1937
1476
    @dbus.service.method(_interface)
1938
1477
    def StartChecker(self):
1939
1478
        "D-Bus method"
1940
1479
        self.start_checker()
1941
 
 
 
1480
    
1942
1481
    # Disable - method
1943
1482
    @dbus_annotations({"org.freedesktop.DBus.Deprecated": "true"})
1944
1483
    @dbus.service.method(_interface)
1945
1484
    def Disable(self):
1946
1485
        "D-Bus method"
1947
1486
        self.disable()
1948
 
 
 
1487
    
1949
1488
    # StopChecker - method
1950
1489
    @dbus_annotations({"org.freedesktop.DBus.Deprecated": "true"})
1951
1490
    @dbus.service.method(_interface)
1952
1491
    def StopChecker(self):
1953
1492
        self.stop_checker()
1954
 
 
1955
 
    #  Properties
1956
 
 
 
1493
    
 
1494
    ## Properties
 
1495
    
1957
1496
    # ApprovalPending - property
1958
1497
    @dbus_service_property(_interface, signature="b", access="read")
1959
1498
    def ApprovalPending_dbus_property(self):
1960
1499
        return dbus.Boolean(bool(self.approvals_pending))
1961
 
 
 
1500
    
1962
1501
    # ApprovedByDefault - property
1963
1502
    @dbus_service_property(_interface,
1964
1503
                           signature="b",
1967
1506
        if value is None:       # get
1968
1507
            return dbus.Boolean(self.approved_by_default)
1969
1508
        self.approved_by_default = bool(value)
1970
 
 
 
1509
    
1971
1510
    # ApprovalDelay - property
1972
1511
    @dbus_service_property(_interface,
1973
1512
                           signature="t",
1977
1516
            return dbus.UInt64(self.approval_delay.total_seconds()
1978
1517
                               * 1000)
1979
1518
        self.approval_delay = datetime.timedelta(0, 0, 0, value)
1980
 
 
 
1519
    
1981
1520
    # ApprovalDuration - property
1982
1521
    @dbus_service_property(_interface,
1983
1522
                           signature="t",
1987
1526
            return dbus.UInt64(self.approval_duration.total_seconds()
1988
1527
                               * 1000)
1989
1528
        self.approval_duration = datetime.timedelta(0, 0, 0, value)
1990
 
 
 
1529
    
1991
1530
    # Name - property
1992
1531
    @dbus_annotations(
1993
1532
        {"org.freedesktop.DBus.Property.EmitsChangedSignal": "const"})
1994
1533
    @dbus_service_property(_interface, signature="s", access="read")
1995
1534
    def Name_dbus_property(self):
1996
1535
        return dbus.String(self.name)
1997
 
 
 
1536
    
1998
1537
    # Fingerprint - property
1999
1538
    @dbus_annotations(
2000
1539
        {"org.freedesktop.DBus.Property.EmitsChangedSignal": "const"})
2001
1540
    @dbus_service_property(_interface, signature="s", access="read")
2002
1541
    def Fingerprint_dbus_property(self):
2003
1542
        return dbus.String(self.fingerprint)
2004
 
 
 
1543
    
2005
1544
    # Host - property
2006
1545
    @dbus_service_property(_interface,
2007
1546
                           signature="s",
2010
1549
        if value is None:       # get
2011
1550
            return dbus.String(self.host)
2012
1551
        self.host = str(value)
2013
 
 
 
1552
    
2014
1553
    # Created - property
2015
1554
    @dbus_annotations(
2016
1555
        {"org.freedesktop.DBus.Property.EmitsChangedSignal": "const"})
2017
1556
    @dbus_service_property(_interface, signature="s", access="read")
2018
1557
    def Created_dbus_property(self):
2019
1558
        return datetime_to_dbus(self.created)
2020
 
 
 
1559
    
2021
1560
    # LastEnabled - property
2022
1561
    @dbus_service_property(_interface, signature="s", access="read")
2023
1562
    def LastEnabled_dbus_property(self):
2024
1563
        return datetime_to_dbus(self.last_enabled)
2025
 
 
 
1564
    
2026
1565
    # Enabled - property
2027
1566
    @dbus_service_property(_interface,
2028
1567
                           signature="b",
2034
1573
            self.enable()
2035
1574
        else:
2036
1575
            self.disable()
2037
 
 
 
1576
    
2038
1577
    # LastCheckedOK - property
2039
1578
    @dbus_service_property(_interface,
2040
1579
                           signature="s",
2044
1583
            self.checked_ok()
2045
1584
            return
2046
1585
        return datetime_to_dbus(self.last_checked_ok)
2047
 
 
 
1586
    
2048
1587
    # LastCheckerStatus - property
2049
1588
    @dbus_service_property(_interface, signature="n", access="read")
2050
1589
    def LastCheckerStatus_dbus_property(self):
2051
1590
        return dbus.Int16(self.last_checker_status)
2052
 
 
 
1591
    
2053
1592
    # Expires - property
2054
1593
    @dbus_service_property(_interface, signature="s", access="read")
2055
1594
    def Expires_dbus_property(self):
2056
1595
        return datetime_to_dbus(self.expires)
2057
 
 
 
1596
    
2058
1597
    # LastApprovalRequest - property
2059
1598
    @dbus_service_property(_interface, signature="s", access="read")
2060
1599
    def LastApprovalRequest_dbus_property(self):
2061
1600
        return datetime_to_dbus(self.last_approval_request)
2062
 
 
 
1601
    
2063
1602
    # Timeout - property
2064
1603
    @dbus_service_property(_interface,
2065
1604
                           signature="t",
2080
1619
                if (getattr(self, "disable_initiator_tag", None)
2081
1620
                    is None):
2082
1621
                    return
2083
 
                GLib.source_remove(self.disable_initiator_tag)
2084
 
                self.disable_initiator_tag = GLib.timeout_add(
 
1622
                gobject.source_remove(self.disable_initiator_tag)
 
1623
                self.disable_initiator_tag = gobject.timeout_add(
2085
1624
                    int((self.expires - now).total_seconds() * 1000),
2086
1625
                    self.disable)
2087
 
 
 
1626
    
2088
1627
    # ExtendedTimeout - property
2089
1628
    @dbus_service_property(_interface,
2090
1629
                           signature="t",
2094
1633
            return dbus.UInt64(self.extended_timeout.total_seconds()
2095
1634
                               * 1000)
2096
1635
        self.extended_timeout = datetime.timedelta(0, 0, 0, value)
2097
 
 
 
1636
    
2098
1637
    # Interval - property
2099
1638
    @dbus_service_property(_interface,
2100
1639
                           signature="t",
2107
1646
            return
2108
1647
        if self.enabled:
2109
1648
            # Reschedule checker run
2110
 
            GLib.source_remove(self.checker_initiator_tag)
2111
 
            self.checker_initiator_tag = GLib.timeout_add(
 
1649
            gobject.source_remove(self.checker_initiator_tag)
 
1650
            self.checker_initiator_tag = gobject.timeout_add(
2112
1651
                value, self.start_checker)
2113
 
            self.start_checker()  # Start one now, too
2114
 
 
 
1652
            self.start_checker() # Start one now, too
 
1653
    
2115
1654
    # Checker - property
2116
1655
    @dbus_service_property(_interface,
2117
1656
                           signature="s",
2120
1659
        if value is None:       # get
2121
1660
            return dbus.String(self.checker_command)
2122
1661
        self.checker_command = str(value)
2123
 
 
 
1662
    
2124
1663
    # CheckerRunning - property
2125
1664
    @dbus_service_property(_interface,
2126
1665
                           signature="b",
2132
1671
            self.start_checker()
2133
1672
        else:
2134
1673
            self.stop_checker()
2135
 
 
 
1674
    
2136
1675
    # ObjectPath - property
2137
1676
    @dbus_annotations(
2138
1677
        {"org.freedesktop.DBus.Property.EmitsChangedSignal": "const",
2139
1678
         "org.freedesktop.DBus.Deprecated": "true"})
2140
1679
    @dbus_service_property(_interface, signature="o", access="read")
2141
1680
    def ObjectPath_dbus_property(self):
2142
 
        return self.dbus_object_path  # is already a dbus.ObjectPath
2143
 
 
 
1681
        return self.dbus_object_path # is already a dbus.ObjectPath
 
1682
    
2144
1683
    # Secret = property
2145
1684
    @dbus_annotations(
2146
1685
        {"org.freedesktop.DBus.Property.EmitsChangedSignal":
2151
1690
                           byte_arrays=True)
2152
1691
    def Secret_dbus_property(self, value):
2153
1692
        self.secret = bytes(value)
2154
 
 
 
1693
    
2155
1694
    del _interface
2156
1695
 
2157
1696
 
2161
1700
        self._pipe.send(('init', fpr, address))
2162
1701
        if not self._pipe.recv():
2163
1702
            raise KeyError(fpr)
2164
 
 
 
1703
    
2165
1704
    def __getattribute__(self, name):
2166
1705
        if name == '_pipe':
2167
1706
            return super(ProxyClient, self).__getattribute__(name)
2170
1709
        if data[0] == 'data':
2171
1710
            return data[1]
2172
1711
        if data[0] == 'function':
2173
 
 
 
1712
            
2174
1713
            def func(*args, **kwargs):
2175
1714
                self._pipe.send(('funcall', name, args, kwargs))
2176
1715
                return self._pipe.recv()[1]
2177
 
 
 
1716
            
2178
1717
            return func
2179
 
 
 
1718
    
2180
1719
    def __setattr__(self, name, value):
2181
1720
        if name == '_pipe':
2182
1721
            return super(ProxyClient, self).__setattr__(name, value)
2185
1724
 
2186
1725
class ClientHandler(socketserver.BaseRequestHandler, object):
2187
1726
    """A class to handle client connections.
2188
 
 
 
1727
    
2189
1728
    Instantiated once for each connection to handle it.
2190
1729
    Note: This will run in its own forked process."""
2191
 
 
 
1730
    
2192
1731
    def handle(self):
2193
1732
        with contextlib.closing(self.server.child_pipe) as child_pipe:
2194
1733
            logger.info("TCP connection from: %s",
2195
1734
                        str(self.client_address))
2196
1735
            logger.debug("Pipe FD: %d",
2197
1736
                         self.server.child_pipe.fileno())
2198
 
 
2199
 
            session = gnutls.ClientSession(self.request)
2200
 
 
2201
 
            # priority = ':'.join(("NONE", "+VERS-TLS1.1",
2202
 
            #                       "+AES-256-CBC", "+SHA1",
2203
 
            #                       "+COMP-NULL", "+CTYPE-OPENPGP",
2204
 
            #                       "+DHE-DSS"))
 
1737
            
 
1738
            session = gnutls.connection.ClientSession(
 
1739
                self.request, gnutls.connection .X509Credentials())
 
1740
            
 
1741
            # Note: gnutls.connection.X509Credentials is really a
 
1742
            # generic GnuTLS certificate credentials object so long as
 
1743
            # no X.509 keys are added to it.  Therefore, we can use it
 
1744
            # here despite using OpenPGP certificates.
 
1745
            
 
1746
            #priority = ':'.join(("NONE", "+VERS-TLS1.1",
 
1747
            #                      "+AES-256-CBC", "+SHA1",
 
1748
            #                      "+COMP-NULL", "+CTYPE-OPENPGP",
 
1749
            #                      "+DHE-DSS"))
2205
1750
            # Use a fallback default, since this MUST be set.
2206
1751
            priority = self.server.gnutls_priority
2207
1752
            if priority is None:
2208
1753
                priority = "NORMAL"
2209
 
            gnutls.priority_set_direct(session._c_object,
2210
 
                                       priority.encode("utf-8"),
2211
 
                                       None)
2212
 
 
 
1754
            gnutls.library.functions.gnutls_priority_set_direct(
 
1755
                session._c_object, priority, None)
 
1756
            
2213
1757
            # Start communication using the Mandos protocol
2214
1758
            # Get protocol number
2215
1759
            line = self.request.makefile().readline()
2220
1764
            except (ValueError, IndexError, RuntimeError) as error:
2221
1765
                logger.error("Unknown protocol version: %s", error)
2222
1766
                return
2223
 
 
 
1767
            
2224
1768
            # Start GnuTLS connection
2225
1769
            try:
2226
1770
                session.handshake()
2227
 
            except gnutls.Error as error:
 
1771
            except gnutls.errors.GNUTLSError as error:
2228
1772
                logger.warning("Handshake failed: %s", error)
2229
1773
                # Do not run session.bye() here: the session is not
2230
1774
                # established.  Just abandon the request.
2231
1775
                return
2232
1776
            logger.debug("Handshake succeeded")
2233
 
 
 
1777
            
2234
1778
            approval_required = False
2235
1779
            try:
2236
1780
                try:
2237
1781
                    fpr = self.fingerprint(
2238
1782
                        self.peer_certificate(session))
2239
 
                except (TypeError, gnutls.Error) as error:
 
1783
                except (TypeError,
 
1784
                        gnutls.errors.GNUTLSError) as error:
2240
1785
                    logger.warning("Bad certificate: %s", error)
2241
1786
                    return
2242
1787
                logger.debug("Fingerprint: %s", fpr)
2243
 
 
 
1788
                
2244
1789
                try:
2245
1790
                    client = ProxyClient(child_pipe, fpr,
2246
1791
                                         self.client_address)
2247
1792
                except KeyError:
2248
1793
                    return
2249
 
 
 
1794
                
2250
1795
                if client.approval_delay:
2251
1796
                    delay = client.approval_delay
2252
1797
                    client.approvals_pending += 1
2253
1798
                    approval_required = True
2254
 
 
 
1799
                
2255
1800
                while True:
2256
1801
                    if not client.enabled:
2257
1802
                        logger.info("Client %s is disabled",
2260
1805
                            # Emit D-Bus signal
2261
1806
                            client.Rejected("Disabled")
2262
1807
                        return
2263
 
 
 
1808
                    
2264
1809
                    if client.approved or not client.approval_delay:
2265
 
                        # We are approved or approval is disabled
 
1810
                        #We are approved or approval is disabled
2266
1811
                        break
2267
1812
                    elif client.approved is None:
2268
1813
                        logger.info("Client %s needs approval",
2279
1824
                            # Emit D-Bus signal
2280
1825
                            client.Rejected("Denied")
2281
1826
                        return
2282
 
 
2283
 
                    # wait until timeout or approved
 
1827
                    
 
1828
                    #wait until timeout or approved
2284
1829
                    time = datetime.datetime.now()
2285
1830
                    client.changedstate.acquire()
2286
1831
                    client.changedstate.wait(delay.total_seconds())
2299
1844
                            break
2300
1845
                    else:
2301
1846
                        delay -= time2 - time
2302
 
 
2303
 
                try:
2304
 
                    session.send(client.secret)
2305
 
                except gnutls.Error as error:
2306
 
                    logger.warning("gnutls send failed",
2307
 
                                   exc_info=error)
2308
 
                    return
2309
 
 
 
1847
                
 
1848
                sent_size = 0
 
1849
                while sent_size < len(client.secret):
 
1850
                    try:
 
1851
                        sent = session.send(client.secret[sent_size:])
 
1852
                    except gnutls.errors.GNUTLSError as error:
 
1853
                        logger.warning("gnutls send failed",
 
1854
                                       exc_info=error)
 
1855
                        return
 
1856
                    logger.debug("Sent: %d, remaining: %d", sent,
 
1857
                                 len(client.secret) - (sent_size
 
1858
                                                       + sent))
 
1859
                    sent_size += sent
 
1860
                
2310
1861
                logger.info("Sending secret to %s", client.name)
2311
1862
                # bump the timeout using extended_timeout
2312
1863
                client.bump_timeout(client.extended_timeout)
2313
1864
                if self.server.use_dbus:
2314
1865
                    # Emit D-Bus signal
2315
1866
                    client.GotSecret()
2316
 
 
 
1867
            
2317
1868
            finally:
2318
1869
                if approval_required:
2319
1870
                    client.approvals_pending -= 1
2320
1871
                try:
2321
1872
                    session.bye()
2322
 
                except gnutls.Error as error:
 
1873
                except gnutls.errors.GNUTLSError as error:
2323
1874
                    logger.warning("GnuTLS bye failed",
2324
1875
                                   exc_info=error)
2325
 
 
 
1876
    
2326
1877
    @staticmethod
2327
1878
    def peer_certificate(session):
2328
1879
        "Return the peer's OpenPGP certificate as a bytestring"
2329
1880
        # If not an OpenPGP certificate...
2330
 
        if (gnutls.certificate_type_get(session._c_object)
2331
 
            != gnutls.CRT_OPENPGP):
2332
 
            # ...return invalid data
2333
 
            return b""
 
1881
        if (gnutls.library.functions.gnutls_certificate_type_get(
 
1882
                session._c_object)
 
1883
            != gnutls.library.constants.GNUTLS_CRT_OPENPGP):
 
1884
            # ...do the normal thing
 
1885
            return session.peer_certificate
2334
1886
        list_size = ctypes.c_uint(1)
2335
 
        cert_list = (gnutls.certificate_get_peers
 
1887
        cert_list = (gnutls.library.functions
 
1888
                     .gnutls_certificate_get_peers
2336
1889
                     (session._c_object, ctypes.byref(list_size)))
2337
1890
        if not bool(cert_list) and list_size.value != 0:
2338
 
            raise gnutls.Error("error getting peer certificate")
 
1891
            raise gnutls.errors.GNUTLSError("error getting peer"
 
1892
                                            " certificate")
2339
1893
        if list_size.value == 0:
2340
1894
            return None
2341
1895
        cert = cert_list[0]
2342
1896
        return ctypes.string_at(cert.data, cert.size)
2343
 
 
 
1897
    
2344
1898
    @staticmethod
2345
1899
    def fingerprint(openpgp):
2346
1900
        "Convert an OpenPGP bytestring to a hexdigit fingerprint"
2347
1901
        # New GnuTLS "datum" with the OpenPGP public key
2348
 
        datum = gnutls.datum_t(
 
1902
        datum = gnutls.library.types.gnutls_datum_t(
2349
1903
            ctypes.cast(ctypes.c_char_p(openpgp),
2350
1904
                        ctypes.POINTER(ctypes.c_ubyte)),
2351
1905
            ctypes.c_uint(len(openpgp)))
2352
1906
        # New empty GnuTLS certificate
2353
 
        crt = gnutls.openpgp_crt_t()
2354
 
        gnutls.openpgp_crt_init(ctypes.byref(crt))
 
1907
        crt = gnutls.library.types.gnutls_openpgp_crt_t()
 
1908
        gnutls.library.functions.gnutls_openpgp_crt_init(
 
1909
            ctypes.byref(crt))
2355
1910
        # Import the OpenPGP public key into the certificate
2356
 
        gnutls.openpgp_crt_import(crt, ctypes.byref(datum),
2357
 
                                  gnutls.OPENPGP_FMT_RAW)
 
1911
        gnutls.library.functions.gnutls_openpgp_crt_import(
 
1912
            crt, ctypes.byref(datum),
 
1913
            gnutls.library.constants.GNUTLS_OPENPGP_FMT_RAW)
2358
1914
        # Verify the self signature in the key
2359
1915
        crtverify = ctypes.c_uint()
2360
 
        gnutls.openpgp_crt_verify_self(crt, 0,
2361
 
                                       ctypes.byref(crtverify))
 
1916
        gnutls.library.functions.gnutls_openpgp_crt_verify_self(
 
1917
            crt, 0, ctypes.byref(crtverify))
2362
1918
        if crtverify.value != 0:
2363
 
            gnutls.openpgp_crt_deinit(crt)
2364
 
            raise gnutls.CertificateSecurityError("Verify failed")
 
1919
            gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
 
1920
            raise gnutls.errors.CertificateSecurityError(
 
1921
                "Verify failed")
2365
1922
        # New buffer for the fingerprint
2366
1923
        buf = ctypes.create_string_buffer(20)
2367
1924
        buf_len = ctypes.c_size_t()
2368
1925
        # Get the fingerprint from the certificate into the buffer
2369
 
        gnutls.openpgp_crt_get_fingerprint(crt, ctypes.byref(buf),
2370
 
                                           ctypes.byref(buf_len))
 
1926
        gnutls.library.functions.gnutls_openpgp_crt_get_fingerprint(
 
1927
            crt, ctypes.byref(buf), ctypes.byref(buf_len))
2371
1928
        # Deinit the certificate
2372
 
        gnutls.openpgp_crt_deinit(crt)
 
1929
        gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
2373
1930
        # Convert the buffer to a Python bytestring
2374
1931
        fpr = ctypes.string_at(buf, buf_len.value)
2375
1932
        # Convert the bytestring to hexadecimal notation
2379
1936
 
2380
1937
class MultiprocessingMixIn(object):
2381
1938
    """Like socketserver.ThreadingMixIn, but with multiprocessing"""
2382
 
 
 
1939
    
2383
1940
    def sub_process_main(self, request, address):
2384
1941
        try:
2385
1942
            self.finish_request(request, address)
2386
1943
        except Exception:
2387
1944
            self.handle_error(request, address)
2388
1945
        self.close_request(request)
2389
 
 
 
1946
    
2390
1947
    def process_request(self, request, address):
2391
1948
        """Start a new process to process the request."""
2392
 
        proc = multiprocessing.Process(target=self.sub_process_main,
2393
 
                                       args=(request, address))
 
1949
        proc = multiprocessing.Process(target = self.sub_process_main,
 
1950
                                       args = (request, address))
2394
1951
        proc.start()
2395
1952
        return proc
2396
1953
 
2397
1954
 
2398
1955
class MultiprocessingMixInWithPipe(MultiprocessingMixIn, object):
2399
1956
    """ adds a pipe to the MixIn """
2400
 
 
 
1957
    
2401
1958
    def process_request(self, request, client_address):
2402
1959
        """Overrides and wraps the original process_request().
2403
 
 
 
1960
        
2404
1961
        This function creates a new pipe in self.pipe
2405
1962
        """
2406
1963
        parent_pipe, self.child_pipe = multiprocessing.Pipe()
2407
 
 
 
1964
        
2408
1965
        proc = MultiprocessingMixIn.process_request(self, request,
2409
1966
                                                    client_address)
2410
1967
        self.child_pipe.close()
2411
1968
        self.add_pipe(parent_pipe, proc)
2412
 
 
 
1969
    
2413
1970
    def add_pipe(self, parent_pipe, proc):
2414
1971
        """Dummy function; override as necessary"""
2415
1972
        raise NotImplementedError()
2418
1975
class IPv6_TCPServer(MultiprocessingMixInWithPipe,
2419
1976
                     socketserver.TCPServer, object):
2420
1977
    """IPv6-capable TCP server.  Accepts 'None' as address and/or port
2421
 
 
 
1978
    
2422
1979
    Attributes:
2423
1980
        enabled:        Boolean; whether this server is activated yet
2424
1981
        interface:      None or a network interface name (string)
2425
1982
        use_ipv6:       Boolean; to use IPv6 or not
2426
1983
    """
2427
 
 
 
1984
    
2428
1985
    def __init__(self, server_address, RequestHandlerClass,
2429
1986
                 interface=None,
2430
1987
                 use_ipv6=True,
2440
1997
            self.socketfd = socketfd
2441
1998
            # Save the original socket.socket() function
2442
1999
            self.socket_socket = socket.socket
2443
 
 
2444
2000
            # To implement --socket, we monkey patch socket.socket.
2445
 
            #
 
2001
            # 
2446
2002
            # (When socketserver.TCPServer is a new-style class, we
2447
2003
            # could make self.socket into a property instead of monkey
2448
2004
            # patching socket.socket.)
2449
 
            #
 
2005
            # 
2450
2006
            # Create a one-time-only replacement for socket.socket()
2451
2007
            @functools.wraps(socket.socket)
2452
2008
            def socket_wrapper(*args, **kwargs):
2464
2020
        # socket_wrapper(), if socketfd was set.
2465
2021
        socketserver.TCPServer.__init__(self, server_address,
2466
2022
                                        RequestHandlerClass)
2467
 
 
 
2023
    
2468
2024
    def server_bind(self):
2469
2025
        """This overrides the normal server_bind() function
2470
2026
        to bind to an interface if one was specified, and also NOT to
2471
2027
        bind to an address or port if they were not specified."""
2472
 
        global SO_BINDTODEVICE
2473
2028
        if self.interface is not None:
2474
2029
            if SO_BINDTODEVICE is None:
2475
 
                # Fall back to a hard-coded value which seems to be
2476
 
                # common enough.
2477
 
                logger.warning("SO_BINDTODEVICE not found, trying 25")
2478
 
                SO_BINDTODEVICE = 25
2479
 
            try:
2480
 
                self.socket.setsockopt(
2481
 
                    socket.SOL_SOCKET, SO_BINDTODEVICE,
2482
 
                    (self.interface + "\0").encode("utf-8"))
2483
 
            except socket.error as error:
2484
 
                if error.errno == errno.EPERM:
2485
 
                    logger.error("No permission to bind to"
2486
 
                                 " interface %s", self.interface)
2487
 
                elif error.errno == errno.ENOPROTOOPT:
2488
 
                    logger.error("SO_BINDTODEVICE not available;"
2489
 
                                 " cannot bind to interface %s",
2490
 
                                 self.interface)
2491
 
                elif error.errno == errno.ENODEV:
2492
 
                    logger.error("Interface %s does not exist,"
2493
 
                                 " cannot bind", self.interface)
2494
 
                else:
2495
 
                    raise
 
2030
                logger.error("SO_BINDTODEVICE does not exist;"
 
2031
                             " cannot bind to interface %s",
 
2032
                             self.interface)
 
2033
            else:
 
2034
                try:
 
2035
                    self.socket.setsockopt(
 
2036
                        socket.SOL_SOCKET, SO_BINDTODEVICE,
 
2037
                        (self.interface + "\0").encode("utf-8"))
 
2038
                except socket.error as error:
 
2039
                    if error.errno == errno.EPERM:
 
2040
                        logger.error("No permission to bind to"
 
2041
                                     " interface %s", self.interface)
 
2042
                    elif error.errno == errno.ENOPROTOOPT:
 
2043
                        logger.error("SO_BINDTODEVICE not available;"
 
2044
                                     " cannot bind to interface %s",
 
2045
                                     self.interface)
 
2046
                    elif error.errno == errno.ENODEV:
 
2047
                        logger.error("Interface %s does not exist,"
 
2048
                                     " cannot bind", self.interface)
 
2049
                    else:
 
2050
                        raise
2496
2051
        # Only bind(2) the socket if we really need to.
2497
2052
        if self.server_address[0] or self.server_address[1]:
2498
2053
            if not self.server_address[0]:
2499
2054
                if self.address_family == socket.AF_INET6:
2500
 
                    any_address = "::"  # in6addr_any
 
2055
                    any_address = "::" # in6addr_any
2501
2056
                else:
2502
 
                    any_address = "0.0.0.0"  # INADDR_ANY
 
2057
                    any_address = "0.0.0.0" # INADDR_ANY
2503
2058
                self.server_address = (any_address,
2504
2059
                                       self.server_address[1])
2505
2060
            elif not self.server_address[1]:
2515
2070
 
2516
2071
class MandosServer(IPv6_TCPServer):
2517
2072
    """Mandos server.
2518
 
 
 
2073
    
2519
2074
    Attributes:
2520
2075
        clients:        set of Client objects
2521
2076
        gnutls_priority GnuTLS priority string
2522
2077
        use_dbus:       Boolean; to emit D-Bus signals or not
2523
 
 
2524
 
    Assumes a GLib.MainLoop event loop.
 
2078
    
 
2079
    Assumes a gobject.MainLoop event loop.
2525
2080
    """
2526
 
 
 
2081
    
2527
2082
    def __init__(self, server_address, RequestHandlerClass,
2528
2083
                 interface=None,
2529
2084
                 use_ipv6=True,
2539
2094
        self.gnutls_priority = gnutls_priority
2540
2095
        IPv6_TCPServer.__init__(self, server_address,
2541
2096
                                RequestHandlerClass,
2542
 
                                interface=interface,
2543
 
                                use_ipv6=use_ipv6,
2544
 
                                socketfd=socketfd)
2545
 
 
 
2097
                                interface = interface,
 
2098
                                use_ipv6 = use_ipv6,
 
2099
                                socketfd = socketfd)
 
2100
    
2546
2101
    def server_activate(self):
2547
2102
        if self.enabled:
2548
2103
            return socketserver.TCPServer.server_activate(self)
2549
 
 
 
2104
    
2550
2105
    def enable(self):
2551
2106
        self.enabled = True
2552
 
 
 
2107
    
2553
2108
    def add_pipe(self, parent_pipe, proc):
2554
2109
        # Call "handle_ipc" for both data and EOF events
2555
 
        GLib.io_add_watch(
 
2110
        gobject.io_add_watch(
2556
2111
            parent_pipe.fileno(),
2557
 
            GLib.IO_IN | GLib.IO_HUP,
 
2112
            gobject.IO_IN | gobject.IO_HUP,
2558
2113
            functools.partial(self.handle_ipc,
2559
 
                              parent_pipe=parent_pipe,
2560
 
                              proc=proc))
2561
 
 
 
2114
                              parent_pipe = parent_pipe,
 
2115
                              proc = proc))
 
2116
    
2562
2117
    def handle_ipc(self, source, condition,
2563
2118
                   parent_pipe=None,
2564
 
                   proc=None,
 
2119
                   proc = None,
2565
2120
                   client_object=None):
2566
2121
        # error, or the other end of multiprocessing.Pipe has closed
2567
 
        if condition & (GLib.IO_ERR | GLib.IO_HUP):
 
2122
        if condition & (gobject.IO_ERR | gobject.IO_HUP):
2568
2123
            # Wait for other process to exit
2569
2124
            proc.join()
2570
2125
            return False
2571
 
 
 
2126
        
2572
2127
        # Read a request from the child
2573
2128
        request = parent_pipe.recv()
2574
2129
        command = request[0]
2575
 
 
 
2130
        
2576
2131
        if command == 'init':
2577
2132
            fpr = request[1]
2578
2133
            address = request[2]
2579
 
 
2580
 
            for c in self.clients.values():
 
2134
            
 
2135
            for c in self.clients.itervalues():
2581
2136
                if c.fingerprint == fpr:
2582
2137
                    client = c
2583
2138
                    break
2590
2145
                                                       address[0])
2591
2146
                parent_pipe.send(False)
2592
2147
                return False
2593
 
 
2594
 
            GLib.io_add_watch(
 
2148
            
 
2149
            gobject.io_add_watch(
2595
2150
                parent_pipe.fileno(),
2596
 
                GLib.IO_IN | GLib.IO_HUP,
 
2151
                gobject.IO_IN | gobject.IO_HUP,
2597
2152
                functools.partial(self.handle_ipc,
2598
 
                                  parent_pipe=parent_pipe,
2599
 
                                  proc=proc,
2600
 
                                  client_object=client))
 
2153
                                  parent_pipe = parent_pipe,
 
2154
                                  proc = proc,
 
2155
                                  client_object = client))
2601
2156
            parent_pipe.send(True)
2602
2157
            # remove the old hook in favor of the new above hook on
2603
2158
            # same fileno
2606
2161
            funcname = request[1]
2607
2162
            args = request[2]
2608
2163
            kwargs = request[3]
2609
 
 
 
2164
            
2610
2165
            parent_pipe.send(('data', getattr(client_object,
2611
2166
                                              funcname)(*args,
2612
2167
                                                        **kwargs)))
2613
 
 
 
2168
        
2614
2169
        if command == 'getattr':
2615
2170
            attrname = request[1]
2616
2171
            if isinstance(client_object.__getattribute__(attrname),
2619
2174
            else:
2620
2175
                parent_pipe.send((
2621
2176
                    'data', client_object.__getattribute__(attrname)))
2622
 
 
 
2177
        
2623
2178
        if command == 'setattr':
2624
2179
            attrname = request[1]
2625
2180
            value = request[2]
2626
2181
            setattr(client_object, attrname, value)
2627
 
 
 
2182
        
2628
2183
        return True
2629
2184
 
2630
2185
 
2631
2186
def rfc3339_duration_to_delta(duration):
2632
2187
    """Parse an RFC 3339 "duration" and return a datetime.timedelta
2633
 
 
 
2188
    
2634
2189
    >>> rfc3339_duration_to_delta("P7D")
2635
2190
    datetime.timedelta(7)
2636
2191
    >>> rfc3339_duration_to_delta("PT60S")
2646
2201
    >>> rfc3339_duration_to_delta("P1DT3M20S")
2647
2202
    datetime.timedelta(1, 200)
2648
2203
    """
2649
 
 
 
2204
    
2650
2205
    # Parsing an RFC 3339 duration with regular expressions is not
2651
2206
    # possible - there would have to be multiple places for the same
2652
2207
    # values, like seconds.  The current code, while more esoteric, is
2653
2208
    # cleaner without depending on a parsing library.  If Python had a
2654
2209
    # built-in library for parsing we would use it, but we'd like to
2655
2210
    # avoid excessive use of external libraries.
2656
 
 
 
2211
    
2657
2212
    # New type for defining tokens, syntax, and semantics all-in-one
2658
2213
    Token = collections.namedtuple("Token", (
2659
2214
        "regexp",  # To match token; if "value" is not None, must have
2692
2247
                           frozenset((token_year, token_month,
2693
2248
                                      token_day, token_time,
2694
2249
                                      token_week)))
2695
 
    # Define starting values:
2696
 
    # Value so far
2697
 
    value = datetime.timedelta()
 
2250
    # Define starting values
 
2251
    value = datetime.timedelta() # Value so far
2698
2252
    found_token = None
2699
 
    # Following valid tokens
2700
 
    followers = frozenset((token_duration, ))
2701
 
    # String left to parse
2702
 
    s = duration
 
2253
    followers = frozenset((token_duration, )) # Following valid tokens
 
2254
    s = duration                # String left to parse
2703
2255
    # Loop until end token is found
2704
2256
    while found_token is not token_end:
2705
2257
        # Search for any currently valid tokens
2729
2281
 
2730
2282
def string_to_delta(interval):
2731
2283
    """Parse a string and return a datetime.timedelta
2732
 
 
 
2284
    
2733
2285
    >>> string_to_delta('7d')
2734
2286
    datetime.timedelta(7)
2735
2287
    >>> string_to_delta('60s')
2743
2295
    >>> string_to_delta('5m 30s')
2744
2296
    datetime.timedelta(0, 330)
2745
2297
    """
2746
 
 
 
2298
    
2747
2299
    try:
2748
2300
        return rfc3339_duration_to_delta(interval)
2749
2301
    except ValueError:
2750
2302
        pass
2751
 
 
 
2303
    
2752
2304
    timevalue = datetime.timedelta(0)
2753
2305
    for s in interval.split():
2754
2306
        try:
2772
2324
    return timevalue
2773
2325
 
2774
2326
 
2775
 
def daemon(nochdir=False, noclose=False):
 
2327
def daemon(nochdir = False, noclose = False):
2776
2328
    """See daemon(3).  Standard BSD Unix function.
2777
 
 
 
2329
    
2778
2330
    This should really exist as os.daemon, but it doesn't (yet)."""
2779
2331
    if os.fork():
2780
2332
        sys.exit()
2798
2350
 
2799
2351
 
2800
2352
def main():
2801
 
 
 
2353
    
2802
2354
    ##################################################################
2803
2355
    # Parsing of options, both command line and config file
2804
 
 
 
2356
    
2805
2357
    parser = argparse.ArgumentParser()
2806
2358
    parser.add_argument("-v", "--version", action="version",
2807
 
                        version="%(prog)s {}".format(version),
 
2359
                        version = "%(prog)s {}".format(version),
2808
2360
                        help="show version number and exit")
2809
2361
    parser.add_argument("-i", "--interface", metavar="IF",
2810
2362
                        help="Bind to interface IF")
2846
2398
    parser.add_argument("--no-zeroconf", action="store_false",
2847
2399
                        dest="zeroconf", help="Do not use Zeroconf",
2848
2400
                        default=None)
2849
 
 
 
2401
    
2850
2402
    options = parser.parse_args()
2851
 
 
 
2403
    
2852
2404
    if options.check:
2853
2405
        import doctest
2854
2406
        fail_count, test_count = doctest.testmod()
2855
2407
        sys.exit(os.EX_OK if fail_count == 0 else 1)
2856
 
 
 
2408
    
2857
2409
    # Default values for config file for server-global settings
2858
 
    server_defaults = {"interface": "",
2859
 
                       "address": "",
2860
 
                       "port": "",
2861
 
                       "debug": "False",
2862
 
                       "priority":
2863
 
                       "SECURE256:!CTYPE-X.509:+CTYPE-OPENPGP:!RSA"
2864
 
                       ":+SIGN-DSA-SHA256",
2865
 
                       "servicename": "Mandos",
2866
 
                       "use_dbus": "True",
2867
 
                       "use_ipv6": "True",
2868
 
                       "debuglevel": "",
2869
 
                       "restore": "True",
2870
 
                       "socket": "",
2871
 
                       "statedir": "/var/lib/mandos",
2872
 
                       "foreground": "False",
2873
 
                       "zeroconf": "True",
2874
 
                       }
2875
 
 
 
2410
    server_defaults = { "interface": "",
 
2411
                        "address": "",
 
2412
                        "port": "",
 
2413
                        "debug": "False",
 
2414
                        "priority":
 
2415
                        "SECURE256:!CTYPE-X.509:+CTYPE-OPENPGP:!RSA"
 
2416
                        ":+SIGN-DSA-SHA256",
 
2417
                        "servicename": "Mandos",
 
2418
                        "use_dbus": "True",
 
2419
                        "use_ipv6": "True",
 
2420
                        "debuglevel": "",
 
2421
                        "restore": "True",
 
2422
                        "socket": "",
 
2423
                        "statedir": "/var/lib/mandos",
 
2424
                        "foreground": "False",
 
2425
                        "zeroconf": "True",
 
2426
                    }
 
2427
    
2876
2428
    # Parse config file for server-global settings
2877
2429
    server_config = configparser.SafeConfigParser(server_defaults)
2878
2430
    del server_defaults
2896
2448
            server_settings["socket"] = os.dup(server_settings
2897
2449
                                               ["socket"])
2898
2450
    del server_config
2899
 
 
 
2451
    
2900
2452
    # Override the settings from the config file with command line
2901
2453
    # options, if set.
2902
2454
    for option in ("interface", "address", "port", "debug",
2920
2472
    if server_settings["debug"]:
2921
2473
        server_settings["foreground"] = True
2922
2474
    # Now we have our good server settings in "server_settings"
2923
 
 
 
2475
    
2924
2476
    ##################################################################
2925
 
 
 
2477
    
2926
2478
    if (not server_settings["zeroconf"]
2927
2479
        and not (server_settings["port"]
2928
2480
                 or server_settings["socket"] != "")):
2929
2481
        parser.error("Needs port or socket to work without Zeroconf")
2930
 
 
 
2482
    
2931
2483
    # For convenience
2932
2484
    debug = server_settings["debug"]
2933
2485
    debuglevel = server_settings["debuglevel"]
2937
2489
                                     stored_state_file)
2938
2490
    foreground = server_settings["foreground"]
2939
2491
    zeroconf = server_settings["zeroconf"]
2940
 
 
 
2492
    
2941
2493
    if debug:
2942
2494
        initlogger(debug, logging.DEBUG)
2943
2495
    else:
2946
2498
        else:
2947
2499
            level = getattr(logging, debuglevel.upper())
2948
2500
            initlogger(debug, level)
2949
 
 
 
2501
    
2950
2502
    if server_settings["servicename"] != "Mandos":
2951
2503
        syslogger.setFormatter(
2952
2504
            logging.Formatter('Mandos ({}) [%(process)d]:'
2953
2505
                              ' %(levelname)s: %(message)s'.format(
2954
2506
                                  server_settings["servicename"])))
2955
 
 
 
2507
    
2956
2508
    # Parse config file with clients
2957
2509
    client_config = configparser.SafeConfigParser(Client
2958
2510
                                                  .client_defaults)
2959
2511
    client_config.read(os.path.join(server_settings["configdir"],
2960
2512
                                    "clients.conf"))
2961
 
 
 
2513
    
2962
2514
    global mandos_dbus_service
2963
2515
    mandos_dbus_service = None
2964
 
 
 
2516
    
2965
2517
    socketfd = None
2966
2518
    if server_settings["socket"] != "":
2967
2519
        socketfd = server_settings["socket"]
2983
2535
        except IOError as e:
2984
2536
            logger.error("Could not open file %r", pidfilename,
2985
2537
                         exc_info=e)
2986
 
 
2987
 
    for name, group in (("_mandos", "_mandos"),
2988
 
                        ("mandos", "mandos"),
2989
 
                        ("nobody", "nogroup")):
 
2538
    
 
2539
    for name in ("_mandos", "mandos", "nobody"):
2990
2540
        try:
2991
2541
            uid = pwd.getpwnam(name).pw_uid
2992
 
            gid = pwd.getpwnam(group).pw_gid
 
2542
            gid = pwd.getpwnam(name).pw_gid
2993
2543
            break
2994
2544
        except KeyError:
2995
2545
            continue
2999
2549
    try:
3000
2550
        os.setgid(gid)
3001
2551
        os.setuid(uid)
3002
 
        if debug:
3003
 
            logger.debug("Did setuid/setgid to {}:{}".format(uid,
3004
 
                                                             gid))
3005
2552
    except OSError as error:
3006
 
        logger.warning("Failed to setuid/setgid to {}:{}: {}"
3007
 
                       .format(uid, gid, os.strerror(error.errno)))
3008
2553
        if error.errno != errno.EPERM:
3009
2554
            raise
3010
 
 
 
2555
    
3011
2556
    if debug:
3012
2557
        # Enable all possible GnuTLS debugging
3013
 
 
 
2558
        
3014
2559
        # "Use a log level over 10 to enable all debugging options."
3015
2560
        # - GnuTLS manual
3016
 
        gnutls.global_set_log_level(11)
3017
 
 
3018
 
        @gnutls.log_func
 
2561
        gnutls.library.functions.gnutls_global_set_log_level(11)
 
2562
        
 
2563
        @gnutls.library.types.gnutls_log_func
3019
2564
        def debug_gnutls(level, string):
3020
2565
            logger.debug("GnuTLS: %s", string[:-1])
3021
 
 
3022
 
        gnutls.global_set_log_function(debug_gnutls)
3023
 
 
 
2566
        
 
2567
        gnutls.library.functions.gnutls_global_set_log_function(
 
2568
            debug_gnutls)
 
2569
        
3024
2570
        # Redirect stdin so all checkers get /dev/null
3025
2571
        null = os.open(os.devnull, os.O_NOCTTY | os.O_RDWR)
3026
2572
        os.dup2(null, sys.stdin.fileno())
3027
2573
        if null > 2:
3028
2574
            os.close(null)
3029
 
 
 
2575
    
3030
2576
    # Need to fork before connecting to D-Bus
3031
2577
    if not foreground:
3032
2578
        # Close all input and output, do double fork, etc.
3033
2579
        daemon()
3034
 
 
3035
 
    # multiprocessing will use threads, so before we use GLib we need
3036
 
    # to inform GLib that threads will be used.
3037
 
    GLib.threads_init()
3038
 
 
 
2580
    
 
2581
    # multiprocessing will use threads, so before we use gobject we
 
2582
    # need to inform gobject that threads will be used.
 
2583
    gobject.threads_init()
 
2584
    
3039
2585
    global main_loop
3040
2586
    # From the Avahi example code
3041
2587
    DBusGMainLoop(set_as_default=True)
3042
 
    main_loop = GLib.MainLoop()
 
2588
    main_loop = gobject.MainLoop()
3043
2589
    bus = dbus.SystemBus()
3044
2590
    # End of Avahi example code
3045
2591
    if use_dbus:
3058
2604
    if zeroconf:
3059
2605
        protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
3060
2606
        service = AvahiServiceToSyslog(
3061
 
            name=server_settings["servicename"],
3062
 
            servicetype="_mandos._tcp",
3063
 
            protocol=protocol,
3064
 
            bus=bus)
 
2607
            name = server_settings["servicename"],
 
2608
            servicetype = "_mandos._tcp",
 
2609
            protocol = protocol,
 
2610
            bus = bus)
3065
2611
        if server_settings["interface"]:
3066
2612
            service.interface = if_nametoindex(
3067
2613
                server_settings["interface"].encode("utf-8"))
3068
 
 
 
2614
    
3069
2615
    global multiprocessing_manager
3070
2616
    multiprocessing_manager = multiprocessing.Manager()
3071
 
 
 
2617
    
3072
2618
    client_class = Client
3073
2619
    if use_dbus:
3074
 
        client_class = functools.partial(ClientDBus, bus=bus)
3075
 
 
 
2620
        client_class = functools.partial(ClientDBus, bus = bus)
 
2621
    
3076
2622
    client_settings = Client.config_parser(client_config)
3077
2623
    old_client_settings = {}
3078
2624
    clients_data = {}
3079
 
 
 
2625
    
3080
2626
    # This is used to redirect stdout and stderr for checker processes
3081
2627
    global wnull
3082
 
    wnull = open(os.devnull, "w")  # A writable /dev/null
 
2628
    wnull = open(os.devnull, "w") # A writable /dev/null
3083
2629
    # Only used if server is running in foreground but not in debug
3084
2630
    # mode
3085
2631
    if debug or not foreground:
3086
2632
        wnull.close()
3087
 
 
 
2633
    
3088
2634
    # Get client data and settings from last running state.
3089
2635
    if server_settings["restore"]:
3090
2636
        try:
3091
2637
            with open(stored_state_path, "rb") as stored_state:
3092
 
                if sys.version_info.major == 2:
3093
 
                    clients_data, old_client_settings = pickle.load(
3094
 
                        stored_state)
3095
 
                else:
3096
 
                    bytes_clients_data, bytes_old_client_settings = (
3097
 
                        pickle.load(stored_state, encoding="bytes"))
3098
 
                    #   Fix bytes to strings
3099
 
                    #  clients_data
3100
 
                    # .keys()
3101
 
                    clients_data = {(key.decode("utf-8")
3102
 
                                     if isinstance(key, bytes)
3103
 
                                     else key): value
3104
 
                                    for key, value in
3105
 
                                    bytes_clients_data.items()}
3106
 
                    del bytes_clients_data
3107
 
                    for key in clients_data:
3108
 
                        value = {(k.decode("utf-8")
3109
 
                                  if isinstance(k, bytes) else k): v
3110
 
                                 for k, v in
3111
 
                                 clients_data[key].items()}
3112
 
                        clients_data[key] = value
3113
 
                        # .client_structure
3114
 
                        value["client_structure"] = [
3115
 
                            (s.decode("utf-8")
3116
 
                             if isinstance(s, bytes)
3117
 
                             else s) for s in
3118
 
                            value["client_structure"]]
3119
 
                        # .name & .host
3120
 
                        for k in ("name", "host"):
3121
 
                            if isinstance(value[k], bytes):
3122
 
                                value[k] = value[k].decode("utf-8")
3123
 
                    #  old_client_settings
3124
 
                    # .keys()
3125
 
                    old_client_settings = {
3126
 
                        (key.decode("utf-8")
3127
 
                         if isinstance(key, bytes)
3128
 
                         else key): value
3129
 
                        for key, value in
3130
 
                        bytes_old_client_settings.items()}
3131
 
                    del bytes_old_client_settings
3132
 
                    # .host
3133
 
                    for value in old_client_settings.values():
3134
 
                        if isinstance(value["host"], bytes):
3135
 
                            value["host"] = (value["host"]
3136
 
                                             .decode("utf-8"))
 
2638
                clients_data, old_client_settings = pickle.load(
 
2639
                    stored_state)
3137
2640
            os.remove(stored_state_path)
3138
2641
        except IOError as e:
3139
2642
            if e.errno == errno.ENOENT:
3147
2650
            logger.warning("Could not load persistent state: "
3148
2651
                           "EOFError:",
3149
2652
                           exc_info=e)
3150
 
 
 
2653
    
3151
2654
    with PGPEngine() as pgp:
3152
2655
        for client_name, client in clients_data.items():
3153
2656
            # Skip removed clients
3154
2657
            if client_name not in client_settings:
3155
2658
                continue
3156
 
 
 
2659
            
3157
2660
            # Decide which value to use after restoring saved state.
3158
2661
            # We have three different values: Old config file,
3159
2662
            # new config file, and saved state.
3170
2673
                        client[name] = value
3171
2674
                except KeyError:
3172
2675
                    pass
3173
 
 
 
2676
            
3174
2677
            # Clients who has passed its expire date can still be
3175
2678
            # enabled if its last checker was successful.  A Client
3176
2679
            # whose checker succeeded before we stored its state is
3209
2712
                    client_name))
3210
2713
                client["secret"] = (client_settings[client_name]
3211
2714
                                    ["secret"])
3212
 
 
 
2715
    
3213
2716
    # Add/remove clients based on new changes made to config
3214
2717
    for client_name in (set(old_client_settings)
3215
2718
                        - set(client_settings)):
3217
2720
    for client_name in (set(client_settings)
3218
2721
                        - set(old_client_settings)):
3219
2722
        clients_data[client_name] = client_settings[client_name]
3220
 
 
 
2723
    
3221
2724
    # Create all client objects
3222
2725
    for client_name, client in clients_data.items():
3223
2726
        tcp_server.clients[client_name] = client_class(
3224
 
            name=client_name,
3225
 
            settings=client,
3226
 
            server_settings=server_settings)
3227
 
 
 
2727
            name = client_name,
 
2728
            settings = client,
 
2729
            server_settings = server_settings)
 
2730
    
3228
2731
    if not tcp_server.clients:
3229
2732
        logger.warning("No clients defined")
3230
 
 
 
2733
    
3231
2734
    if not foreground:
3232
2735
        if pidfile is not None:
3233
2736
            pid = os.getpid()
3239
2742
                             pidfilename, pid)
3240
2743
        del pidfile
3241
2744
        del pidfilename
3242
 
 
3243
 
    for termsig in (signal.SIGHUP, signal.SIGTERM):
3244
 
        GLib.unix_signal_add(GLib.PRIORITY_HIGH, termsig,
3245
 
                             lambda: main_loop.quit() and False)
3246
 
 
 
2745
    
 
2746
    signal.signal(signal.SIGHUP, lambda signum, frame: sys.exit())
 
2747
    signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit())
 
2748
    
3247
2749
    if use_dbus:
3248
 
 
 
2750
        
3249
2751
        @alternate_dbus_interfaces(
3250
 
            {"se.recompile.Mandos": "se.bsnet.fukt.Mandos"})
3251
 
        class MandosDBusService(DBusObjectWithObjectManager):
 
2752
            { "se.recompile.Mandos": "se.bsnet.fukt.Mandos" })
 
2753
        class MandosDBusService(DBusObjectWithProperties):
3252
2754
            """A D-Bus proxy object"""
3253
 
 
 
2755
            
3254
2756
            def __init__(self):
3255
2757
                dbus.service.Object.__init__(self, bus, "/")
3256
 
 
 
2758
            
3257
2759
            _interface = "se.recompile.Mandos"
3258
 
 
 
2760
            
 
2761
            @dbus_interface_annotations(_interface)
 
2762
            def _foo(self):
 
2763
                return {
 
2764
                    "org.freedesktop.DBus.Property.EmitsChangedSignal":
 
2765
                    "false" }
 
2766
            
3259
2767
            @dbus.service.signal(_interface, signature="o")
3260
2768
            def ClientAdded(self, objpath):
3261
2769
                "D-Bus signal"
3262
2770
                pass
3263
 
 
 
2771
            
3264
2772
            @dbus.service.signal(_interface, signature="ss")
3265
2773
            def ClientNotFound(self, fingerprint, address):
3266
2774
                "D-Bus signal"
3267
2775
                pass
3268
 
 
3269
 
            @dbus_annotations({"org.freedesktop.DBus.Deprecated":
3270
 
                               "true"})
 
2776
            
3271
2777
            @dbus.service.signal(_interface, signature="os")
3272
2778
            def ClientRemoved(self, objpath, name):
3273
2779
                "D-Bus signal"
3274
2780
                pass
3275
 
 
3276
 
            @dbus_annotations({"org.freedesktop.DBus.Deprecated":
3277
 
                               "true"})
 
2781
            
3278
2782
            @dbus.service.method(_interface, out_signature="ao")
3279
2783
            def GetAllClients(self):
3280
2784
                "D-Bus method"
3281
2785
                return dbus.Array(c.dbus_object_path for c in
3282
 
                                  tcp_server.clients.values())
3283
 
 
3284
 
            @dbus_annotations({"org.freedesktop.DBus.Deprecated":
3285
 
                               "true"})
 
2786
                                  tcp_server.clients.itervalues())
 
2787
            
3286
2788
            @dbus.service.method(_interface,
3287
2789
                                 out_signature="a{oa{sv}}")
3288
2790
            def GetAllClientsWithProperties(self):
3289
2791
                "D-Bus method"
3290
2792
                return dbus.Dictionary(
3291
 
                    {c.dbus_object_path: c.GetAll(
3292
 
                        "se.recompile.Mandos.Client")
3293
 
                     for c in tcp_server.clients.values()},
 
2793
                    { c.dbus_object_path: c.GetAll("")
 
2794
                      for c in tcp_server.clients.itervalues() },
3294
2795
                    signature="oa{sv}")
3295
 
 
 
2796
            
3296
2797
            @dbus.service.method(_interface, in_signature="o")
3297
2798
            def RemoveClient(self, object_path):
3298
2799
                "D-Bus method"
3299
 
                for c in tcp_server.clients.values():
 
2800
                for c in tcp_server.clients.itervalues():
3300
2801
                    if c.dbus_object_path == object_path:
3301
2802
                        del tcp_server.clients[c.name]
3302
2803
                        c.remove_from_connection()
3303
 
                        # Don't signal the disabling
 
2804
                        # Don't signal anything except ClientRemoved
3304
2805
                        c.disable(quiet=True)
3305
 
                        # Emit D-Bus signal for removal
3306
 
                        self.client_removed_signal(c)
 
2806
                        # Emit D-Bus signal
 
2807
                        self.ClientRemoved(object_path, c.name)
3307
2808
                        return
3308
2809
                raise KeyError(object_path)
3309
 
 
 
2810
            
3310
2811
            del _interface
3311
 
 
3312
 
            @dbus.service.method(dbus.OBJECT_MANAGER_IFACE,
3313
 
                                 out_signature="a{oa{sa{sv}}}")
3314
 
            def GetManagedObjects(self):
3315
 
                """D-Bus method"""
3316
 
                return dbus.Dictionary(
3317
 
                    {client.dbus_object_path:
3318
 
                     dbus.Dictionary(
3319
 
                         {interface: client.GetAll(interface)
3320
 
                          for interface in
3321
 
                          client._get_all_interface_names()})
3322
 
                     for client in tcp_server.clients.values()})
3323
 
 
3324
 
            def client_added_signal(self, client):
3325
 
                """Send the new standard signal and the old signal"""
3326
 
                if use_dbus:
3327
 
                    # New standard signal
3328
 
                    self.InterfacesAdded(
3329
 
                        client.dbus_object_path,
3330
 
                        dbus.Dictionary(
3331
 
                            {interface: client.GetAll(interface)
3332
 
                             for interface in
3333
 
                             client._get_all_interface_names()}))
3334
 
                    # Old signal
3335
 
                    self.ClientAdded(client.dbus_object_path)
3336
 
 
3337
 
            def client_removed_signal(self, client):
3338
 
                """Send the new standard signal and the old signal"""
3339
 
                if use_dbus:
3340
 
                    # New standard signal
3341
 
                    self.InterfacesRemoved(
3342
 
                        client.dbus_object_path,
3343
 
                        client._get_all_interface_names())
3344
 
                    # Old signal
3345
 
                    self.ClientRemoved(client.dbus_object_path,
3346
 
                                       client.name)
3347
 
 
 
2812
        
3348
2813
        mandos_dbus_service = MandosDBusService()
3349
 
 
3350
 
    # Save modules to variables to exempt the modules from being
3351
 
    # unloaded before the function registered with atexit() is run.
3352
 
    mp = multiprocessing
3353
 
    wn = wnull
3354
 
 
 
2814
    
3355
2815
    def cleanup():
3356
2816
        "Cleanup function; run on exit"
3357
2817
        if zeroconf:
3358
2818
            service.cleanup()
3359
 
 
3360
 
        mp.active_children()
3361
 
        wn.close()
 
2819
        
 
2820
        multiprocessing.active_children()
 
2821
        wnull.close()
3362
2822
        if not (tcp_server.clients or client_settings):
3363
2823
            return
3364
 
 
 
2824
        
3365
2825
        # Store client before exiting. Secrets are encrypted with key
3366
2826
        # based on what config file has. If config file is
3367
2827
        # removed/edited, old secret will thus be unrecovable.
3368
2828
        clients = {}
3369
2829
        with PGPEngine() as pgp:
3370
 
            for client in tcp_server.clients.values():
 
2830
            for client in tcp_server.clients.itervalues():
3371
2831
                key = client_settings[client.name]["secret"]
3372
2832
                client.encrypted_secret = pgp.encrypt(client.secret,
3373
2833
                                                      key)
3374
2834
                client_dict = {}
3375
 
 
 
2835
                
3376
2836
                # A list of attributes that can not be pickled
3377
2837
                # + secret.
3378
 
                exclude = {"bus", "changedstate", "secret",
3379
 
                           "checker", "server_settings"}
 
2838
                exclude = { "bus", "changedstate", "secret",
 
2839
                            "checker", "server_settings" }
3380
2840
                for name, typ in inspect.getmembers(dbus.service
3381
2841
                                                    .Object):
3382
2842
                    exclude.add(name)
3383
 
 
 
2843
                
3384
2844
                client_dict["encrypted_secret"] = (client
3385
2845
                                                   .encrypted_secret)
3386
2846
                for attr in client.client_structure:
3387
2847
                    if attr not in exclude:
3388
2848
                        client_dict[attr] = getattr(client, attr)
3389
 
 
 
2849
                
3390
2850
                clients[client.name] = client_dict
3391
2851
                del client_settings[client.name]["secret"]
3392
 
 
 
2852
        
3393
2853
        try:
3394
2854
            with tempfile.NamedTemporaryFile(
3395
2855
                    mode='wb',
3397
2857
                    prefix='clients-',
3398
2858
                    dir=os.path.dirname(stored_state_path),
3399
2859
                    delete=False) as stored_state:
3400
 
                pickle.dump((clients, client_settings), stored_state,
3401
 
                            protocol=2)
 
2860
                pickle.dump((clients, client_settings), stored_state)
3402
2861
                tempname = stored_state.name
3403
2862
            os.rename(tempname, stored_state_path)
3404
2863
        except (IOError, OSError) as e:
3414
2873
                logger.warning("Could not save persistent state:",
3415
2874
                               exc_info=e)
3416
2875
                raise
3417
 
 
 
2876
        
3418
2877
        # Delete all clients, and settings from config
3419
2878
        while tcp_server.clients:
3420
2879
            name, client = tcp_server.clients.popitem()
3421
2880
            if use_dbus:
3422
2881
                client.remove_from_connection()
3423
 
            # Don't signal the disabling
 
2882
            # Don't signal anything except ClientRemoved
3424
2883
            client.disable(quiet=True)
3425
 
            # Emit D-Bus signal for removal
3426
2884
            if use_dbus:
3427
 
                mandos_dbus_service.client_removed_signal(client)
 
2885
                # Emit D-Bus signal
 
2886
                mandos_dbus_service.ClientRemoved(
 
2887
                    client.dbus_object_path, client.name)
3428
2888
        client_settings.clear()
3429
 
 
 
2889
    
3430
2890
    atexit.register(cleanup)
3431
 
 
3432
 
    for client in tcp_server.clients.values():
 
2891
    
 
2892
    for client in tcp_server.clients.itervalues():
3433
2893
        if use_dbus:
3434
 
            # Emit D-Bus signal for adding
3435
 
            mandos_dbus_service.client_added_signal(client)
 
2894
            # Emit D-Bus signal
 
2895
            mandos_dbus_service.ClientAdded(client.dbus_object_path)
3436
2896
        # Need to initiate checking of clients
3437
2897
        if client.enabled:
3438
2898
            client.init_checker()
3439
 
 
 
2899
    
3440
2900
    tcp_server.enable()
3441
2901
    tcp_server.server_activate()
3442
 
 
 
2902
    
3443
2903
    # Find out what port we got
3444
2904
    if zeroconf:
3445
2905
        service.port = tcp_server.socket.getsockname()[1]
3450
2910
    else:                       # IPv4
3451
2911
        logger.info("Now listening on address %r, port %d",
3452
2912
                    *tcp_server.socket.getsockname())
3453
 
 
3454
 
    # service.interface = tcp_server.socket.getsockname()[3]
3455
 
 
 
2913
    
 
2914
    #service.interface = tcp_server.socket.getsockname()[3]
 
2915
    
3456
2916
    try:
3457
2917
        if zeroconf:
3458
2918
            # From the Avahi example code
3463
2923
                cleanup()
3464
2924
                sys.exit(1)
3465
2925
            # End of Avahi example code
3466
 
 
3467
 
        GLib.io_add_watch(tcp_server.fileno(), GLib.IO_IN,
3468
 
                          lambda *args, **kwargs:
3469
 
                          (tcp_server.handle_request
3470
 
                           (*args[2:], **kwargs) or True))
3471
 
 
 
2926
        
 
2927
        gobject.io_add_watch(tcp_server.fileno(), gobject.IO_IN,
 
2928
                             lambda *args, **kwargs:
 
2929
                             (tcp_server.handle_request
 
2930
                              (*args[2:], **kwargs) or True))
 
2931
        
3472
2932
        logger.debug("Starting main loop")
3473
2933
        main_loop.run()
3474
2934
    except AvahiError as error: