/mandos/release

To get this branch, use:
bzr branch http://bzr.recompile.se/loggerhead/mandos/release

« back to all changes in this revision

Viewing changes to mandos

  • Committer: Teddy Hogeborn
  • Date: 2016-03-23 07:11:22 UTC
  • mto: (237.7.594 trunk)
  • mto: This revision was merged to the branch mainline in revision 343.
  • Revision ID: teddy@recompile.se-20160323071122-55srtjdizr21rr7f
Use HTTPS in home page links

Since we have a real certificate now, change all links to the home
page to use HTTPS.

* README: Use HTTPS in home page links
* debian/control (Source: mandos/Homepage): - '' -
* debian/copyright (Source): - '' -
* intro.xml (SEE ALSO): - '' -
* mandos.lsm (Primary-site): - '' -

Show diffs side-by-side

added added

removed removed

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