/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: 2019-08-24 14:43:51 UTC
  • Revision ID: teddy@recompile.se-20190824144351-2y0l31jpj496vrtu
Server: Add scaffolding for tests

* mandos: Add code to run tests via the unittest module, similar to
          the code in mandos-ctl.  Also shut down logging on exit.

Show diffs side-by-side

added added

removed removed

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