/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 23:42:38 UTC
  • Revision ID: teddy@recompile.se-20160312234238-xdszntu18cfwife9
Server: Use python-gi instead of old python-gobject

The python-gobject module is old, deprecated, and replaced with the
python-gi (GObject Introspection) module; use that instead.

* debian/control (Source: mandos/Build-Depends-Indep): Change
  "python-gi | python-gobject" to "python-gi".
* mandos: Import "GLib" instead of "GObject"; change all users.
* mandos-monitor: - '' -

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