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