/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-06-03 18:24:51 UTC
  • Revision ID: teddy@recompile.se-20160603182451-l1hfhvi0wdf6sde1
mandos: Minor bug fix for Python 3

* mandos (ClientHandler.handle): The GnuTLS priority string needs to
                                 be encoded to a byte string

Reported-by: Valerio Bellizzomi <valerio@selnet.org>

Show diffs side-by-side

added added

removed removed

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