/mandos/trunk

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

« back to all changes in this revision

Viewing changes to mandos

  • Committer: Teddy Hogeborn
  • Date: 2016-08-25 17:37:05 UTC
  • Revision ID: teddy@recompile.se-20160825173705-q2v6lban8ph9uw75
PEP8 compliance: mandos

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

Show diffs side-by-side

added added

removed removed

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