/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: 2016-08-25 17:37:05 UTC
  • Revision ID: teddy@recompile.se-20160825173705-q2v6lban8ph9uw75
PEP8 compliance: mandos

* mandos: Add PEP8 compliance (as per the "pycodestyle" tool).

Show diffs side-by-side

added added

removed removed

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