/mandos/trunk

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

« back to all changes in this revision

Viewing changes to mandos

  • Committer: Teddy Hogeborn
  • Date: 2019-02-10 08:41:14 UTC
  • Revision ID: teddy@recompile.se-20190210084114-u91mijrxtifvzra5
Bug fix: Only create TLS key with certtool, and read correct key file

* debian/mandos-client.postinst (create_keys): Remove any bad keys
                                               created by 1.8.0-1.
                                               Only create TLS keys if
                                               certtool succeeds.
* debian/mandos.postinst (configure): Remove any bad keys from
                                      clients.conf, and inform the
                                      user if any were found.
* debian/mandos.templates (mandos/removed_bad_key_ids): New message.
* mandos (MandosServer.handle_ipc): Do not trust a key_id with a known
                                    bad key ID.
* mandos-keygen (keygen): Only create TLS keys if certtool succeeds.
  (password): Bug fix: Generate key_id correctly, and only output
              key_id if TLS key exists.

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