/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-12-12 18:25:02 UTC
  • Revision ID: teddy@recompile.se-20161212182502-72seb9hxiu65cgwa
Add spaces around all '=' signs in all C code.

* plugin-runner.c: Add white space around all '=' signs.
* plugins.d/mandos-client.c: - '' -
* plugins.d/plymouth.c: - '' -

Show diffs side-by-side

added added

removed removed

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