/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-03-12 20:23:15 UTC
  • Revision ID: teddy@recompile.se-20160312202315-hu7b87ivetlxqbw3
Server: Fix minor thing with Python 3 compatibility

Fix another small thing with unpickling string values.

* mandos (main): When restoring pickled client data, only decode byte
                 string for "host" key if it really is a byte string.

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