/mandos/trunk

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

« back to all changes in this revision

Viewing changes to mandos

  • Committer: Teddy Hogeborn
  • Date: 2013-10-13 01:49:18 UTC
  • Revision ID: teddy@recompile.se-20131013014918-08ybiy64qxy4ceza
* initramfs-tools-hook: Bug fix: Make sure the right version of GnuPG
                        is copied into the initramfs image.  Always
                        assume that GPGME is used to avoid searching
                        for it since the path might not be /usr/lib.
                        Thanks to Félix Sipma <felix+debian@gueux.org>
                        for the initial bug report, and also thanks to
                        Dick Middleton <dick@lingbrae.com> for some
                        more debugging.
* initramfs-unpack: New script to help with development and debugging.
                    It is only part of the source tree, it is not
                    installed.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
#!/usr/bin/python2.7
 
1
#!/usr/bin/python
2
2
# -*- mode: python; coding: utf-8 -*-
3
3
4
4
# Mandos server - give out binary blobs to connecting clients.
11
11
# "AvahiService" class, and some lines in "main".
12
12
13
13
# Everything else is
14
 
# Copyright © 2008-2015 Teddy Hogeborn
15
 
# Copyright © 2008-2015 Björn Påhlsson
 
14
# Copyright © 2008-2012 Teddy Hogeborn
 
15
# Copyright © 2008-2012 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
36
36
 
37
37
from future_builtins import *
38
38
 
39
 
try:
40
 
    import SocketServer as socketserver
41
 
except ImportError:
42
 
    import socketserver
 
39
import SocketServer as socketserver
43
40
import socket
44
41
import argparse
45
42
import datetime
46
43
import errno
47
 
try:
48
 
    import ConfigParser as configparser
49
 
except ImportError:
50
 
    import configparser
 
44
import gnutls.crypto
 
45
import gnutls.connection
 
46
import gnutls.errors
 
47
import gnutls.library.functions
 
48
import gnutls.library.constants
 
49
import gnutls.library.types
 
50
import ConfigParser as configparser
51
51
import sys
52
52
import re
53
53
import os
62
62
import struct
63
63
import fcntl
64
64
import functools
65
 
try:
66
 
    import cPickle as pickle
67
 
except ImportError:
68
 
    import pickle
 
65
import cPickle as pickle
69
66
import multiprocessing
70
67
import types
71
68
import binascii
72
69
import tempfile
73
70
import itertools
74
71
import collections
75
 
import codecs
76
72
 
77
73
import dbus
78
74
import dbus.service
79
 
try:
80
 
    import gobject
81
 
except ImportError:
82
 
    from gi.repository import GObject as gobject
 
75
import gobject
83
76
import avahi
84
77
from dbus.mainloop.glib import DBusGMainLoop
85
78
import ctypes
95
88
    except ImportError:
96
89
        SO_BINDTODEVICE = None
97
90
 
98
 
if sys.version_info.major == 2:
99
 
    str = unicode
100
 
 
101
 
version = "1.7.1"
 
91
version = "1.6.0"
102
92
stored_state_file = "clients.pickle"
103
93
 
104
94
logger = logging.getLogger()
105
 
syslogger = None
 
95
syslogger = (logging.handlers.SysLogHandler
 
96
             (facility = logging.handlers.SysLogHandler.LOG_DAEMON,
 
97
              address = str("/dev/log")))
106
98
 
107
99
try:
108
 
    if_nametoindex = ctypes.cdll.LoadLibrary(
109
 
        ctypes.util.find_library("c")).if_nametoindex
 
100
    if_nametoindex = (ctypes.cdll.LoadLibrary
 
101
                      (ctypes.util.find_library("c"))
 
102
                      .if_nametoindex)
110
103
except (OSError, AttributeError):
111
 
    
112
104
    def if_nametoindex(interface):
113
105
        "Get an interface index the hard way, i.e. using fcntl()"
114
106
        SIOCGIFINDEX = 0x8933  # From /usr/include/linux/sockios.h
115
107
        with contextlib.closing(socket.socket()) as s:
116
108
            ifreq = fcntl.ioctl(s, SIOCGIFINDEX,
117
 
                                struct.pack(b"16s16x", interface))
118
 
        interface_index = struct.unpack("I", ifreq[16:20])[0]
 
109
                                struct.pack(str("16s16x"),
 
110
                                            interface))
 
111
        interface_index = struct.unpack(str("I"),
 
112
                                        ifreq[16:20])[0]
119
113
        return interface_index
120
114
 
121
115
 
122
116
def initlogger(debug, level=logging.WARNING):
123
117
    """init logger and add loglevel"""
124
118
    
125
 
    global syslogger
126
 
    syslogger = (logging.handlers.SysLogHandler(
127
 
        facility = logging.handlers.SysLogHandler.LOG_DAEMON,
128
 
        address = "/dev/log"))
129
119
    syslogger.setFormatter(logging.Formatter
130
120
                           ('Mandos [%(process)d]: %(levelname)s:'
131
121
                            ' %(message)s'))
148
138
 
149
139
class PGPEngine(object):
150
140
    """A simple class for OpenPGP symmetric encryption & decryption"""
151
 
    
152
141
    def __init__(self):
153
142
        self.tempdir = tempfile.mkdtemp(prefix="mandos-")
154
143
        self.gnupgargs = ['--batch',
183
172
    def password_encode(self, password):
184
173
        # Passphrase can not be empty and can not contain newlines or
185
174
        # NUL bytes.  So we prefix it and hex encode it.
186
 
        encoded = b"mandos" + binascii.hexlify(password)
187
 
        if len(encoded) > 2048:
188
 
            # GnuPG can't handle long passwords, so encode differently
189
 
            encoded = (b"mandos" + password.replace(b"\\", b"\\\\")
190
 
                       .replace(b"\n", b"\\n")
191
 
                       .replace(b"\0", b"\\x00"))
192
 
        return encoded
 
175
        return b"mandos" + binascii.hexlify(password)
193
176
    
194
177
    def encrypt(self, data, password):
195
178
        passphrase = self.password_encode(password)
196
 
        with tempfile.NamedTemporaryFile(
197
 
                dir=self.tempdir) as passfile:
 
179
        with tempfile.NamedTemporaryFile(dir=self.tempdir
 
180
                                         ) as passfile:
198
181
            passfile.write(passphrase)
199
182
            passfile.flush()
200
183
            proc = subprocess.Popen(['gpg', '--symmetric',
211
194
    
212
195
    def decrypt(self, data, password):
213
196
        passphrase = self.password_encode(password)
214
 
        with tempfile.NamedTemporaryFile(
215
 
                dir = self.tempdir) as passfile:
 
197
        with tempfile.NamedTemporaryFile(dir = self.tempdir
 
198
                                         ) as passfile:
216
199
            passfile.write(passphrase)
217
200
            passfile.flush()
218
201
            proc = subprocess.Popen(['gpg', '--decrypt',
222
205
                                    stdin = subprocess.PIPE,
223
206
                                    stdout = subprocess.PIPE,
224
207
                                    stderr = subprocess.PIPE)
225
 
            decrypted_plaintext, err = proc.communicate(input = data)
 
208
            decrypted_plaintext, err = proc.communicate(input
 
209
                                                        = data)
226
210
        if proc.returncode != 0:
227
211
            raise PGPError(err)
228
212
        return decrypted_plaintext
231
215
class AvahiError(Exception):
232
216
    def __init__(self, value, *args, **kwargs):
233
217
        self.value = value
234
 
        return super(AvahiError, self).__init__(value, *args,
235
 
                                                **kwargs)
236
 
 
 
218
        super(AvahiError, self).__init__(value, *args, **kwargs)
 
219
    def __unicode__(self):
 
220
        return unicode(repr(self.value))
237
221
 
238
222
class AvahiServiceError(AvahiError):
239
223
    pass
240
224
 
241
 
 
242
225
class AvahiGroupError(AvahiError):
243
226
    pass
244
227
 
264
247
    bus: dbus.SystemBus()
265
248
    """
266
249
    
267
 
    def __init__(self,
268
 
                 interface = avahi.IF_UNSPEC,
269
 
                 name = None,
270
 
                 servicetype = None,
271
 
                 port = None,
272
 
                 TXT = None,
273
 
                 domain = "",
274
 
                 host = "",
275
 
                 max_renames = 32768,
276
 
                 protocol = avahi.PROTO_UNSPEC,
277
 
                 bus = None):
 
250
    def __init__(self, interface = avahi.IF_UNSPEC, name = None,
 
251
                 servicetype = None, port = None, TXT = None,
 
252
                 domain = "", host = "", max_renames = 32768,
 
253
                 protocol = avahi.PROTO_UNSPEC, bus = None):
278
254
        self.interface = interface
279
255
        self.name = name
280
256
        self.type = servicetype
290
266
        self.bus = bus
291
267
        self.entry_group_state_changed_match = None
292
268
    
293
 
    def rename(self, remove=True):
 
269
    def rename(self):
294
270
        """Derived from the Avahi example code"""
295
271
        if self.rename_count >= self.max_renames:
296
272
            logger.critical("No suitable Zeroconf service name found"
297
273
                            " after %i retries, exiting.",
298
274
                            self.rename_count)
299
275
            raise AvahiServiceError("Too many renames")
300
 
        self.name = str(
301
 
            self.server.GetAlternativeServiceName(self.name))
302
 
        self.rename_count += 1
 
276
        self.name = unicode(self.server
 
277
                            .GetAlternativeServiceName(self.name))
303
278
        logger.info("Changing Zeroconf service name to %r ...",
304
279
                    self.name)
305
 
        if remove:
306
 
            self.remove()
 
280
        self.remove()
307
281
        try:
308
282
            self.add()
309
283
        except dbus.exceptions.DBusException as error:
310
 
            if (error.get_dbus_name()
311
 
                == "org.freedesktop.Avahi.CollisionError"):
312
 
                logger.info("Local Zeroconf service name collision.")
313
 
                return self.rename(remove=False)
314
 
            else:
315
 
                logger.critical("D-Bus Exception", exc_info=error)
316
 
                self.cleanup()
317
 
                os._exit(1)
 
284
            logger.critical("D-Bus Exception", exc_info=error)
 
285
            self.cleanup()
 
286
            os._exit(1)
 
287
        self.rename_count += 1
318
288
    
319
289
    def remove(self):
320
290
        """Derived from the Avahi example code"""
358
328
            self.rename()
359
329
        elif state == avahi.ENTRY_GROUP_FAILURE:
360
330
            logger.critical("Avahi: Error in group state changed %s",
361
 
                            str(error))
362
 
            raise AvahiGroupError("State changed: {!s}".format(error))
 
331
                            unicode(error))
 
332
            raise AvahiGroupError("State changed: {0!s}"
 
333
                                  .format(error))
363
334
    
364
335
    def cleanup(self):
365
336
        """Derived from the Avahi example code"""
375
346
    def server_state_changed(self, state, error=None):
376
347
        """Derived from the Avahi example code"""
377
348
        logger.debug("Avahi server state change: %i", state)
378
 
        bad_states = {
379
 
            avahi.SERVER_INVALID: "Zeroconf server invalid",
380
 
            avahi.SERVER_REGISTERING: None,
381
 
            avahi.SERVER_COLLISION: "Zeroconf server name collision",
382
 
            avahi.SERVER_FAILURE: "Zeroconf server failure",
383
 
        }
 
349
        bad_states = { avahi.SERVER_INVALID:
 
350
                           "Zeroconf server invalid",
 
351
                       avahi.SERVER_REGISTERING: None,
 
352
                       avahi.SERVER_COLLISION:
 
353
                           "Zeroconf server name collision",
 
354
                       avahi.SERVER_FAILURE:
 
355
                           "Zeroconf server failure" }
384
356
        if state in bad_states:
385
357
            if bad_states[state] is not None:
386
358
                if error is None:
389
361
                    logger.error(bad_states[state] + ": %r", error)
390
362
            self.cleanup()
391
363
        elif state == avahi.SERVER_RUNNING:
392
 
            try:
393
 
                self.add()
394
 
            except dbus.exceptions.DBusException as error:
395
 
                if (error.get_dbus_name()
396
 
                    == "org.freedesktop.Avahi.CollisionError"):
397
 
                    logger.info("Local Zeroconf service name"
398
 
                                " collision.")
399
 
                    return self.rename(remove=False)
400
 
                else:
401
 
                    logger.critical("D-Bus Exception", exc_info=error)
402
 
                    self.cleanup()
403
 
                    os._exit(1)
 
364
            self.add()
404
365
        else:
405
366
            if error is None:
406
367
                logger.debug("Unknown state: %r", state)
416
377
                                    follow_name_owner_changes=True),
417
378
                avahi.DBUS_INTERFACE_SERVER)
418
379
        self.server.connect_to_signal("StateChanged",
419
 
                                      self.server_state_changed)
 
380
                                 self.server_state_changed)
420
381
        self.server_state_changed(self.server.GetState())
421
382
 
422
383
 
423
384
class AvahiServiceToSyslog(AvahiService):
424
 
    def rename(self, *args, **kwargs):
 
385
    def rename(self):
425
386
        """Add the new name to the syslog messages"""
426
 
        ret = AvahiService.rename(self, *args, **kwargs)
427
 
        syslogger.setFormatter(logging.Formatter(
428
 
            'Mandos ({}) [%(process)d]: %(levelname)s: %(message)s'
429
 
            .format(self.name)))
 
387
        ret = AvahiService.rename(self)
 
388
        syslogger.setFormatter(logging.Formatter
 
389
                               ('Mandos ({0}) [%(process)d]:'
 
390
                                ' %(levelname)s: %(message)s'
 
391
                                .format(self.name)))
430
392
        return ret
431
393
 
432
 
# Pretend that we have a GnuTLS module
433
 
class GnuTLS(object):
434
 
    """This isn't so much a class as it is a module-like namespace.
435
 
    It is instantiated once, and simulates having a GnuTLS module."""
436
 
    
437
 
    _library = ctypes.cdll.LoadLibrary(
438
 
        ctypes.util.find_library("gnutls"))
439
 
    _need_version = "3.3.0"
440
 
    def __init__(self):
441
 
        # Need to use class name "GnuTLS" here, since this method is
442
 
        # called before the assignment to the "gnutls" global variable
443
 
        # happens.
444
 
        if GnuTLS.check_version(self._need_version) is None:
445
 
            raise GnuTLS.Error("Needs GnuTLS {} or later"
446
 
                               .format(self._need_version))
447
 
    
448
 
    # Unless otherwise indicated, the constants and types below are
449
 
    # all from the gnutls/gnutls.h C header file.
450
 
    
451
 
    # Constants
452
 
    E_SUCCESS = 0
453
 
    CRT_OPENPGP = 2
454
 
    CLIENT = 2
455
 
    SHUT_RDWR = 0
456
 
    CRD_CERTIFICATE = 1
457
 
    E_NO_CERTIFICATE_FOUND = -49
458
 
    OPENPGP_FMT_RAW = 0         # gnutls/openpgp.h
459
 
    
460
 
    # Types
461
 
    class session_int(ctypes.Structure):
462
 
        _fields_ = []
463
 
    session_t = ctypes.POINTER(session_int)
464
 
    class certificate_credentials_st(ctypes.Structure):
465
 
        _fields_ = []
466
 
    certificate_credentials_t = ctypes.POINTER(
467
 
        certificate_credentials_st)
468
 
    certificate_type_t = ctypes.c_int
469
 
    class datum_t(ctypes.Structure):
470
 
        _fields_ = [('data', ctypes.POINTER(ctypes.c_ubyte)),
471
 
                    ('size', ctypes.c_uint)]
472
 
    class openpgp_crt_int(ctypes.Structure):
473
 
        _fields_ = []
474
 
    openpgp_crt_t = ctypes.POINTER(openpgp_crt_int)
475
 
    openpgp_crt_fmt_t = ctypes.c_int # gnutls/openpgp.h
476
 
    log_func = ctypes.CFUNCTYPE(None, ctypes.c_int, ctypes.c_char_p)
477
 
    credentials_type_t = ctypes.c_int # 
478
 
    transport_ptr_t = ctypes.c_void_p
479
 
    close_request_t = ctypes.c_int
480
 
    
481
 
    # Exceptions
482
 
    class Error(Exception):
483
 
        # We need to use the class name "GnuTLS" here, since this
484
 
        # exception might be raised from within GnuTLS.__init__,
485
 
        # which is called before the assignment to the "gnutls"
486
 
        # global variable happens.
487
 
        def __init__(self, message = None, code = None, args=()):
488
 
            # Default usage is by a message string, but if a return
489
 
            # code is passed, convert it to a string with
490
 
            # gnutls.strerror()
491
 
            if message is None and code is not None:
492
 
                message = GnuTLS.strerror(code)
493
 
            return super(GnuTLS.Error, self).__init__(
494
 
                message, *args)
495
 
    
496
 
    class CertificateSecurityError(Error):
497
 
        pass
498
 
    
499
 
    # Classes
500
 
    class Credentials(object):
501
 
        def __init__(self):
502
 
            self._c_object = gnutls.certificate_credentials_t()
503
 
            gnutls.certificate_allocate_credentials(
504
 
                ctypes.byref(self._c_object))
505
 
            self.type = gnutls.CRD_CERTIFICATE
506
 
        
507
 
        def __del__(self):
508
 
            gnutls.certificate_free_credentials(self._c_object)
509
 
    
510
 
    class ClientSession(object):
511
 
        def __init__(self, socket, credentials = None):
512
 
            self._c_object = gnutls.session_t()
513
 
            gnutls.init(ctypes.byref(self._c_object), gnutls.CLIENT)
514
 
            gnutls.set_default_priority(self._c_object)
515
 
            gnutls.transport_set_ptr(self._c_object, socket.fileno())
516
 
            gnutls.handshake_set_private_extensions(self._c_object,
517
 
                                                    True)
518
 
            self.socket = socket
519
 
            if credentials is None:
520
 
                credentials = gnutls.Credentials()
521
 
            gnutls.credentials_set(self._c_object, credentials.type,
522
 
                                   ctypes.cast(credentials._c_object,
523
 
                                               ctypes.c_void_p))
524
 
            self.credentials = credentials
525
 
        
526
 
        def __del__(self):
527
 
            gnutls.deinit(self._c_object)
528
 
        
529
 
        def handshake(self):
530
 
            return gnutls.handshake(self._c_object)
531
 
        
532
 
        def send(self, data):
533
 
            data = bytes(data)
534
 
            if not data:
535
 
                return 0
536
 
            return gnutls.record_send(self._c_object, data, len(data))
537
 
        
538
 
        def bye(self):
539
 
            return gnutls.bye(self._c_object, gnutls.SHUT_RDWR)
540
 
    
541
 
    # Error handling function
542
 
    def _error_code(result):
543
 
        """A function to raise exceptions on errors, suitable
544
 
        for the 'restype' attribute on ctypes functions"""
545
 
        if result >= 0:
546
 
            return result
547
 
        if result == gnutls.E_NO_CERTIFICATE_FOUND:
548
 
            raise gnutls.CertificateSecurityError(code = result)
549
 
        raise gnutls.Error(code = result)
550
 
    
551
 
    # Unless otherwise indicated, the function declarations below are
552
 
    # all from the gnutls/gnutls.h C header file.
553
 
    
554
 
    # Functions
555
 
    priority_set_direct = _library.gnutls_priority_set_direct
556
 
    priority_set_direct.argtypes = [session_t, ctypes.c_char_p,
557
 
                                    ctypes.POINTER(ctypes.c_char_p)]
558
 
    priority_set_direct.restype = _error_code
559
 
    
560
 
    init = _library.gnutls_init
561
 
    init.argtypes = [ctypes.POINTER(session_t), ctypes.c_int]
562
 
    init.restype = _error_code
563
 
    
564
 
    set_default_priority = _library.gnutls_set_default_priority
565
 
    set_default_priority.argtypes = [session_t]
566
 
    set_default_priority.restype = _error_code
567
 
    
568
 
    record_send = _library.gnutls_record_send
569
 
    record_send.argtypes = [session_t, ctypes.c_void_p,
570
 
                            ctypes.c_size_t]
571
 
    record_send.restype = ctypes.c_ssize_t
572
 
    
573
 
    certificate_allocate_credentials = (
574
 
        _library.gnutls_certificate_allocate_credentials)
575
 
    certificate_allocate_credentials.argtypes = [
576
 
        ctypes.POINTER(certificate_credentials_t)]
577
 
    certificate_allocate_credentials.restype = _error_code
578
 
    
579
 
    certificate_free_credentials = (
580
 
        _library.gnutls_certificate_free_credentials)
581
 
    certificate_free_credentials.argtypes = [certificate_credentials_t]
582
 
    certificate_free_credentials.restype = None
583
 
    
584
 
    handshake_set_private_extensions = (
585
 
        _library.gnutls_handshake_set_private_extensions)
586
 
    handshake_set_private_extensions.argtypes = [session_t,
587
 
                                                 ctypes.c_int]
588
 
    handshake_set_private_extensions.restype = None
589
 
    
590
 
    credentials_set = _library.gnutls_credentials_set
591
 
    credentials_set.argtypes = [session_t, credentials_type_t,
592
 
                                ctypes.c_void_p]
593
 
    credentials_set.restype = _error_code
594
 
    
595
 
    strerror = _library.gnutls_strerror
596
 
    strerror.argtypes = [ctypes.c_int]
597
 
    strerror.restype = ctypes.c_char_p
598
 
    
599
 
    certificate_type_get = _library.gnutls_certificate_type_get
600
 
    certificate_type_get.argtypes = [session_t]
601
 
    certificate_type_get.restype = _error_code
602
 
    
603
 
    certificate_get_peers = _library.gnutls_certificate_get_peers
604
 
    certificate_get_peers.argtypes = [session_t,
605
 
                                      ctypes.POINTER(ctypes.c_uint)]
606
 
    certificate_get_peers.restype = ctypes.POINTER(datum_t)
607
 
    
608
 
    global_set_log_level = _library.gnutls_global_set_log_level
609
 
    global_set_log_level.argtypes = [ctypes.c_int]
610
 
    global_set_log_level.restype = None
611
 
    
612
 
    global_set_log_function = _library.gnutls_global_set_log_function
613
 
    global_set_log_function.argtypes = [log_func]
614
 
    global_set_log_function.restype = None
615
 
    
616
 
    deinit = _library.gnutls_deinit
617
 
    deinit.argtypes = [session_t]
618
 
    deinit.restype = None
619
 
    
620
 
    handshake = _library.gnutls_handshake
621
 
    handshake.argtypes = [session_t]
622
 
    handshake.restype = _error_code
623
 
    
624
 
    transport_set_ptr = _library.gnutls_transport_set_ptr
625
 
    transport_set_ptr.argtypes = [session_t, transport_ptr_t]
626
 
    transport_set_ptr.restype = None
627
 
    
628
 
    bye = _library.gnutls_bye
629
 
    bye.argtypes = [session_t, close_request_t]
630
 
    bye.restype = _error_code
631
 
    
632
 
    check_version = _library.gnutls_check_version
633
 
    check_version.argtypes = [ctypes.c_char_p]
634
 
    check_version.restype = ctypes.c_char_p
635
 
    
636
 
    # All the function declarations below are from gnutls/openpgp.h
637
 
    
638
 
    openpgp_crt_init = _library.gnutls_openpgp_crt_init
639
 
    openpgp_crt_init.argtypes = [ctypes.POINTER(openpgp_crt_t)]
640
 
    openpgp_crt_init.restype = _error_code
641
 
    
642
 
    openpgp_crt_import = _library.gnutls_openpgp_crt_import
643
 
    openpgp_crt_import.argtypes = [openpgp_crt_t,
644
 
                                   ctypes.POINTER(datum_t),
645
 
                                   openpgp_crt_fmt_t]
646
 
    openpgp_crt_import.restype = _error_code
647
 
    
648
 
    openpgp_crt_verify_self = _library.gnutls_openpgp_crt_verify_self
649
 
    openpgp_crt_verify_self.argtypes = [openpgp_crt_t, ctypes.c_uint,
650
 
                                        ctypes.POINTER(ctypes.c_uint)]
651
 
    openpgp_crt_verify_self.restype = _error_code
652
 
    
653
 
    openpgp_crt_deinit = _library.gnutls_openpgp_crt_deinit
654
 
    openpgp_crt_deinit.argtypes = [openpgp_crt_t]
655
 
    openpgp_crt_deinit.restype = None
656
 
    
657
 
    openpgp_crt_get_fingerprint = (
658
 
        _library.gnutls_openpgp_crt_get_fingerprint)
659
 
    openpgp_crt_get_fingerprint.argtypes = [openpgp_crt_t,
660
 
                                            ctypes.c_void_p,
661
 
                                            ctypes.POINTER(
662
 
                                                ctypes.c_size_t)]
663
 
    openpgp_crt_get_fingerprint.restype = _error_code
664
 
    
665
 
    # Remove non-public function
666
 
    del _error_code
667
 
# Create the global "gnutls" object, simulating a module
668
 
gnutls = GnuTLS()
669
 
 
670
 
def call_pipe(connection,       # : multiprocessing.Connection
671
 
              func, *args, **kwargs):
672
 
    """This function is meant to be called by multiprocessing.Process
673
 
    
674
 
    This function runs func(*args, **kwargs), and writes the resulting
675
 
    return value on the provided multiprocessing.Connection.
676
 
    """
677
 
    connection.send(func(*args, **kwargs))
678
 
    connection.close()
 
394
 
 
395
def timedelta_to_milliseconds(td):
 
396
    "Convert a datetime.timedelta() to milliseconds"
 
397
    return ((td.days * 24 * 60 * 60 * 1000)
 
398
            + (td.seconds * 1000)
 
399
            + (td.microseconds // 1000))
 
400
 
679
401
 
680
402
class Client(object):
681
403
    """A representation of a client host served by this server.
708
430
    last_checker_status: integer between 0 and 255 reflecting exit
709
431
                         status of last checker. -1 reflects crashed
710
432
                         checker, -2 means no checker completed yet.
711
 
    last_checker_signal: The signal which killed the last checker, if
712
 
                         last_checker_status is -1
713
433
    last_enabled: datetime.datetime(); (UTC) or None
714
434
    name:       string; from the config file, used in log messages and
715
435
                        D-Bus identifiers
728
448
                          "fingerprint", "host", "interval",
729
449
                          "last_approval_request", "last_checked_ok",
730
450
                          "last_enabled", "name", "timeout")
731
 
    client_defaults = {
732
 
        "timeout": "PT5M",
733
 
        "extended_timeout": "PT15M",
734
 
        "interval": "PT2M",
735
 
        "checker": "fping -q -- %%(host)s",
736
 
        "host": "",
737
 
        "approval_delay": "PT0S",
738
 
        "approval_duration": "PT1S",
739
 
        "approved_by_default": "True",
740
 
        "enabled": "True",
741
 
    }
 
451
    client_defaults = { "timeout": "PT5M",
 
452
                        "extended_timeout": "PT15M",
 
453
                        "interval": "PT2M",
 
454
                        "checker": "fping -q -- %%(host)s",
 
455
                        "host": "",
 
456
                        "approval_delay": "PT0S",
 
457
                        "approval_duration": "PT1S",
 
458
                        "approved_by_default": "True",
 
459
                        "enabled": "True",
 
460
                        }
 
461
    
 
462
    def timeout_milliseconds(self):
 
463
        "Return the 'timeout' attribute in milliseconds"
 
464
        return timedelta_to_milliseconds(self.timeout)
 
465
    
 
466
    def extended_timeout_milliseconds(self):
 
467
        "Return the 'extended_timeout' attribute in milliseconds"
 
468
        return timedelta_to_milliseconds(self.extended_timeout)
 
469
    
 
470
    def interval_milliseconds(self):
 
471
        "Return the 'interval' attribute in milliseconds"
 
472
        return timedelta_to_milliseconds(self.interval)
 
473
    
 
474
    def approval_delay_milliseconds(self):
 
475
        return timedelta_to_milliseconds(self.approval_delay)
742
476
    
743
477
    @staticmethod
744
478
    def config_parser(config):
760
494
            client["enabled"] = config.getboolean(client_name,
761
495
                                                  "enabled")
762
496
            
763
 
            # Uppercase and remove spaces from fingerprint for later
764
 
            # comparison purposes with return value from the
765
 
            # fingerprint() function
766
497
            client["fingerprint"] = (section["fingerprint"].upper()
767
498
                                     .replace(" ", ""))
768
499
            if "secret" in section:
773
504
                          "rb") as secfile:
774
505
                    client["secret"] = secfile.read()
775
506
            else:
776
 
                raise TypeError("No secret or secfile for section {}"
 
507
                raise TypeError("No secret or secfile for section {0}"
777
508
                                .format(section))
778
509
            client["timeout"] = string_to_delta(section["timeout"])
779
510
            client["extended_timeout"] = string_to_delta(
796
527
            server_settings = {}
797
528
        self.server_settings = server_settings
798
529
        # adding all client settings
799
 
        for setting, value in settings.items():
 
530
        for setting, value in settings.iteritems():
800
531
            setattr(self, setting, value)
801
532
        
802
533
        if self.enabled:
810
541
            self.expires = None
811
542
        
812
543
        logger.debug("Creating client %r", self.name)
 
544
        # Uppercase and remove spaces from fingerprint for later
 
545
        # comparison purposes with return value from the fingerprint()
 
546
        # function
813
547
        logger.debug("  Fingerprint: %s", self.fingerprint)
814
548
        self.created = settings.get("created",
815
549
                                    datetime.datetime.utcnow())
822
556
        self.current_checker_command = None
823
557
        self.approved = None
824
558
        self.approvals_pending = 0
825
 
        self.changedstate = multiprocessing_manager.Condition(
826
 
            multiprocessing_manager.Lock())
827
 
        self.client_structure = [attr
828
 
                                 for attr in self.__dict__.iterkeys()
 
559
        self.changedstate = (multiprocessing_manager
 
560
                             .Condition(multiprocessing_manager
 
561
                                        .Lock()))
 
562
        self.client_structure = [attr for attr in
 
563
                                 self.__dict__.iterkeys()
829
564
                                 if not attr.startswith("_")]
830
565
        self.client_structure.append("client_structure")
831
566
        
832
 
        for name, t in inspect.getmembers(
833
 
                type(self), lambda obj: isinstance(obj, property)):
 
567
        for name, t in inspect.getmembers(type(self),
 
568
                                          lambda obj:
 
569
                                              isinstance(obj,
 
570
                                                         property)):
834
571
            if not name.startswith("_"):
835
572
                self.client_structure.append(name)
836
573
    
878
615
        # and every interval from then on.
879
616
        if self.checker_initiator_tag is not None:
880
617
            gobject.source_remove(self.checker_initiator_tag)
881
 
        self.checker_initiator_tag = gobject.timeout_add(
882
 
            int(self.interval.total_seconds() * 1000),
883
 
            self.start_checker)
 
618
        self.checker_initiator_tag = (gobject.timeout_add
 
619
                                      (self.interval_milliseconds(),
 
620
                                       self.start_checker))
884
621
        # Schedule a disable() when 'timeout' has passed
885
622
        if self.disable_initiator_tag is not None:
886
623
            gobject.source_remove(self.disable_initiator_tag)
887
 
        self.disable_initiator_tag = gobject.timeout_add(
888
 
            int(self.timeout.total_seconds() * 1000), self.disable)
 
624
        self.disable_initiator_tag = (gobject.timeout_add
 
625
                                   (self.timeout_milliseconds(),
 
626
                                    self.disable))
889
627
        # Also start a new checker *right now*.
890
628
        self.start_checker()
891
629
    
892
 
    def checker_callback(self, source, condition, connection,
893
 
                         command):
 
630
    def checker_callback(self, pid, condition, command):
894
631
        """The checker has completed, so take appropriate actions."""
895
632
        self.checker_callback_tag = None
896
633
        self.checker = None
897
 
        # Read return code from connection (see call_pipe)
898
 
        returncode = connection.recv()
899
 
        connection.close()
900
 
        
901
 
        if returncode >= 0:
902
 
            self.last_checker_status = returncode
903
 
            self.last_checker_signal = None
 
634
        if os.WIFEXITED(condition):
 
635
            self.last_checker_status = os.WEXITSTATUS(condition)
904
636
            if self.last_checker_status == 0:
905
637
                logger.info("Checker for %(name)s succeeded",
906
638
                            vars(self))
907
639
                self.checked_ok()
908
640
            else:
909
 
                logger.info("Checker for %(name)s failed", vars(self))
 
641
                logger.info("Checker for %(name)s failed",
 
642
                            vars(self))
910
643
        else:
911
644
            self.last_checker_status = -1
912
 
            self.last_checker_signal = -returncode
913
645
            logger.warning("Checker for %(name)s crashed?",
914
646
                           vars(self))
915
 
        return False
916
647
    
917
648
    def checked_ok(self):
918
649
        """Assert that the client has been seen, alive and well."""
919
650
        self.last_checked_ok = datetime.datetime.utcnow()
920
651
        self.last_checker_status = 0
921
 
        self.last_checker_signal = None
922
652
        self.bump_timeout()
923
653
    
924
654
    def bump_timeout(self, timeout=None):
929
659
            gobject.source_remove(self.disable_initiator_tag)
930
660
            self.disable_initiator_tag = None
931
661
        if getattr(self, "enabled", False):
932
 
            self.disable_initiator_tag = gobject.timeout_add(
933
 
                int(timeout.total_seconds() * 1000), self.disable)
 
662
            self.disable_initiator_tag = (gobject.timeout_add
 
663
                                          (timedelta_to_milliseconds
 
664
                                           (timeout), self.disable))
934
665
            self.expires = datetime.datetime.utcnow() + timeout
935
666
    
936
667
    def need_approval(self):
950
681
        # than 'timeout' for the client to be disabled, which is as it
951
682
        # should be.
952
683
        
953
 
        if self.checker is not None and not self.checker.is_alive():
954
 
            logger.warning("Checker was not alive; joining")
955
 
            self.checker.join()
956
 
            self.checker = None
 
684
        # If a checker exists, make sure it is not a zombie
 
685
        try:
 
686
            pid, status = os.waitpid(self.checker.pid, os.WNOHANG)
 
687
        except (AttributeError, OSError) as error:
 
688
            if (isinstance(error, OSError)
 
689
                and error.errno != errno.ECHILD):
 
690
                raise error
 
691
        else:
 
692
            if pid:
 
693
                logger.warning("Checker was a zombie")
 
694
                gobject.source_remove(self.checker_callback_tag)
 
695
                self.checker_callback(pid, status,
 
696
                                      self.current_checker_command)
957
697
        # Start a new checker if needed
958
698
        if self.checker is None:
959
699
            # Escape attributes for the shell
960
 
            escaped_attrs = {
961
 
                attr: re.escape(str(getattr(self, attr)))
962
 
                for attr in self.runtime_expansions }
 
700
            escaped_attrs = dict(
 
701
                (attr, re.escape(unicode(getattr(self, attr))))
 
702
                for attr in
 
703
                self.runtime_expansions)
963
704
            try:
964
705
                command = self.checker_command % escaped_attrs
965
706
            except TypeError as error:
966
707
                logger.error('Could not format string "%s"',
967
 
                             self.checker_command,
 
708
                             self.checker_command, exc_info=error)
 
709
                return True # Try again later
 
710
            self.current_checker_command = command
 
711
            try:
 
712
                logger.info("Starting checker %r for %s",
 
713
                            command, self.name)
 
714
                # We don't need to redirect stdout and stderr, since
 
715
                # in normal mode, that is already done by daemon(),
 
716
                # and in debug mode we don't want to.  (Stdin is
 
717
                # always replaced by /dev/null.)
 
718
                # The exception is when not debugging but nevertheless
 
719
                # running in the foreground; use the previously
 
720
                # created wnull.
 
721
                popen_args = {}
 
722
                if (not self.server_settings["debug"]
 
723
                    and self.server_settings["foreground"]):
 
724
                    popen_args.update({"stdout": wnull,
 
725
                                       "stderr": wnull })
 
726
                self.checker = subprocess.Popen(command,
 
727
                                                close_fds=True,
 
728
                                                shell=True, cwd="/",
 
729
                                                **popen_args)
 
730
            except OSError as error:
 
731
                logger.error("Failed to start subprocess",
968
732
                             exc_info=error)
969
 
                return True     # Try again later
970
 
            self.current_checker_command = command
971
 
            logger.info("Starting checker %r for %s", command,
972
 
                        self.name)
973
 
            # We don't need to redirect stdout and stderr, since
974
 
            # in normal mode, that is already done by daemon(),
975
 
            # and in debug mode we don't want to.  (Stdin is
976
 
            # always replaced by /dev/null.)
977
 
            # The exception is when not debugging but nevertheless
978
 
            # running in the foreground; use the previously
979
 
            # created wnull.
980
 
            popen_args = { "close_fds": True,
981
 
                           "shell": True,
982
 
                           "cwd": "/" }
983
 
            if (not self.server_settings["debug"]
984
 
                and self.server_settings["foreground"]):
985
 
                popen_args.update({"stdout": wnull,
986
 
                                   "stderr": wnull })
987
 
            pipe = multiprocessing.Pipe(duplex = False)
988
 
            self.checker = multiprocessing.Process(
989
 
                target = call_pipe,
990
 
                args = (pipe[1], subprocess.call, command),
991
 
                kwargs = popen_args)
992
 
            self.checker.start()
993
 
            self.checker_callback_tag = gobject.io_add_watch(
994
 
                pipe[0].fileno(), gobject.IO_IN,
995
 
                self.checker_callback, pipe[0], command)
 
733
                return True
 
734
            self.checker_callback_tag = (gobject.child_watch_add
 
735
                                         (self.checker.pid,
 
736
                                          self.checker_callback,
 
737
                                          data=command))
 
738
            # The checker may have completed before the gobject
 
739
            # watch was added.  Check for this.
 
740
            try:
 
741
                pid, status = os.waitpid(self.checker.pid, os.WNOHANG)
 
742
            except OSError as error:
 
743
                if error.errno == errno.ECHILD:
 
744
                    # This should never happen
 
745
                    logger.error("Child process vanished",
 
746
                                 exc_info=error)
 
747
                    return True
 
748
                raise
 
749
            if pid:
 
750
                gobject.source_remove(self.checker_callback_tag)
 
751
                self.checker_callback(pid, status, command)
996
752
        # Re-run this periodically if run by gobject.timeout_add
997
753
        return True
998
754
    
1004
760
        if getattr(self, "checker", None) is None:
1005
761
            return
1006
762
        logger.debug("Stopping checker for %(name)s", vars(self))
1007
 
        self.checker.terminate()
 
763
        try:
 
764
            self.checker.terminate()
 
765
            #time.sleep(0.5)
 
766
            #if self.checker.poll() is None:
 
767
            #    self.checker.kill()
 
768
        except OSError as error:
 
769
            if error.errno != errno.ESRCH: # No such process
 
770
                raise
1008
771
        self.checker = None
1009
772
 
1010
773
 
1011
 
def dbus_service_property(dbus_interface,
1012
 
                          signature="v",
1013
 
                          access="readwrite",
1014
 
                          byte_arrays=False):
 
774
def dbus_service_property(dbus_interface, signature="v",
 
775
                          access="readwrite", byte_arrays=False):
1015
776
    """Decorators for marking methods of a DBusObjectWithProperties to
1016
777
    become properties on the D-Bus.
1017
778
    
1026
787
    # "Set" method, so we fail early here:
1027
788
    if byte_arrays and signature != "ay":
1028
789
        raise ValueError("Byte arrays not supported for non-'ay'"
1029
 
                         " signature {!r}".format(signature))
1030
 
    
 
790
                         " signature {0!r}".format(signature))
1031
791
    def decorator(func):
1032
792
        func._dbus_is_property = True
1033
793
        func._dbus_interface = dbus_interface
1038
798
            func._dbus_name = func._dbus_name[:-14]
1039
799
        func._dbus_get_args_options = {'byte_arrays': byte_arrays }
1040
800
        return func
1041
 
    
1042
801
    return decorator
1043
802
 
1044
803
 
1053
812
                "org.freedesktop.DBus.Property.EmitsChangedSignal":
1054
813
                    "false"}
1055
814
    """
1056
 
    
1057
815
    def decorator(func):
1058
816
        func._dbus_is_interface = True
1059
817
        func._dbus_interface = dbus_interface
1060
818
        func._dbus_name = dbus_interface
1061
819
        return func
1062
 
    
1063
820
    return decorator
1064
821
 
1065
822
 
1067
824
    """Decorator to annotate D-Bus methods, signals or properties
1068
825
    Usage:
1069
826
    
1070
 
    @dbus_annotations({"org.freedesktop.DBus.Deprecated": "true",
1071
 
                       "org.freedesktop.DBus.Property."
1072
 
                       "EmitsChangedSignal": "false"})
1073
827
    @dbus_service_property("org.example.Interface", signature="b",
1074
828
                           access="r")
 
829
    @dbus_annotations({{"org.freedesktop.DBus.Deprecated": "true",
 
830
                        "org.freedesktop.DBus.Property."
 
831
                        "EmitsChangedSignal": "false"})
1075
832
    def Property_dbus_property(self):
1076
833
        return dbus.Boolean(False)
1077
 
    
1078
 
    See also the DBusObjectWithAnnotations class.
1079
834
    """
1080
 
    
1081
835
    def decorator(func):
1082
836
        func._dbus_annotations = annotations
1083
837
        return func
1084
 
    
1085
838
    return decorator
1086
839
 
1087
840
 
1088
841
class DBusPropertyException(dbus.exceptions.DBusException):
1089
842
    """A base class for D-Bus property-related exceptions
1090
843
    """
1091
 
    pass
 
844
    def __unicode__(self):
 
845
        return unicode(str(self))
1092
846
 
1093
847
 
1094
848
class DBusPropertyAccessException(DBusPropertyException):
1103
857
    pass
1104
858
 
1105
859
 
1106
 
class DBusObjectWithAnnotations(dbus.service.Object):
1107
 
    """A D-Bus object with annotations.
 
860
class DBusObjectWithProperties(dbus.service.Object):
 
861
    """A D-Bus object with properties.
1108
862
    
1109
 
    Classes inheriting from this can use the dbus_annotations
1110
 
    decorator to add annotations to methods or signals.
 
863
    Classes inheriting from this can use the dbus_service_property
 
864
    decorator to expose methods as D-Bus properties.  It exposes the
 
865
    standard Get(), Set(), and GetAll() methods on the D-Bus.
1111
866
    """
1112
867
    
1113
868
    @staticmethod
1117
872
        If called like _is_dbus_thing("method") it returns a function
1118
873
        suitable for use as predicate to inspect.getmembers().
1119
874
        """
1120
 
        return lambda obj: getattr(obj, "_dbus_is_{}".format(thing),
 
875
        return lambda obj: getattr(obj, "_dbus_is_{0}".format(thing),
1121
876
                                   False)
1122
877
    
1123
878
    def _get_all_dbus_things(self, thing):
1124
879
        """Returns a generator of (name, attribute) pairs
1125
880
        """
1126
 
        return ((getattr(athing.__get__(self), "_dbus_name", name),
 
881
        return ((getattr(athing.__get__(self), "_dbus_name",
 
882
                         name),
1127
883
                 athing.__get__(self))
1128
884
                for cls in self.__class__.__mro__
1129
885
                for name, athing in
1130
 
                inspect.getmembers(cls, self._is_dbus_thing(thing)))
1131
 
    
1132
 
    @dbus.service.method(dbus.INTROSPECTABLE_IFACE,
1133
 
                         out_signature = "s",
1134
 
                         path_keyword = 'object_path',
1135
 
                         connection_keyword = 'connection')
1136
 
    def Introspect(self, object_path, connection):
1137
 
        """Overloading of standard D-Bus method.
1138
 
        
1139
 
        Inserts annotation tags on methods and signals.
1140
 
        """
1141
 
        xmlstring = dbus.service.Object.Introspect(self, object_path,
1142
 
                                                   connection)
1143
 
        try:
1144
 
            document = xml.dom.minidom.parseString(xmlstring)
1145
 
            
1146
 
            for if_tag in document.getElementsByTagName("interface"):
1147
 
                # Add annotation tags
1148
 
                for typ in ("method", "signal"):
1149
 
                    for tag in if_tag.getElementsByTagName(typ):
1150
 
                        annots = dict()
1151
 
                        for name, prop in (self.
1152
 
                                           _get_all_dbus_things(typ)):
1153
 
                            if (name == tag.getAttribute("name")
1154
 
                                and prop._dbus_interface
1155
 
                                == if_tag.getAttribute("name")):
1156
 
                                annots.update(getattr(
1157
 
                                    prop, "_dbus_annotations", {}))
1158
 
                        for name, value in annots.items():
1159
 
                            ann_tag = document.createElement(
1160
 
                                "annotation")
1161
 
                            ann_tag.setAttribute("name", name)
1162
 
                            ann_tag.setAttribute("value", value)
1163
 
                            tag.appendChild(ann_tag)
1164
 
                # Add interface annotation tags
1165
 
                for annotation, value in dict(
1166
 
                    itertools.chain.from_iterable(
1167
 
                        annotations().items()
1168
 
                        for name, annotations
1169
 
                        in self._get_all_dbus_things("interface")
1170
 
                        if name == if_tag.getAttribute("name")
1171
 
                        )).items():
1172
 
                    ann_tag = document.createElement("annotation")
1173
 
                    ann_tag.setAttribute("name", annotation)
1174
 
                    ann_tag.setAttribute("value", value)
1175
 
                    if_tag.appendChild(ann_tag)
1176
 
                # Fix argument name for the Introspect method itself
1177
 
                if (if_tag.getAttribute("name")
1178
 
                                == dbus.INTROSPECTABLE_IFACE):
1179
 
                    for cn in if_tag.getElementsByTagName("method"):
1180
 
                        if cn.getAttribute("name") == "Introspect":
1181
 
                            for arg in cn.getElementsByTagName("arg"):
1182
 
                                if (arg.getAttribute("direction")
1183
 
                                    == "out"):
1184
 
                                    arg.setAttribute("name",
1185
 
                                                     "xml_data")
1186
 
            xmlstring = document.toxml("utf-8")
1187
 
            document.unlink()
1188
 
        except (AttributeError, xml.dom.DOMException,
1189
 
                xml.parsers.expat.ExpatError) as error:
1190
 
            logger.error("Failed to override Introspection method",
1191
 
                         exc_info=error)
1192
 
        return xmlstring
1193
 
 
1194
 
 
1195
 
class DBusObjectWithProperties(DBusObjectWithAnnotations):
1196
 
    """A D-Bus object with properties.
1197
 
    
1198
 
    Classes inheriting from this can use the dbus_service_property
1199
 
    decorator to expose methods as D-Bus properties.  It exposes the
1200
 
    standard Get(), Set(), and GetAll() methods on the D-Bus.
1201
 
    """
 
886
                inspect.getmembers(cls,
 
887
                                   self._is_dbus_thing(thing)))
1202
888
    
1203
889
    def _get_dbus_property(self, interface_name, property_name):
1204
890
        """Returns a bound method if one exists which is a D-Bus
1205
891
        property with the specified name and interface.
1206
892
        """
1207
 
        for cls in self.__class__.__mro__:
1208
 
            for name, value in inspect.getmembers(
1209
 
                    cls, self._is_dbus_thing("property")):
 
893
        for cls in  self.__class__.__mro__:
 
894
            for name, value in (inspect.getmembers
 
895
                                (cls,
 
896
                                 self._is_dbus_thing("property"))):
1210
897
                if (value._dbus_name == property_name
1211
898
                    and value._dbus_interface == interface_name):
1212
899
                    return value.__get__(self)
1213
900
        
1214
901
        # No such property
1215
 
        raise DBusPropertyNotFound("{}:{}.{}".format(
1216
 
            self.dbus_object_path, interface_name, property_name))
1217
 
    
1218
 
    @classmethod
1219
 
    def _get_all_interface_names(cls):
1220
 
        """Get a sequence of all interfaces supported by an object"""
1221
 
        return (name for name in set(getattr(getattr(x, attr),
1222
 
                                             "_dbus_interface", None)
1223
 
                                     for x in (inspect.getmro(cls))
1224
 
                                     for attr in dir(x))
1225
 
                if name is not None)
1226
 
    
1227
 
    @dbus.service.method(dbus.PROPERTIES_IFACE,
1228
 
                         in_signature="ss",
 
902
        raise DBusPropertyNotFound(self.dbus_object_path + ":"
 
903
                                   + interface_name + "."
 
904
                                   + property_name)
 
905
    
 
906
    @dbus.service.method(dbus.PROPERTIES_IFACE, in_signature="ss",
1229
907
                         out_signature="v")
1230
908
    def Get(self, interface_name, property_name):
1231
909
        """Standard D-Bus property Get() method, see D-Bus standard.
1249
927
            # The byte_arrays option is not supported yet on
1250
928
            # signatures other than "ay".
1251
929
            if prop._dbus_signature != "ay":
1252
 
                raise ValueError("Byte arrays not supported for non-"
1253
 
                                 "'ay' signature {!r}"
1254
 
                                 .format(prop._dbus_signature))
 
930
                raise ValueError
1255
931
            value = dbus.ByteArray(b''.join(chr(byte)
1256
932
                                            for byte in value))
1257
933
        prop(value)
1258
934
    
1259
 
    @dbus.service.method(dbus.PROPERTIES_IFACE,
1260
 
                         in_signature="s",
 
935
    @dbus.service.method(dbus.PROPERTIES_IFACE, in_signature="s",
1261
936
                         out_signature="a{sv}")
1262
937
    def GetAll(self, interface_name):
1263
938
        """Standard D-Bus property GetAll() method, see D-Bus
1278
953
            if not hasattr(value, "variant_level"):
1279
954
                properties[name] = value
1280
955
                continue
1281
 
            properties[name] = type(value)(
1282
 
                value, variant_level = value.variant_level + 1)
 
956
            properties[name] = type(value)(value, variant_level=
 
957
                                           value.variant_level+1)
1283
958
        return dbus.Dictionary(properties, signature="sv")
1284
959
    
1285
 
    @dbus.service.signal(dbus.PROPERTIES_IFACE, signature="sa{sv}as")
1286
 
    def PropertiesChanged(self, interface_name, changed_properties,
1287
 
                          invalidated_properties):
1288
 
        """Standard D-Bus PropertiesChanged() signal, see D-Bus
1289
 
        standard.
1290
 
        """
1291
 
        pass
1292
 
    
1293
960
    @dbus.service.method(dbus.INTROSPECTABLE_IFACE,
1294
961
                         out_signature="s",
1295
962
                         path_keyword='object_path',
1299
966
        
1300
967
        Inserts property tags and interface annotation tags.
1301
968
        """
1302
 
        xmlstring = DBusObjectWithAnnotations.Introspect(self,
1303
 
                                                         object_path,
1304
 
                                                         connection)
 
969
        xmlstring = dbus.service.Object.Introspect(self, object_path,
 
970
                                                   connection)
1305
971
        try:
1306
972
            document = xml.dom.minidom.parseString(xmlstring)
1307
 
            
1308
973
            def make_tag(document, name, prop):
1309
974
                e = document.createElement("property")
1310
975
                e.setAttribute("name", name)
1311
976
                e.setAttribute("type", prop._dbus_signature)
1312
977
                e.setAttribute("access", prop._dbus_access)
1313
978
                return e
1314
 
            
1315
979
            for if_tag in document.getElementsByTagName("interface"):
1316
980
                # Add property tags
1317
981
                for tag in (make_tag(document, name, prop)
1320
984
                            if prop._dbus_interface
1321
985
                            == if_tag.getAttribute("name")):
1322
986
                    if_tag.appendChild(tag)
1323
 
                # Add annotation tags for properties
1324
 
                for tag in if_tag.getElementsByTagName("property"):
1325
 
                    annots = dict()
1326
 
                    for name, prop in self._get_all_dbus_things(
1327
 
                            "property"):
1328
 
                        if (name == tag.getAttribute("name")
1329
 
                            and prop._dbus_interface
1330
 
                            == if_tag.getAttribute("name")):
1331
 
                            annots.update(getattr(
1332
 
                                prop, "_dbus_annotations", {}))
1333
 
                    for name, value in annots.items():
1334
 
                        ann_tag = document.createElement(
1335
 
                            "annotation")
1336
 
                        ann_tag.setAttribute("name", name)
1337
 
                        ann_tag.setAttribute("value", value)
1338
 
                        tag.appendChild(ann_tag)
 
987
                # Add annotation tags
 
988
                for typ in ("method", "signal", "property"):
 
989
                    for tag in if_tag.getElementsByTagName(typ):
 
990
                        annots = dict()
 
991
                        for name, prop in (self.
 
992
                                           _get_all_dbus_things(typ)):
 
993
                            if (name == tag.getAttribute("name")
 
994
                                and prop._dbus_interface
 
995
                                == if_tag.getAttribute("name")):
 
996
                                annots.update(getattr
 
997
                                              (prop,
 
998
                                               "_dbus_annotations",
 
999
                                               {}))
 
1000
                        for name, value in annots.iteritems():
 
1001
                            ann_tag = document.createElement(
 
1002
                                "annotation")
 
1003
                            ann_tag.setAttribute("name", name)
 
1004
                            ann_tag.setAttribute("value", value)
 
1005
                            tag.appendChild(ann_tag)
 
1006
                # Add interface annotation tags
 
1007
                for annotation, value in dict(
 
1008
                    itertools.chain.from_iterable(
 
1009
                        annotations().iteritems()
 
1010
                        for name, annotations in
 
1011
                        self._get_all_dbus_things("interface")
 
1012
                        if name == if_tag.getAttribute("name")
 
1013
                        )).iteritems():
 
1014
                    ann_tag = document.createElement("annotation")
 
1015
                    ann_tag.setAttribute("name", annotation)
 
1016
                    ann_tag.setAttribute("value", value)
 
1017
                    if_tag.appendChild(ann_tag)
1339
1018
                # Add the names to the return values for the
1340
1019
                # "org.freedesktop.DBus.Properties" methods
1341
1020
                if (if_tag.getAttribute("name")
1359
1038
                         exc_info=error)
1360
1039
        return xmlstring
1361
1040
 
1362
 
try:
1363
 
    dbus.OBJECT_MANAGER_IFACE
1364
 
except AttributeError:
1365
 
    dbus.OBJECT_MANAGER_IFACE = "org.freedesktop.DBus.ObjectManager"
1366
 
 
1367
 
class DBusObjectWithObjectManager(DBusObjectWithAnnotations):
1368
 
    """A D-Bus object with an ObjectManager.
1369
 
    
1370
 
    Classes inheriting from this exposes the standard
1371
 
    GetManagedObjects call and the InterfacesAdded and
1372
 
    InterfacesRemoved signals on the standard
1373
 
    "org.freedesktop.DBus.ObjectManager" interface.
1374
 
    
1375
 
    Note: No signals are sent automatically; they must be sent
1376
 
    manually.
1377
 
    """
1378
 
    @dbus.service.method(dbus.OBJECT_MANAGER_IFACE,
1379
 
                         out_signature = "a{oa{sa{sv}}}")
1380
 
    def GetManagedObjects(self):
1381
 
        """This function must be overridden"""
1382
 
        raise NotImplementedError()
1383
 
    
1384
 
    @dbus.service.signal(dbus.OBJECT_MANAGER_IFACE,
1385
 
                         signature = "oa{sa{sv}}")
1386
 
    def InterfacesAdded(self, object_path, interfaces_and_properties):
1387
 
        pass
1388
 
    
1389
 
    @dbus.service.signal(dbus.OBJECT_MANAGER_IFACE, signature = "oas")
1390
 
    def InterfacesRemoved(self, object_path, interfaces):
1391
 
        pass
1392
 
    
1393
 
    @dbus.service.method(dbus.INTROSPECTABLE_IFACE,
1394
 
                         out_signature = "s",
1395
 
                         path_keyword = 'object_path',
1396
 
                         connection_keyword = 'connection')
1397
 
    def Introspect(self, object_path, connection):
1398
 
        """Overloading of standard D-Bus method.
1399
 
        
1400
 
        Override return argument name of GetManagedObjects to be
1401
 
        "objpath_interfaces_and_properties"
1402
 
        """
1403
 
        xmlstring = DBusObjectWithAnnotations.Introspect(self,
1404
 
                                                         object_path,
1405
 
                                                         connection)
1406
 
        try:
1407
 
            document = xml.dom.minidom.parseString(xmlstring)
1408
 
            
1409
 
            for if_tag in document.getElementsByTagName("interface"):
1410
 
                # Fix argument name for the GetManagedObjects method
1411
 
                if (if_tag.getAttribute("name")
1412
 
                                == dbus.OBJECT_MANAGER_IFACE):
1413
 
                    for cn in if_tag.getElementsByTagName("method"):
1414
 
                        if (cn.getAttribute("name")
1415
 
                            == "GetManagedObjects"):
1416
 
                            for arg in cn.getElementsByTagName("arg"):
1417
 
                                if (arg.getAttribute("direction")
1418
 
                                    == "out"):
1419
 
                                    arg.setAttribute(
1420
 
                                        "name",
1421
 
                                        "objpath_interfaces"
1422
 
                                        "_and_properties")
1423
 
            xmlstring = document.toxml("utf-8")
1424
 
            document.unlink()
1425
 
        except (AttributeError, xml.dom.DOMException,
1426
 
                xml.parsers.expat.ExpatError) as error:
1427
 
            logger.error("Failed to override Introspection method",
1428
 
                         exc_info = error)
1429
 
        return xmlstring
1430
1041
 
1431
1042
def datetime_to_dbus(dt, variant_level=0):
1432
1043
    """Convert a UTC datetime.datetime() to a D-Bus type."""
1433
1044
    if dt is None:
1434
1045
        return dbus.String("", variant_level = variant_level)
1435
 
    return dbus.String(dt.isoformat(), variant_level=variant_level)
 
1046
    return dbus.String(dt.isoformat(),
 
1047
                       variant_level=variant_level)
1436
1048
 
1437
1049
 
1438
1050
def alternate_dbus_interfaces(alt_interface_names, deprecate=True):
1458
1070
    (from DBusObjectWithProperties) and interfaces (from the
1459
1071
    dbus_interface_annotations decorator).
1460
1072
    """
1461
 
    
1462
1073
    def wrapper(cls):
1463
1074
        for orig_interface_name, alt_interface_name in (
1464
 
                alt_interface_names.items()):
 
1075
            alt_interface_names.iteritems()):
1465
1076
            attr = {}
1466
1077
            interface_names = set()
1467
1078
            # Go though all attributes of the class
1469
1080
                # Ignore non-D-Bus attributes, and D-Bus attributes
1470
1081
                # with the wrong interface name
1471
1082
                if (not hasattr(attribute, "_dbus_interface")
1472
 
                    or not attribute._dbus_interface.startswith(
1473
 
                        orig_interface_name)):
 
1083
                    or not attribute._dbus_interface
 
1084
                    .startswith(orig_interface_name)):
1474
1085
                    continue
1475
1086
                # Create an alternate D-Bus interface name based on
1476
1087
                # the current name
1477
 
                alt_interface = attribute._dbus_interface.replace(
1478
 
                    orig_interface_name, alt_interface_name)
 
1088
                alt_interface = (attribute._dbus_interface
 
1089
                                 .replace(orig_interface_name,
 
1090
                                          alt_interface_name))
1479
1091
                interface_names.add(alt_interface)
1480
1092
                # Is this a D-Bus signal?
1481
1093
                if getattr(attribute, "_dbus_is_signal", False):
1482
 
                    if sys.version_info.major == 2:
1483
 
                        # Extract the original non-method undecorated
1484
 
                        # function by black magic
1485
 
                        nonmethod_func = (dict(
 
1094
                    # Extract the original non-method undecorated
 
1095
                    # function by black magic
 
1096
                    nonmethod_func = (dict(
1486
1097
                            zip(attribute.func_code.co_freevars,
1487
 
                                attribute.__closure__))
1488
 
                                          ["func"].cell_contents)
1489
 
                    else:
1490
 
                        nonmethod_func = attribute
 
1098
                                attribute.__closure__))["func"]
 
1099
                                      .cell_contents)
1491
1100
                    # Create a new, but exactly alike, function
1492
1101
                    # object, and decorate it to be a new D-Bus signal
1493
1102
                    # with the alternate D-Bus interface name
1494
 
                    if sys.version_info.major == 2:
1495
 
                        new_function = types.FunctionType(
1496
 
                            nonmethod_func.func_code,
1497
 
                            nonmethod_func.func_globals,
1498
 
                            nonmethod_func.func_name,
1499
 
                            nonmethod_func.func_defaults,
1500
 
                            nonmethod_func.func_closure)
1501
 
                    else:
1502
 
                        new_function = types.FunctionType(
1503
 
                            nonmethod_func.__code__,
1504
 
                            nonmethod_func.__globals__,
1505
 
                            nonmethod_func.__name__,
1506
 
                            nonmethod_func.__defaults__,
1507
 
                            nonmethod_func.__closure__)
1508
 
                    new_function = (dbus.service.signal(
1509
 
                        alt_interface,
1510
 
                        attribute._dbus_signature)(new_function))
 
1103
                    new_function = (dbus.service.signal
 
1104
                                    (alt_interface,
 
1105
                                     attribute._dbus_signature)
 
1106
                                    (types.FunctionType(
 
1107
                                nonmethod_func.func_code,
 
1108
                                nonmethod_func.func_globals,
 
1109
                                nonmethod_func.func_name,
 
1110
                                nonmethod_func.func_defaults,
 
1111
                                nonmethod_func.func_closure)))
1511
1112
                    # Copy annotations, if any
1512
1113
                    try:
1513
 
                        new_function._dbus_annotations = dict(
1514
 
                            attribute._dbus_annotations)
 
1114
                        new_function._dbus_annotations = (
 
1115
                            dict(attribute._dbus_annotations))
1515
1116
                    except AttributeError:
1516
1117
                        pass
1517
1118
                    # Define a creator of a function to call both the
1522
1123
                        """This function is a scope container to pass
1523
1124
                        func1 and func2 to the "call_both" function
1524
1125
                        outside of its arguments"""
1525
 
                        
1526
 
                        @functools.wraps(func2)
1527
1126
                        def call_both(*args, **kwargs):
1528
1127
                            """This function will emit two D-Bus
1529
1128
                            signals by calling func1 and func2"""
1530
1129
                            func1(*args, **kwargs)
1531
1130
                            func2(*args, **kwargs)
1532
 
                        # Make wrapper function look like a D-Bus signal
1533
 
                        for name, attr in inspect.getmembers(func2):
1534
 
                            if name.startswith("_dbus_"):
1535
 
                                setattr(call_both, name, attr)
1536
 
                        
1537
1131
                        return call_both
1538
1132
                    # Create the "call_both" function and add it to
1539
1133
                    # the class
1544
1138
                    # object.  Decorate it to be a new D-Bus method
1545
1139
                    # with the alternate D-Bus interface name.  Add it
1546
1140
                    # to the class.
1547
 
                    attr[attrname] = (
1548
 
                        dbus.service.method(
1549
 
                            alt_interface,
1550
 
                            attribute._dbus_in_signature,
1551
 
                            attribute._dbus_out_signature)
1552
 
                        (types.FunctionType(attribute.func_code,
1553
 
                                            attribute.func_globals,
1554
 
                                            attribute.func_name,
1555
 
                                            attribute.func_defaults,
1556
 
                                            attribute.func_closure)))
 
1141
                    attr[attrname] = (dbus.service.method
 
1142
                                      (alt_interface,
 
1143
                                       attribute._dbus_in_signature,
 
1144
                                       attribute._dbus_out_signature)
 
1145
                                      (types.FunctionType
 
1146
                                       (attribute.func_code,
 
1147
                                        attribute.func_globals,
 
1148
                                        attribute.func_name,
 
1149
                                        attribute.func_defaults,
 
1150
                                        attribute.func_closure)))
1557
1151
                    # Copy annotations, if any
1558
1152
                    try:
1559
 
                        attr[attrname]._dbus_annotations = dict(
1560
 
                            attribute._dbus_annotations)
 
1153
                        attr[attrname]._dbus_annotations = (
 
1154
                            dict(attribute._dbus_annotations))
1561
1155
                    except AttributeError:
1562
1156
                        pass
1563
1157
                # Is this a D-Bus property?
1566
1160
                    # object, and decorate it to be a new D-Bus
1567
1161
                    # property with the alternate D-Bus interface
1568
1162
                    # name.  Add it to the class.
1569
 
                    attr[attrname] = (dbus_service_property(
1570
 
                        alt_interface, attribute._dbus_signature,
1571
 
                        attribute._dbus_access,
1572
 
                        attribute._dbus_get_args_options
1573
 
                        ["byte_arrays"])
1574
 
                                      (types.FunctionType(
1575
 
                                          attribute.func_code,
1576
 
                                          attribute.func_globals,
1577
 
                                          attribute.func_name,
1578
 
                                          attribute.func_defaults,
1579
 
                                          attribute.func_closure)))
 
1163
                    attr[attrname] = (dbus_service_property
 
1164
                                      (alt_interface,
 
1165
                                       attribute._dbus_signature,
 
1166
                                       attribute._dbus_access,
 
1167
                                       attribute
 
1168
                                       ._dbus_get_args_options
 
1169
                                       ["byte_arrays"])
 
1170
                                      (types.FunctionType
 
1171
                                       (attribute.func_code,
 
1172
                                        attribute.func_globals,
 
1173
                                        attribute.func_name,
 
1174
                                        attribute.func_defaults,
 
1175
                                        attribute.func_closure)))
1580
1176
                    # Copy annotations, if any
1581
1177
                    try:
1582
 
                        attr[attrname]._dbus_annotations = dict(
1583
 
                            attribute._dbus_annotations)
 
1178
                        attr[attrname]._dbus_annotations = (
 
1179
                            dict(attribute._dbus_annotations))
1584
1180
                    except AttributeError:
1585
1181
                        pass
1586
1182
                # Is this a D-Bus interface?
1589
1185
                    # object.  Decorate it to be a new D-Bus interface
1590
1186
                    # with the alternate D-Bus interface name.  Add it
1591
1187
                    # to the class.
1592
 
                    attr[attrname] = (
1593
 
                        dbus_interface_annotations(alt_interface)
1594
 
                        (types.FunctionType(attribute.func_code,
1595
 
                                            attribute.func_globals,
1596
 
                                            attribute.func_name,
1597
 
                                            attribute.func_defaults,
1598
 
                                            attribute.func_closure)))
 
1188
                    attr[attrname] = (dbus_interface_annotations
 
1189
                                      (alt_interface)
 
1190
                                      (types.FunctionType
 
1191
                                       (attribute.func_code,
 
1192
                                        attribute.func_globals,
 
1193
                                        attribute.func_name,
 
1194
                                        attribute.func_defaults,
 
1195
                                        attribute.func_closure)))
1599
1196
            if deprecate:
1600
1197
                # Deprecate all alternate interfaces
1601
 
                iname="_AlternateDBusNames_interface_annotation{}"
 
1198
                iname="_AlternateDBusNames_interface_annotation{0}"
1602
1199
                for interface_name in interface_names:
1603
 
                    
1604
1200
                    @dbus_interface_annotations(interface_name)
1605
1201
                    def func(self):
1606
1202
                        return { "org.freedesktop.DBus.Deprecated":
1607
 
                                 "true" }
 
1203
                                     "true" }
1608
1204
                    # Find an unused name
1609
1205
                    for aname in (iname.format(i)
1610
1206
                                  for i in itertools.count()):
1614
1210
            if interface_names:
1615
1211
                # Replace the class with a new subclass of it with
1616
1212
                # methods, signals, etc. as created above.
1617
 
                cls = type(b"{}Alternate".format(cls.__name__),
1618
 
                           (cls, ), attr)
 
1213
                cls = type(b"{0}Alternate".format(cls.__name__),
 
1214
                           (cls,), attr)
1619
1215
        return cls
1620
 
    
1621
1216
    return wrapper
1622
1217
 
1623
1218
 
1624
1219
@alternate_dbus_interfaces({"se.recompile.Mandos":
1625
 
                            "se.bsnet.fukt.Mandos"})
 
1220
                                "se.bsnet.fukt.Mandos"})
1626
1221
class ClientDBus(Client, DBusObjectWithProperties):
1627
1222
    """A Client class using D-Bus
1628
1223
    
1632
1227
    """
1633
1228
    
1634
1229
    runtime_expansions = (Client.runtime_expansions
1635
 
                          + ("dbus_object_path", ))
1636
 
    
1637
 
    _interface = "se.recompile.Mandos.Client"
 
1230
                          + ("dbus_object_path",))
1638
1231
    
1639
1232
    # dbus.service.Object doesn't use super(), so we can't either.
1640
1233
    
1643
1236
        Client.__init__(self, *args, **kwargs)
1644
1237
        # Only now, when this client is initialized, can it show up on
1645
1238
        # the D-Bus
1646
 
        client_object_name = str(self.name).translate(
 
1239
        client_object_name = unicode(self.name).translate(
1647
1240
            {ord("."): ord("_"),
1648
1241
             ord("-"): ord("_")})
1649
 
        self.dbus_object_path = dbus.ObjectPath(
1650
 
            "/clients/" + client_object_name)
 
1242
        self.dbus_object_path = (dbus.ObjectPath
 
1243
                                 ("/clients/" + client_object_name))
1651
1244
        DBusObjectWithProperties.__init__(self, self.bus,
1652
1245
                                          self.dbus_object_path)
1653
1246
    
1654
 
    def notifychangeproperty(transform_func, dbus_name,
1655
 
                             type_func=lambda x: x,
1656
 
                             variant_level=1,
1657
 
                             invalidate_only=False,
1658
 
                             _interface=_interface):
 
1247
    def notifychangeproperty(transform_func,
 
1248
                             dbus_name, type_func=lambda x: x,
 
1249
                             variant_level=1):
1659
1250
        """ Modify a variable so that it's a property which announces
1660
1251
        its changes to DBus.
1661
1252
        
1666
1257
                   to the D-Bus.  Default: no transform
1667
1258
        variant_level: D-Bus variant level.  Default: 1
1668
1259
        """
1669
 
        attrname = "_{}".format(dbus_name)
1670
 
        
 
1260
        attrname = "_{0}".format(dbus_name)
1671
1261
        def setter(self, value):
1672
1262
            if hasattr(self, "dbus_object_path"):
1673
1263
                if (not hasattr(self, attrname) or
1674
1264
                    type_func(getattr(self, attrname, None))
1675
1265
                    != type_func(value)):
1676
 
                    if invalidate_only:
1677
 
                        self.PropertiesChanged(
1678
 
                            _interface, dbus.Dictionary(),
1679
 
                            dbus.Array((dbus_name, )))
1680
 
                    else:
1681
 
                        dbus_value = transform_func(
1682
 
                            type_func(value),
1683
 
                            variant_level = variant_level)
1684
 
                        self.PropertyChanged(dbus.String(dbus_name),
1685
 
                                             dbus_value)
1686
 
                        self.PropertiesChanged(
1687
 
                            _interface,
1688
 
                            dbus.Dictionary({ dbus.String(dbus_name):
1689
 
                                              dbus_value }),
1690
 
                            dbus.Array())
 
1266
                    dbus_value = transform_func(type_func(value),
 
1267
                                                variant_level
 
1268
                                                =variant_level)
 
1269
                    self.PropertyChanged(dbus.String(dbus_name),
 
1270
                                         dbus_value)
1691
1271
            setattr(self, attrname, value)
1692
1272
        
1693
1273
        return property(lambda self: getattr(self, attrname), setter)
1699
1279
    enabled = notifychangeproperty(dbus.Boolean, "Enabled")
1700
1280
    last_enabled = notifychangeproperty(datetime_to_dbus,
1701
1281
                                        "LastEnabled")
1702
 
    checker = notifychangeproperty(
1703
 
        dbus.Boolean, "CheckerRunning",
1704
 
        type_func = lambda checker: checker is not None)
 
1282
    checker = notifychangeproperty(dbus.Boolean, "CheckerRunning",
 
1283
                                   type_func = lambda checker:
 
1284
                                       checker is not None)
1705
1285
    last_checked_ok = notifychangeproperty(datetime_to_dbus,
1706
1286
                                           "LastCheckedOK")
1707
1287
    last_checker_status = notifychangeproperty(dbus.Int16,
1710
1290
        datetime_to_dbus, "LastApprovalRequest")
1711
1291
    approved_by_default = notifychangeproperty(dbus.Boolean,
1712
1292
                                               "ApprovedByDefault")
1713
 
    approval_delay = notifychangeproperty(
1714
 
        dbus.UInt64, "ApprovalDelay",
1715
 
        type_func = lambda td: td.total_seconds() * 1000)
 
1293
    approval_delay = notifychangeproperty(dbus.UInt64,
 
1294
                                          "ApprovalDelay",
 
1295
                                          type_func =
 
1296
                                          timedelta_to_milliseconds)
1716
1297
    approval_duration = notifychangeproperty(
1717
1298
        dbus.UInt64, "ApprovalDuration",
1718
 
        type_func = lambda td: td.total_seconds() * 1000)
 
1299
        type_func = timedelta_to_milliseconds)
1719
1300
    host = notifychangeproperty(dbus.String, "Host")
1720
 
    timeout = notifychangeproperty(
1721
 
        dbus.UInt64, "Timeout",
1722
 
        type_func = lambda td: td.total_seconds() * 1000)
 
1301
    timeout = notifychangeproperty(dbus.UInt64, "Timeout",
 
1302
                                   type_func =
 
1303
                                   timedelta_to_milliseconds)
1723
1304
    extended_timeout = notifychangeproperty(
1724
1305
        dbus.UInt64, "ExtendedTimeout",
1725
 
        type_func = lambda td: td.total_seconds() * 1000)
1726
 
    interval = notifychangeproperty(
1727
 
        dbus.UInt64, "Interval",
1728
 
        type_func = lambda td: td.total_seconds() * 1000)
 
1306
        type_func = timedelta_to_milliseconds)
 
1307
    interval = notifychangeproperty(dbus.UInt64,
 
1308
                                    "Interval",
 
1309
                                    type_func =
 
1310
                                    timedelta_to_milliseconds)
1729
1311
    checker_command = notifychangeproperty(dbus.String, "Checker")
1730
 
    secret = notifychangeproperty(dbus.ByteArray, "Secret",
1731
 
                                  invalidate_only=True)
1732
1312
    
1733
1313
    del notifychangeproperty
1734
1314
    
1741
1321
            DBusObjectWithProperties.__del__(self, *args, **kwargs)
1742
1322
        Client.__del__(self, *args, **kwargs)
1743
1323
    
1744
 
    def checker_callback(self, source, condition,
1745
 
                         connection, command, *args, **kwargs):
1746
 
        ret = Client.checker_callback(self, source, condition,
1747
 
                                      connection, command, *args,
1748
 
                                      **kwargs)
1749
 
        exitstatus = self.last_checker_status
1750
 
        if exitstatus >= 0:
 
1324
    def checker_callback(self, pid, condition, command,
 
1325
                         *args, **kwargs):
 
1326
        self.checker_callback_tag = None
 
1327
        self.checker = None
 
1328
        if os.WIFEXITED(condition):
 
1329
            exitstatus = os.WEXITSTATUS(condition)
1751
1330
            # Emit D-Bus signal
1752
1331
            self.CheckerCompleted(dbus.Int16(exitstatus),
1753
 
                                  # This is specific to GNU libC
1754
 
                                  dbus.Int64(exitstatus << 8),
 
1332
                                  dbus.Int64(condition),
1755
1333
                                  dbus.String(command))
1756
1334
        else:
1757
1335
            # Emit D-Bus signal
1758
1336
            self.CheckerCompleted(dbus.Int16(-1),
1759
 
                                  dbus.Int64(
1760
 
                                      # This is specific to GNU libC
1761
 
                                      (exitstatus << 8)
1762
 
                                      | self.last_checker_signal),
 
1337
                                  dbus.Int64(condition),
1763
1338
                                  dbus.String(command))
1764
 
        return ret
 
1339
        
 
1340
        return Client.checker_callback(self, pid, condition, command,
 
1341
                                       *args, **kwargs)
1765
1342
    
1766
1343
    def start_checker(self, *args, **kwargs):
1767
 
        old_checker_pid = getattr(self.checker, "pid", None)
 
1344
        old_checker = self.checker
 
1345
        if self.checker is not None:
 
1346
            old_checker_pid = self.checker.pid
 
1347
        else:
 
1348
            old_checker_pid = None
1768
1349
        r = Client.start_checker(self, *args, **kwargs)
1769
1350
        # Only if new checker process was started
1770
1351
        if (self.checker is not None
1779
1360
    
1780
1361
    def approve(self, value=True):
1781
1362
        self.approved = value
1782
 
        gobject.timeout_add(int(self.approval_duration.total_seconds()
1783
 
                                * 1000), self._reset_approved)
 
1363
        gobject.timeout_add(timedelta_to_milliseconds
 
1364
                            (self.approval_duration),
 
1365
                            self._reset_approved)
1784
1366
        self.send_changedstate()
1785
1367
    
1786
1368
    ## D-Bus methods, signals & properties
 
1369
    _interface = "se.recompile.Mandos.Client"
1787
1370
    
1788
1371
    ## Interfaces
1789
1372
    
 
1373
    @dbus_interface_annotations(_interface)
 
1374
    def _foo(self):
 
1375
        return { "org.freedesktop.DBus.Property.EmitsChangedSignal":
 
1376
                     "false"}
 
1377
    
1790
1378
    ## Signals
1791
1379
    
1792
1380
    # CheckerCompleted - signal
1802
1390
        pass
1803
1391
    
1804
1392
    # PropertyChanged - signal
1805
 
    @dbus_annotations({"org.freedesktop.DBus.Deprecated": "true"})
1806
1393
    @dbus.service.signal(_interface, signature="sv")
1807
1394
    def PropertyChanged(self, property, value):
1808
1395
        "D-Bus signal"
1842
1429
        self.checked_ok()
1843
1430
    
1844
1431
    # Enable - method
1845
 
    @dbus_annotations({"org.freedesktop.DBus.Deprecated": "true"})
1846
1432
    @dbus.service.method(_interface)
1847
1433
    def Enable(self):
1848
1434
        "D-Bus method"
1849
1435
        self.enable()
1850
1436
    
1851
1437
    # StartChecker - method
1852
 
    @dbus_annotations({"org.freedesktop.DBus.Deprecated": "true"})
1853
1438
    @dbus.service.method(_interface)
1854
1439
    def StartChecker(self):
1855
1440
        "D-Bus method"
1856
1441
        self.start_checker()
1857
1442
    
1858
1443
    # Disable - method
1859
 
    @dbus_annotations({"org.freedesktop.DBus.Deprecated": "true"})
1860
1444
    @dbus.service.method(_interface)
1861
1445
    def Disable(self):
1862
1446
        "D-Bus method"
1863
1447
        self.disable()
1864
1448
    
1865
1449
    # StopChecker - method
1866
 
    @dbus_annotations({"org.freedesktop.DBus.Deprecated": "true"})
1867
1450
    @dbus.service.method(_interface)
1868
1451
    def StopChecker(self):
1869
1452
        self.stop_checker()
1876
1459
        return dbus.Boolean(bool(self.approvals_pending))
1877
1460
    
1878
1461
    # ApprovedByDefault - property
1879
 
    @dbus_service_property(_interface,
1880
 
                           signature="b",
 
1462
    @dbus_service_property(_interface, signature="b",
1881
1463
                           access="readwrite")
1882
1464
    def ApprovedByDefault_dbus_property(self, value=None):
1883
1465
        if value is None:       # get
1885
1467
        self.approved_by_default = bool(value)
1886
1468
    
1887
1469
    # ApprovalDelay - property
1888
 
    @dbus_service_property(_interface,
1889
 
                           signature="t",
 
1470
    @dbus_service_property(_interface, signature="t",
1890
1471
                           access="readwrite")
1891
1472
    def ApprovalDelay_dbus_property(self, value=None):
1892
1473
        if value is None:       # get
1893
 
            return dbus.UInt64(self.approval_delay.total_seconds()
1894
 
                               * 1000)
 
1474
            return dbus.UInt64(self.approval_delay_milliseconds())
1895
1475
        self.approval_delay = datetime.timedelta(0, 0, 0, value)
1896
1476
    
1897
1477
    # ApprovalDuration - property
1898
 
    @dbus_service_property(_interface,
1899
 
                           signature="t",
 
1478
    @dbus_service_property(_interface, signature="t",
1900
1479
                           access="readwrite")
1901
1480
    def ApprovalDuration_dbus_property(self, value=None):
1902
1481
        if value is None:       # get
1903
 
            return dbus.UInt64(self.approval_duration.total_seconds()
1904
 
                               * 1000)
 
1482
            return dbus.UInt64(timedelta_to_milliseconds(
 
1483
                    self.approval_duration))
1905
1484
        self.approval_duration = datetime.timedelta(0, 0, 0, value)
1906
1485
    
1907
1486
    # Name - property
1908
 
    @dbus_annotations(
1909
 
        {"org.freedesktop.DBus.Property.EmitsChangedSignal": "const"})
1910
1487
    @dbus_service_property(_interface, signature="s", access="read")
1911
1488
    def Name_dbus_property(self):
1912
1489
        return dbus.String(self.name)
1913
1490
    
1914
1491
    # Fingerprint - property
1915
 
    @dbus_annotations(
1916
 
        {"org.freedesktop.DBus.Property.EmitsChangedSignal": "const"})
1917
1492
    @dbus_service_property(_interface, signature="s", access="read")
1918
1493
    def Fingerprint_dbus_property(self):
1919
1494
        return dbus.String(self.fingerprint)
1920
1495
    
1921
1496
    # Host - property
1922
 
    @dbus_service_property(_interface,
1923
 
                           signature="s",
 
1497
    @dbus_service_property(_interface, signature="s",
1924
1498
                           access="readwrite")
1925
1499
    def Host_dbus_property(self, value=None):
1926
1500
        if value is None:       # get
1927
1501
            return dbus.String(self.host)
1928
 
        self.host = str(value)
 
1502
        self.host = unicode(value)
1929
1503
    
1930
1504
    # Created - property
1931
 
    @dbus_annotations(
1932
 
        {"org.freedesktop.DBus.Property.EmitsChangedSignal": "const"})
1933
1505
    @dbus_service_property(_interface, signature="s", access="read")
1934
1506
    def Created_dbus_property(self):
1935
1507
        return datetime_to_dbus(self.created)
1940
1512
        return datetime_to_dbus(self.last_enabled)
1941
1513
    
1942
1514
    # Enabled - property
1943
 
    @dbus_service_property(_interface,
1944
 
                           signature="b",
 
1515
    @dbus_service_property(_interface, signature="b",
1945
1516
                           access="readwrite")
1946
1517
    def Enabled_dbus_property(self, value=None):
1947
1518
        if value is None:       # get
1952
1523
            self.disable()
1953
1524
    
1954
1525
    # LastCheckedOK - property
1955
 
    @dbus_service_property(_interface,
1956
 
                           signature="s",
 
1526
    @dbus_service_property(_interface, signature="s",
1957
1527
                           access="readwrite")
1958
1528
    def LastCheckedOK_dbus_property(self, value=None):
1959
1529
        if value is not None:
1962
1532
        return datetime_to_dbus(self.last_checked_ok)
1963
1533
    
1964
1534
    # LastCheckerStatus - property
1965
 
    @dbus_service_property(_interface, signature="n", access="read")
 
1535
    @dbus_service_property(_interface, signature="n",
 
1536
                           access="read")
1966
1537
    def LastCheckerStatus_dbus_property(self):
1967
1538
        return dbus.Int16(self.last_checker_status)
1968
1539
    
1977
1548
        return datetime_to_dbus(self.last_approval_request)
1978
1549
    
1979
1550
    # Timeout - property
1980
 
    @dbus_service_property(_interface,
1981
 
                           signature="t",
 
1551
    @dbus_service_property(_interface, signature="t",
1982
1552
                           access="readwrite")
1983
1553
    def Timeout_dbus_property(self, value=None):
1984
1554
        if value is None:       # get
1985
 
            return dbus.UInt64(self.timeout.total_seconds() * 1000)
 
1555
            return dbus.UInt64(self.timeout_milliseconds())
1986
1556
        old_timeout = self.timeout
1987
1557
        self.timeout = datetime.timedelta(0, 0, 0, value)
1988
1558
        # Reschedule disabling
1997
1567
                    is None):
1998
1568
                    return
1999
1569
                gobject.source_remove(self.disable_initiator_tag)
2000
 
                self.disable_initiator_tag = gobject.timeout_add(
2001
 
                    int((self.expires - now).total_seconds() * 1000),
2002
 
                    self.disable)
 
1570
                self.disable_initiator_tag = (
 
1571
                    gobject.timeout_add(
 
1572
                        timedelta_to_milliseconds(self.expires - now),
 
1573
                        self.disable))
2003
1574
    
2004
1575
    # ExtendedTimeout - property
2005
 
    @dbus_service_property(_interface,
2006
 
                           signature="t",
 
1576
    @dbus_service_property(_interface, signature="t",
2007
1577
                           access="readwrite")
2008
1578
    def ExtendedTimeout_dbus_property(self, value=None):
2009
1579
        if value is None:       # get
2010
 
            return dbus.UInt64(self.extended_timeout.total_seconds()
2011
 
                               * 1000)
 
1580
            return dbus.UInt64(self.extended_timeout_milliseconds())
2012
1581
        self.extended_timeout = datetime.timedelta(0, 0, 0, value)
2013
1582
    
2014
1583
    # Interval - property
2015
 
    @dbus_service_property(_interface,
2016
 
                           signature="t",
 
1584
    @dbus_service_property(_interface, signature="t",
2017
1585
                           access="readwrite")
2018
1586
    def Interval_dbus_property(self, value=None):
2019
1587
        if value is None:       # get
2020
 
            return dbus.UInt64(self.interval.total_seconds() * 1000)
 
1588
            return dbus.UInt64(self.interval_milliseconds())
2021
1589
        self.interval = datetime.timedelta(0, 0, 0, value)
2022
1590
        if getattr(self, "checker_initiator_tag", None) is None:
2023
1591
            return
2024
1592
        if self.enabled:
2025
1593
            # Reschedule checker run
2026
1594
            gobject.source_remove(self.checker_initiator_tag)
2027
 
            self.checker_initiator_tag = gobject.timeout_add(
2028
 
                value, self.start_checker)
2029
 
            self.start_checker() # Start one now, too
 
1595
            self.checker_initiator_tag = (gobject.timeout_add
 
1596
                                          (value, self.start_checker))
 
1597
            self.start_checker()    # Start one now, too
2030
1598
    
2031
1599
    # Checker - property
2032
 
    @dbus_service_property(_interface,
2033
 
                           signature="s",
 
1600
    @dbus_service_property(_interface, signature="s",
2034
1601
                           access="readwrite")
2035
1602
    def Checker_dbus_property(self, value=None):
2036
1603
        if value is None:       # get
2037
1604
            return dbus.String(self.checker_command)
2038
 
        self.checker_command = str(value)
 
1605
        self.checker_command = unicode(value)
2039
1606
    
2040
1607
    # CheckerRunning - property
2041
 
    @dbus_service_property(_interface,
2042
 
                           signature="b",
 
1608
    @dbus_service_property(_interface, signature="b",
2043
1609
                           access="readwrite")
2044
1610
    def CheckerRunning_dbus_property(self, value=None):
2045
1611
        if value is None:       # get
2050
1616
            self.stop_checker()
2051
1617
    
2052
1618
    # ObjectPath - property
2053
 
    @dbus_annotations(
2054
 
        {"org.freedesktop.DBus.Property.EmitsChangedSignal": "const",
2055
 
         "org.freedesktop.DBus.Deprecated": "true"})
2056
1619
    @dbus_service_property(_interface, signature="o", access="read")
2057
1620
    def ObjectPath_dbus_property(self):
2058
1621
        return self.dbus_object_path # is already a dbus.ObjectPath
2059
1622
    
2060
1623
    # Secret = property
2061
 
    @dbus_annotations(
2062
 
        {"org.freedesktop.DBus.Property.EmitsChangedSignal":
2063
 
         "invalidates"})
2064
 
    @dbus_service_property(_interface,
2065
 
                           signature="ay",
2066
 
                           access="write",
2067
 
                           byte_arrays=True)
 
1624
    @dbus_service_property(_interface, signature="ay",
 
1625
                           access="write", byte_arrays=True)
2068
1626
    def Secret_dbus_property(self, value):
2069
 
        self.secret = bytes(value)
 
1627
        self.secret = str(value)
2070
1628
    
2071
1629
    del _interface
2072
1630
 
2076
1634
        self._pipe = child_pipe
2077
1635
        self._pipe.send(('init', fpr, address))
2078
1636
        if not self._pipe.recv():
2079
 
            raise KeyError(fpr)
 
1637
            raise KeyError()
2080
1638
    
2081
1639
    def __getattribute__(self, name):
2082
1640
        if name == '_pipe':
2086
1644
        if data[0] == 'data':
2087
1645
            return data[1]
2088
1646
        if data[0] == 'function':
2089
 
            
2090
1647
            def func(*args, **kwargs):
2091
1648
                self._pipe.send(('funcall', name, args, kwargs))
2092
1649
                return self._pipe.recv()[1]
2093
 
            
2094
1650
            return func
2095
1651
    
2096
1652
    def __setattr__(self, name, value):
2108
1664
    def handle(self):
2109
1665
        with contextlib.closing(self.server.child_pipe) as child_pipe:
2110
1666
            logger.info("TCP connection from: %s",
2111
 
                        str(self.client_address))
 
1667
                        unicode(self.client_address))
2112
1668
            logger.debug("Pipe FD: %d",
2113
1669
                         self.server.child_pipe.fileno())
2114
1670
            
2115
 
            session = gnutls.ClientSession(self.request)
 
1671
            session = (gnutls.connection
 
1672
                       .ClientSession(self.request,
 
1673
                                      gnutls.connection
 
1674
                                      .X509Credentials()))
 
1675
            
 
1676
            # Note: gnutls.connection.X509Credentials is really a
 
1677
            # generic GnuTLS certificate credentials object so long as
 
1678
            # no X.509 keys are added to it.  Therefore, we can use it
 
1679
            # here despite using OpenPGP certificates.
2116
1680
            
2117
1681
            #priority = ':'.join(("NONE", "+VERS-TLS1.1",
2118
1682
            #                      "+AES-256-CBC", "+SHA1",
2122
1686
            priority = self.server.gnutls_priority
2123
1687
            if priority is None:
2124
1688
                priority = "NORMAL"
2125
 
            gnutls.priority_set_direct(session._c_object, priority,
2126
 
                                       None)
 
1689
            (gnutls.library.functions
 
1690
             .gnutls_priority_set_direct(session._c_object,
 
1691
                                         priority, None))
2127
1692
            
2128
1693
            # Start communication using the Mandos protocol
2129
1694
            # Get protocol number
2131
1696
            logger.debug("Protocol version: %r", line)
2132
1697
            try:
2133
1698
                if int(line.strip().split()[0]) > 1:
2134
 
                    raise RuntimeError(line)
 
1699
                    raise RuntimeError
2135
1700
            except (ValueError, IndexError, RuntimeError) as error:
2136
1701
                logger.error("Unknown protocol version: %s", error)
2137
1702
                return
2139
1704
            # Start GnuTLS connection
2140
1705
            try:
2141
1706
                session.handshake()
2142
 
            except gnutls.Error as error:
 
1707
            except gnutls.errors.GNUTLSError as error:
2143
1708
                logger.warning("Handshake failed: %s", error)
2144
1709
                # Do not run session.bye() here: the session is not
2145
1710
                # established.  Just abandon the request.
2149
1714
            approval_required = False
2150
1715
            try:
2151
1716
                try:
2152
 
                    fpr = self.fingerprint(
2153
 
                        self.peer_certificate(session))
2154
 
                except (TypeError, gnutls.Error) as error:
 
1717
                    fpr = self.fingerprint(self.peer_certificate
 
1718
                                           (session))
 
1719
                except (TypeError,
 
1720
                        gnutls.errors.GNUTLSError) as error:
2155
1721
                    logger.warning("Bad certificate: %s", error)
2156
1722
                    return
2157
1723
                logger.debug("Fingerprint: %s", fpr)
2170
1736
                while True:
2171
1737
                    if not client.enabled:
2172
1738
                        logger.info("Client %s is disabled",
2173
 
                                    client.name)
 
1739
                                       client.name)
2174
1740
                        if self.server.use_dbus:
2175
1741
                            # Emit D-Bus signal
2176
1742
                            client.Rejected("Disabled")
2185
1751
                        if self.server.use_dbus:
2186
1752
                            # Emit D-Bus signal
2187
1753
                            client.NeedApproval(
2188
 
                                client.approval_delay.total_seconds()
2189
 
                                * 1000, client.approved_by_default)
 
1754
                                client.approval_delay_milliseconds(),
 
1755
                                client.approved_by_default)
2190
1756
                    else:
2191
1757
                        logger.warning("Client %s was not approved",
2192
1758
                                       client.name)
2198
1764
                    #wait until timeout or approved
2199
1765
                    time = datetime.datetime.now()
2200
1766
                    client.changedstate.acquire()
2201
 
                    client.changedstate.wait(delay.total_seconds())
 
1767
                    client.changedstate.wait(
 
1768
                        float(timedelta_to_milliseconds(delay)
 
1769
                              / 1000))
2202
1770
                    client.changedstate.release()
2203
1771
                    time2 = datetime.datetime.now()
2204
1772
                    if (time2 - time) >= delay:
2219
1787
                while sent_size < len(client.secret):
2220
1788
                    try:
2221
1789
                        sent = session.send(client.secret[sent_size:])
2222
 
                    except gnutls.Error as error:
 
1790
                    except gnutls.errors.GNUTLSError as error:
2223
1791
                        logger.warning("gnutls send failed",
2224
1792
                                       exc_info=error)
2225
1793
                        return
2226
 
                    logger.debug("Sent: %d, remaining: %d", sent,
2227
 
                                 len(client.secret) - (sent_size
2228
 
                                                       + sent))
 
1794
                    logger.debug("Sent: %d, remaining: %d",
 
1795
                                 sent, len(client.secret)
 
1796
                                 - (sent_size + sent))
2229
1797
                    sent_size += sent
2230
1798
                
2231
1799
                logger.info("Sending secret to %s", client.name)
2240
1808
                    client.approvals_pending -= 1
2241
1809
                try:
2242
1810
                    session.bye()
2243
 
                except gnutls.Error as error:
 
1811
                except gnutls.errors.GNUTLSError as error:
2244
1812
                    logger.warning("GnuTLS bye failed",
2245
1813
                                   exc_info=error)
2246
1814
    
2248
1816
    def peer_certificate(session):
2249
1817
        "Return the peer's OpenPGP certificate as a bytestring"
2250
1818
        # If not an OpenPGP certificate...
2251
 
        if (gnutls.certificate_type_get(session._c_object)
2252
 
            != gnutls.CRT_OPENPGP):
2253
 
            # ...return invalid data
2254
 
            return b""
 
1819
        if (gnutls.library.functions
 
1820
            .gnutls_certificate_type_get(session._c_object)
 
1821
            != gnutls.library.constants.GNUTLS_CRT_OPENPGP):
 
1822
            # ...do the normal thing
 
1823
            return session.peer_certificate
2255
1824
        list_size = ctypes.c_uint(1)
2256
 
        cert_list = (gnutls.certificate_get_peers
 
1825
        cert_list = (gnutls.library.functions
 
1826
                     .gnutls_certificate_get_peers
2257
1827
                     (session._c_object, ctypes.byref(list_size)))
2258
1828
        if not bool(cert_list) and list_size.value != 0:
2259
 
            raise gnutls.Error("error getting peer certificate")
 
1829
            raise gnutls.errors.GNUTLSError("error getting peer"
 
1830
                                            " certificate")
2260
1831
        if list_size.value == 0:
2261
1832
            return None
2262
1833
        cert = cert_list[0]
2266
1837
    def fingerprint(openpgp):
2267
1838
        "Convert an OpenPGP bytestring to a hexdigit fingerprint"
2268
1839
        # New GnuTLS "datum" with the OpenPGP public key
2269
 
        datum = gnutls.datum_t(
2270
 
            ctypes.cast(ctypes.c_char_p(openpgp),
2271
 
                        ctypes.POINTER(ctypes.c_ubyte)),
2272
 
            ctypes.c_uint(len(openpgp)))
 
1840
        datum = (gnutls.library.types
 
1841
                 .gnutls_datum_t(ctypes.cast(ctypes.c_char_p(openpgp),
 
1842
                                             ctypes.POINTER
 
1843
                                             (ctypes.c_ubyte)),
 
1844
                                 ctypes.c_uint(len(openpgp))))
2273
1845
        # New empty GnuTLS certificate
2274
 
        crt = gnutls.openpgp_crt_t()
2275
 
        gnutls.openpgp_crt_init(ctypes.byref(crt))
 
1846
        crt = gnutls.library.types.gnutls_openpgp_crt_t()
 
1847
        (gnutls.library.functions
 
1848
         .gnutls_openpgp_crt_init(ctypes.byref(crt)))
2276
1849
        # Import the OpenPGP public key into the certificate
2277
 
        gnutls.openpgp_crt_import(crt, ctypes.byref(datum),
2278
 
                                  gnutls.OPENPGP_FMT_RAW)
 
1850
        (gnutls.library.functions
 
1851
         .gnutls_openpgp_crt_import(crt, ctypes.byref(datum),
 
1852
                                    gnutls.library.constants
 
1853
                                    .GNUTLS_OPENPGP_FMT_RAW))
2279
1854
        # Verify the self signature in the key
2280
1855
        crtverify = ctypes.c_uint()
2281
 
        gnutls.openpgp_crt_verify_self(crt, 0,
2282
 
                                       ctypes.byref(crtverify))
 
1856
        (gnutls.library.functions
 
1857
         .gnutls_openpgp_crt_verify_self(crt, 0,
 
1858
                                         ctypes.byref(crtverify)))
2283
1859
        if crtverify.value != 0:
2284
 
            gnutls.openpgp_crt_deinit(crt)
2285
 
            raise gnutls.CertificateSecurityError("Verify failed")
 
1860
            gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
 
1861
            raise (gnutls.errors.CertificateSecurityError
 
1862
                   ("Verify failed"))
2286
1863
        # New buffer for the fingerprint
2287
1864
        buf = ctypes.create_string_buffer(20)
2288
1865
        buf_len = ctypes.c_size_t()
2289
1866
        # Get the fingerprint from the certificate into the buffer
2290
 
        gnutls.openpgp_crt_get_fingerprint(crt, ctypes.byref(buf),
2291
 
                                           ctypes.byref(buf_len))
 
1867
        (gnutls.library.functions
 
1868
         .gnutls_openpgp_crt_get_fingerprint(crt, ctypes.byref(buf),
 
1869
                                             ctypes.byref(buf_len)))
2292
1870
        # Deinit the certificate
2293
 
        gnutls.openpgp_crt_deinit(crt)
 
1871
        gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
2294
1872
        # Convert the buffer to a Python bytestring
2295
1873
        fpr = ctypes.string_at(buf, buf_len.value)
2296
1874
        # Convert the bytestring to hexadecimal notation
2300
1878
 
2301
1879
class MultiprocessingMixIn(object):
2302
1880
    """Like socketserver.ThreadingMixIn, but with multiprocessing"""
2303
 
    
2304
1881
    def sub_process_main(self, request, address):
2305
1882
        try:
2306
1883
            self.finish_request(request, address)
2318
1895
 
2319
1896
class MultiprocessingMixInWithPipe(MultiprocessingMixIn, object):
2320
1897
    """ adds a pipe to the MixIn """
2321
 
    
2322
1898
    def process_request(self, request, client_address):
2323
1899
        """Overrides and wraps the original process_request().
2324
1900
        
2333
1909
    
2334
1910
    def add_pipe(self, parent_pipe, proc):
2335
1911
        """Dummy function; override as necessary"""
2336
 
        raise NotImplementedError()
 
1912
        raise NotImplementedError
2337
1913
 
2338
1914
 
2339
1915
class IPv6_TCPServer(MultiprocessingMixInWithPipe,
2345
1921
        interface:      None or a network interface name (string)
2346
1922
        use_ipv6:       Boolean; to use IPv6 or not
2347
1923
    """
2348
 
    
2349
1924
    def __init__(self, server_address, RequestHandlerClass,
2350
 
                 interface=None,
2351
 
                 use_ipv6=True,
2352
 
                 socketfd=None):
 
1925
                 interface=None, use_ipv6=True, socketfd=None):
2353
1926
        """If socketfd is set, use that file descriptor instead of
2354
1927
        creating a new one with socket.socket().
2355
1928
        """
2396
1969
                             self.interface)
2397
1970
            else:
2398
1971
                try:
2399
 
                    self.socket.setsockopt(
2400
 
                        socket.SOL_SOCKET, SO_BINDTODEVICE,
2401
 
                        (self.interface + "\0").encode("utf-8"))
 
1972
                    self.socket.setsockopt(socket.SOL_SOCKET,
 
1973
                                           SO_BINDTODEVICE,
 
1974
                                           str(self.interface + '\0'))
2402
1975
                except socket.error as error:
2403
1976
                    if error.errno == errno.EPERM:
2404
1977
                        logger.error("No permission to bind to"
2422
1995
                self.server_address = (any_address,
2423
1996
                                       self.server_address[1])
2424
1997
            elif not self.server_address[1]:
2425
 
                self.server_address = (self.server_address[0], 0)
 
1998
                self.server_address = (self.server_address[0],
 
1999
                                       0)
2426
2000
#                 if self.interface:
2427
2001
#                     self.server_address = (self.server_address[0],
2428
2002
#                                            0, # port
2442
2016
    
2443
2017
    Assumes a gobject.MainLoop event loop.
2444
2018
    """
2445
 
    
2446
2019
    def __init__(self, server_address, RequestHandlerClass,
2447
 
                 interface=None,
2448
 
                 use_ipv6=True,
2449
 
                 clients=None,
2450
 
                 gnutls_priority=None,
2451
 
                 use_dbus=True,
2452
 
                 socketfd=None):
 
2020
                 interface=None, use_ipv6=True, clients=None,
 
2021
                 gnutls_priority=None, use_dbus=True, socketfd=None):
2453
2022
        self.enabled = False
2454
2023
        self.clients = clients
2455
2024
        if self.clients is None:
2461
2030
                                interface = interface,
2462
2031
                                use_ipv6 = use_ipv6,
2463
2032
                                socketfd = socketfd)
2464
 
    
2465
2033
    def server_activate(self):
2466
2034
        if self.enabled:
2467
2035
            return socketserver.TCPServer.server_activate(self)
2471
2039
    
2472
2040
    def add_pipe(self, parent_pipe, proc):
2473
2041
        # Call "handle_ipc" for both data and EOF events
2474
 
        gobject.io_add_watch(
2475
 
            parent_pipe.fileno(),
2476
 
            gobject.IO_IN | gobject.IO_HUP,
2477
 
            functools.partial(self.handle_ipc,
2478
 
                              parent_pipe = parent_pipe,
2479
 
                              proc = proc))
 
2042
        gobject.io_add_watch(parent_pipe.fileno(),
 
2043
                             gobject.IO_IN | gobject.IO_HUP,
 
2044
                             functools.partial(self.handle_ipc,
 
2045
                                               parent_pipe =
 
2046
                                               parent_pipe,
 
2047
                                               proc = proc))
2480
2048
    
2481
 
    def handle_ipc(self, source, condition,
2482
 
                   parent_pipe=None,
2483
 
                   proc = None,
2484
 
                   client_object=None):
 
2049
    def handle_ipc(self, source, condition, parent_pipe=None,
 
2050
                   proc = None, client_object=None):
2485
2051
        # error, or the other end of multiprocessing.Pipe has closed
2486
2052
        if condition & (gobject.IO_ERR | gobject.IO_HUP):
2487
2053
            # Wait for other process to exit
2510
2076
                parent_pipe.send(False)
2511
2077
                return False
2512
2078
            
2513
 
            gobject.io_add_watch(
2514
 
                parent_pipe.fileno(),
2515
 
                gobject.IO_IN | gobject.IO_HUP,
2516
 
                functools.partial(self.handle_ipc,
2517
 
                                  parent_pipe = parent_pipe,
2518
 
                                  proc = proc,
2519
 
                                  client_object = client))
 
2079
            gobject.io_add_watch(parent_pipe.fileno(),
 
2080
                                 gobject.IO_IN | gobject.IO_HUP,
 
2081
                                 functools.partial(self.handle_ipc,
 
2082
                                                   parent_pipe =
 
2083
                                                   parent_pipe,
 
2084
                                                   proc = proc,
 
2085
                                                   client_object =
 
2086
                                                   client))
2520
2087
            parent_pipe.send(True)
2521
2088
            # remove the old hook in favor of the new above hook on
2522
2089
            # same fileno
2528
2095
            
2529
2096
            parent_pipe.send(('data', getattr(client_object,
2530
2097
                                              funcname)(*args,
2531
 
                                                        **kwargs)))
 
2098
                                                         **kwargs)))
2532
2099
        
2533
2100
        if command == 'getattr':
2534
2101
            attrname = request[1]
2535
 
            if isinstance(client_object.__getattribute__(attrname),
2536
 
                          collections.Callable):
2537
 
                parent_pipe.send(('function', ))
 
2102
            if callable(client_object.__getattribute__(attrname)):
 
2103
                parent_pipe.send(('function',))
2538
2104
            else:
2539
 
                parent_pipe.send((
2540
 
                    'data', client_object.__getattribute__(attrname)))
 
2105
                parent_pipe.send(('data', client_object
 
2106
                                  .__getattribute__(attrname)))
2541
2107
        
2542
2108
        if command == 'setattr':
2543
2109
            attrname = request[1]
2574
2140
    # avoid excessive use of external libraries.
2575
2141
    
2576
2142
    # New type for defining tokens, syntax, and semantics all-in-one
2577
 
    Token = collections.namedtuple("Token", (
2578
 
        "regexp",  # To match token; if "value" is not None, must have
2579
 
                   # a "group" containing digits
2580
 
        "value",   # datetime.timedelta or None
2581
 
        "followers"))           # Tokens valid after this token
 
2143
    Token = collections.namedtuple("Token",
 
2144
                                   ("regexp", # To match token; if
 
2145
                                              # "value" is not None,
 
2146
                                              # must have a "group"
 
2147
                                              # containing digits
 
2148
                                    "value",  # datetime.timedelta or
 
2149
                                              # None
 
2150
                                    "followers")) # Tokens valid after
 
2151
                                                  # this token
2582
2152
    # RFC 3339 "duration" tokens, syntax, and semantics; taken from
2583
2153
    # the "duration" ABNF definition in RFC 3339, Appendix A.
2584
2154
    token_end = Token(re.compile(r"$"), None, frozenset())
2585
2155
    token_second = Token(re.compile(r"(\d+)S"),
2586
2156
                         datetime.timedelta(seconds=1),
2587
 
                         frozenset((token_end, )))
 
2157
                         frozenset((token_end,)))
2588
2158
    token_minute = Token(re.compile(r"(\d+)M"),
2589
2159
                         datetime.timedelta(minutes=1),
2590
2160
                         frozenset((token_second, token_end)))
2606
2176
                       frozenset((token_month, token_end)))
2607
2177
    token_week = Token(re.compile(r"(\d+)W"),
2608
2178
                       datetime.timedelta(weeks=1),
2609
 
                       frozenset((token_end, )))
 
2179
                       frozenset((token_end,)))
2610
2180
    token_duration = Token(re.compile(r"P"), None,
2611
2181
                           frozenset((token_year, token_month,
2612
2182
                                      token_day, token_time,
2613
 
                                      token_week)))
 
2183
                                      token_week))),
2614
2184
    # Define starting values
2615
2185
    value = datetime.timedelta() # Value so far
2616
2186
    found_token = None
2617
 
    followers = frozenset((token_duration, )) # Following valid tokens
 
2187
    followers = frozenset(token_duration,) # Following valid tokens
2618
2188
    s = duration                # String left to parse
2619
2189
    # Loop until end token is found
2620
2190
    while found_token is not token_end:
2637
2207
                break
2638
2208
        else:
2639
2209
            # No currently valid tokens were found
2640
 
            raise ValueError("Invalid RFC 3339 duration: {!r}"
2641
 
                             .format(duration))
 
2210
            raise ValueError("Invalid RFC 3339 duration")
2642
2211
    # End token found
2643
2212
    return value
2644
2213
 
2668
2237
    timevalue = datetime.timedelta(0)
2669
2238
    for s in interval.split():
2670
2239
        try:
2671
 
            suffix = s[-1]
 
2240
            suffix = unicode(s[-1])
2672
2241
            value = int(s[:-1])
2673
2242
            if suffix == "d":
2674
2243
                delta = datetime.timedelta(value)
2681
2250
            elif suffix == "w":
2682
2251
                delta = datetime.timedelta(0, 0, 0, 0, 0, 0, value)
2683
2252
            else:
2684
 
                raise ValueError("Unknown suffix {!r}".format(suffix))
2685
 
        except IndexError as e:
 
2253
                raise ValueError("Unknown suffix {0!r}"
 
2254
                                 .format(suffix))
 
2255
        except (ValueError, IndexError) as e:
2686
2256
            raise ValueError(*(e.args))
2687
2257
        timevalue += delta
2688
2258
    return timevalue
2704
2274
        null = os.open(os.devnull, os.O_NOCTTY | os.O_RDWR)
2705
2275
        if not stat.S_ISCHR(os.fstat(null).st_mode):
2706
2276
            raise OSError(errno.ENODEV,
2707
 
                          "{} not a character device"
 
2277
                          "{0} not a character device"
2708
2278
                          .format(os.devnull))
2709
2279
        os.dup2(null, sys.stdin.fileno())
2710
2280
        os.dup2(null, sys.stdout.fileno())
2720
2290
    
2721
2291
    parser = argparse.ArgumentParser()
2722
2292
    parser.add_argument("-v", "--version", action="version",
2723
 
                        version = "%(prog)s {}".format(version),
 
2293
                        version = "%(prog)s {0}".format(version),
2724
2294
                        help="show version number and exit")
2725
2295
    parser.add_argument("-i", "--interface", metavar="IF",
2726
2296
                        help="Bind to interface IF")
2759
2329
                        help="Directory to save/restore state in")
2760
2330
    parser.add_argument("--foreground", action="store_true",
2761
2331
                        help="Run in foreground", default=None)
2762
 
    parser.add_argument("--no-zeroconf", action="store_false",
2763
 
                        dest="zeroconf", help="Do not use Zeroconf",
2764
 
                        default=None)
2765
2332
    
2766
2333
    options = parser.parse_args()
2767
2334
    
2768
2335
    if options.check:
2769
2336
        import doctest
2770
 
        fail_count, test_count = doctest.testmod()
2771
 
        sys.exit(os.EX_OK if fail_count == 0 else 1)
 
2337
        doctest.testmod()
 
2338
        sys.exit()
2772
2339
    
2773
2340
    # Default values for config file for server-global settings
2774
2341
    server_defaults = { "interface": "",
2776
2343
                        "port": "",
2777
2344
                        "debug": "False",
2778
2345
                        "priority":
2779
 
                        "SECURE256:!CTYPE-X.509:+CTYPE-OPENPGP:!RSA"
2780
 
                        ":+SIGN-DSA-SHA256",
 
2346
                        "SECURE256:!CTYPE-X.509:+CTYPE-OPENPGP:+SIGN-RSA-SHA224",
2781
2347
                        "servicename": "Mandos",
2782
2348
                        "use_dbus": "True",
2783
2349
                        "use_ipv6": "True",
2786
2352
                        "socket": "",
2787
2353
                        "statedir": "/var/lib/mandos",
2788
2354
                        "foreground": "False",
2789
 
                        "zeroconf": "True",
2790
 
                    }
 
2355
                        }
2791
2356
    
2792
2357
    # Parse config file for server-global settings
2793
2358
    server_config = configparser.SafeConfigParser(server_defaults)
2794
2359
    del server_defaults
2795
 
    server_config.read(os.path.join(options.configdir, "mandos.conf"))
 
2360
    server_config.read(os.path.join(options.configdir,
 
2361
                                    "mandos.conf"))
2796
2362
    # Convert the SafeConfigParser object to a dict
2797
2363
    server_settings = server_config.defaults()
2798
2364
    # Use the appropriate methods on the non-string config options
2816
2382
    # Override the settings from the config file with command line
2817
2383
    # options, if set.
2818
2384
    for option in ("interface", "address", "port", "debug",
2819
 
                   "priority", "servicename", "configdir", "use_dbus",
2820
 
                   "use_ipv6", "debuglevel", "restore", "statedir",
2821
 
                   "socket", "foreground", "zeroconf"):
 
2385
                   "priority", "servicename", "configdir",
 
2386
                   "use_dbus", "use_ipv6", "debuglevel", "restore",
 
2387
                   "statedir", "socket", "foreground"):
2822
2388
        value = getattr(options, option)
2823
2389
        if value is not None:
2824
2390
            server_settings[option] = value
2825
2391
    del options
2826
2392
    # Force all strings to be unicode
2827
2393
    for option in server_settings.keys():
2828
 
        if isinstance(server_settings[option], bytes):
2829
 
            server_settings[option] = (server_settings[option]
2830
 
                                       .decode("utf-8"))
 
2394
        if type(server_settings[option]) is str:
 
2395
            server_settings[option] = unicode(server_settings[option])
2831
2396
    # Force all boolean options to be boolean
2832
2397
    for option in ("debug", "use_dbus", "use_ipv6", "restore",
2833
 
                   "foreground", "zeroconf"):
 
2398
                   "foreground"):
2834
2399
        server_settings[option] = bool(server_settings[option])
2835
2400
    # Debug implies foreground
2836
2401
    if server_settings["debug"]:
2839
2404
    
2840
2405
    ##################################################################
2841
2406
    
2842
 
    if (not server_settings["zeroconf"]
2843
 
        and not (server_settings["port"]
2844
 
                 or server_settings["socket"] != "")):
2845
 
        parser.error("Needs port or socket to work without Zeroconf")
2846
 
    
2847
2407
    # For convenience
2848
2408
    debug = server_settings["debug"]
2849
2409
    debuglevel = server_settings["debuglevel"]
2852
2412
    stored_state_path = os.path.join(server_settings["statedir"],
2853
2413
                                     stored_state_file)
2854
2414
    foreground = server_settings["foreground"]
2855
 
    zeroconf = server_settings["zeroconf"]
2856
2415
    
2857
2416
    if debug:
2858
2417
        initlogger(debug, logging.DEBUG)
2864
2423
            initlogger(debug, level)
2865
2424
    
2866
2425
    if server_settings["servicename"] != "Mandos":
2867
 
        syslogger.setFormatter(
2868
 
            logging.Formatter('Mandos ({}) [%(process)d]:'
2869
 
                              ' %(levelname)s: %(message)s'.format(
2870
 
                                  server_settings["servicename"])))
 
2426
        syslogger.setFormatter(logging.Formatter
 
2427
                               ('Mandos ({0}) [%(process)d]:'
 
2428
                                ' %(levelname)s: %(message)s'
 
2429
                                .format(server_settings
 
2430
                                        ["servicename"])))
2871
2431
    
2872
2432
    # Parse config file with clients
2873
2433
    client_config = configparser.SafeConfigParser(Client
2878
2438
    global mandos_dbus_service
2879
2439
    mandos_dbus_service = None
2880
2440
    
2881
 
    socketfd = None
2882
 
    if server_settings["socket"] != "":
2883
 
        socketfd = server_settings["socket"]
2884
 
    tcp_server = MandosServer(
2885
 
        (server_settings["address"], server_settings["port"]),
2886
 
        ClientHandler,
2887
 
        interface=(server_settings["interface"] or None),
2888
 
        use_ipv6=use_ipv6,
2889
 
        gnutls_priority=server_settings["priority"],
2890
 
        use_dbus=use_dbus,
2891
 
        socketfd=socketfd)
 
2441
    tcp_server = MandosServer((server_settings["address"],
 
2442
                               server_settings["port"]),
 
2443
                              ClientHandler,
 
2444
                              interface=(server_settings["interface"]
 
2445
                                         or None),
 
2446
                              use_ipv6=use_ipv6,
 
2447
                              gnutls_priority=
 
2448
                              server_settings["priority"],
 
2449
                              use_dbus=use_dbus,
 
2450
                              socketfd=(server_settings["socket"]
 
2451
                                        or None))
2892
2452
    if not foreground:
2893
 
        pidfilename = "/run/mandos.pid"
2894
 
        if not os.path.isdir("/run/."):
2895
 
            pidfilename = "/var/run/mandos.pid"
 
2453
        pidfilename = "/var/run/mandos.pid"
2896
2454
        pidfile = None
2897
2455
        try:
2898
 
            pidfile = codecs.open(pidfilename, "w", encoding="utf-8")
 
2456
            pidfile = open(pidfilename, "w")
2899
2457
        except IOError as e:
2900
2458
            logger.error("Could not open file %r", pidfilename,
2901
2459
                         exc_info=e)
2915
2473
        os.setuid(uid)
2916
2474
    except OSError as error:
2917
2475
        if error.errno != errno.EPERM:
2918
 
            raise
 
2476
            raise error
2919
2477
    
2920
2478
    if debug:
2921
2479
        # Enable all possible GnuTLS debugging
2922
2480
        
2923
2481
        # "Use a log level over 10 to enable all debugging options."
2924
2482
        # - GnuTLS manual
2925
 
        gnutls.global_set_log_level(11)
 
2483
        gnutls.library.functions.gnutls_global_set_log_level(11)
2926
2484
        
2927
 
        @gnutls.log_func
 
2485
        @gnutls.library.types.gnutls_log_func
2928
2486
        def debug_gnutls(level, string):
2929
2487
            logger.debug("GnuTLS: %s", string[:-1])
2930
2488
        
2931
 
        gnutls.global_set_log_function(debug_gnutls)
 
2489
        (gnutls.library.functions
 
2490
         .gnutls_global_set_log_function(debug_gnutls))
2932
2491
        
2933
2492
        # Redirect stdin so all checkers get /dev/null
2934
2493
        null = os.open(os.devnull, os.O_NOCTTY | os.O_RDWR)
2954
2513
    if use_dbus:
2955
2514
        try:
2956
2515
            bus_name = dbus.service.BusName("se.recompile.Mandos",
2957
 
                                            bus,
2958
 
                                            do_not_queue=True)
2959
 
            old_bus_name = dbus.service.BusName(
2960
 
                "se.bsnet.fukt.Mandos", bus,
2961
 
                do_not_queue=True)
2962
 
        except dbus.exceptions.DBusException as e:
 
2516
                                            bus, do_not_queue=True)
 
2517
            old_bus_name = (dbus.service.BusName
 
2518
                            ("se.bsnet.fukt.Mandos", bus,
 
2519
                             do_not_queue=True))
 
2520
        except dbus.exceptions.NameExistsException as e:
2963
2521
            logger.error("Disabling D-Bus:", exc_info=e)
2964
2522
            use_dbus = False
2965
2523
            server_settings["use_dbus"] = False
2966
2524
            tcp_server.use_dbus = False
2967
 
    if zeroconf:
2968
 
        protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
2969
 
        service = AvahiServiceToSyslog(
2970
 
            name = server_settings["servicename"],
2971
 
            servicetype = "_mandos._tcp",
2972
 
            protocol = protocol,
2973
 
            bus = bus)
2974
 
        if server_settings["interface"]:
2975
 
            service.interface = if_nametoindex(
2976
 
                server_settings["interface"].encode("utf-8"))
 
2525
    protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
 
2526
    service = AvahiServiceToSyslog(name =
 
2527
                                   server_settings["servicename"],
 
2528
                                   servicetype = "_mandos._tcp",
 
2529
                                   protocol = protocol, bus = bus)
 
2530
    if server_settings["interface"]:
 
2531
        service.interface = (if_nametoindex
 
2532
                             (str(server_settings["interface"])))
2977
2533
    
2978
2534
    global multiprocessing_manager
2979
2535
    multiprocessing_manager = multiprocessing.Manager()
2998
2554
    if server_settings["restore"]:
2999
2555
        try:
3000
2556
            with open(stored_state_path, "rb") as stored_state:
3001
 
                clients_data, old_client_settings = pickle.load(
3002
 
                    stored_state)
 
2557
                clients_data, old_client_settings = (pickle.load
 
2558
                                                     (stored_state))
3003
2559
            os.remove(stored_state_path)
3004
2560
        except IOError as e:
3005
2561
            if e.errno == errno.ENOENT:
3006
 
                logger.warning("Could not load persistent state:"
3007
 
                               " {}".format(os.strerror(e.errno)))
 
2562
                logger.warning("Could not load persistent state: {0}"
 
2563
                                .format(os.strerror(e.errno)))
3008
2564
            else:
3009
2565
                logger.critical("Could not load persistent state:",
3010
2566
                                exc_info=e)
3011
2567
                raise
3012
2568
        except EOFError as e:
3013
2569
            logger.warning("Could not load persistent state: "
3014
 
                           "EOFError:",
3015
 
                           exc_info=e)
 
2570
                           "EOFError:", exc_info=e)
3016
2571
    
3017
2572
    with PGPEngine() as pgp:
3018
 
        for client_name, client in clients_data.items():
 
2573
        for client_name, client in clients_data.iteritems():
3019
2574
            # Skip removed clients
3020
2575
            if client_name not in client_settings:
3021
2576
                continue
3030
2585
                    # For each value in new config, check if it
3031
2586
                    # differs from the old config value (Except for
3032
2587
                    # the "secret" attribute)
3033
 
                    if (name != "secret"
3034
 
                        and (value !=
3035
 
                             old_client_settings[client_name][name])):
 
2588
                    if (name != "secret" and
 
2589
                        value != old_client_settings[client_name]
 
2590
                        [name]):
3036
2591
                        client[name] = value
3037
2592
                except KeyError:
3038
2593
                    pass
3039
2594
            
3040
2595
            # Clients who has passed its expire date can still be
3041
 
            # enabled if its last checker was successful.  A Client
 
2596
            # enabled if its last checker was successful.  Clients
3042
2597
            # whose checker succeeded before we stored its state is
3043
2598
            # assumed to have successfully run all checkers during
3044
2599
            # downtime.
3046
2601
                if datetime.datetime.utcnow() >= client["expires"]:
3047
2602
                    if not client["last_checked_ok"]:
3048
2603
                        logger.warning(
3049
 
                            "disabling client {} - Client never "
3050
 
                            "performed a successful checker".format(
3051
 
                                client_name))
 
2604
                            "disabling client {0} - Client never "
 
2605
                            "performed a successful checker"
 
2606
                            .format(client_name))
3052
2607
                        client["enabled"] = False
3053
2608
                    elif client["last_checker_status"] != 0:
3054
2609
                        logger.warning(
3055
 
                            "disabling client {} - Client last"
3056
 
                            " checker failed with error code"
3057
 
                            " {}".format(
3058
 
                                client_name,
3059
 
                                client["last_checker_status"]))
 
2610
                            "disabling client {0} - Client "
 
2611
                            "last checker failed with error code {1}"
 
2612
                            .format(client_name,
 
2613
                                    client["last_checker_status"]))
3060
2614
                        client["enabled"] = False
3061
2615
                    else:
3062
 
                        client["expires"] = (
3063
 
                            datetime.datetime.utcnow()
3064
 
                            + client["timeout"])
 
2616
                        client["expires"] = (datetime.datetime
 
2617
                                             .utcnow()
 
2618
                                             + client["timeout"])
3065
2619
                        logger.debug("Last checker succeeded,"
3066
 
                                     " keeping {} enabled".format(
3067
 
                                         client_name))
 
2620
                                     " keeping {0} enabled"
 
2621
                                     .format(client_name))
3068
2622
            try:
3069
 
                client["secret"] = pgp.decrypt(
3070
 
                    client["encrypted_secret"],
3071
 
                    client_settings[client_name]["secret"])
 
2623
                client["secret"] = (
 
2624
                    pgp.decrypt(client["encrypted_secret"],
 
2625
                                client_settings[client_name]
 
2626
                                ["secret"]))
3072
2627
            except PGPError:
3073
2628
                # If decryption fails, we use secret from new settings
3074
 
                logger.debug("Failed to decrypt {} old secret".format(
3075
 
                    client_name))
3076
 
                client["secret"] = (client_settings[client_name]
3077
 
                                    ["secret"])
 
2629
                logger.debug("Failed to decrypt {0} old secret"
 
2630
                             .format(client_name))
 
2631
                client["secret"] = (
 
2632
                    client_settings[client_name]["secret"])
3078
2633
    
3079
2634
    # Add/remove clients based on new changes made to config
3080
2635
    for client_name in (set(old_client_settings)
3085
2640
        clients_data[client_name] = client_settings[client_name]
3086
2641
    
3087
2642
    # Create all client objects
3088
 
    for client_name, client in clients_data.items():
 
2643
    for client_name, client in clients_data.iteritems():
3089
2644
        tcp_server.clients[client_name] = client_class(
3090
 
            name = client_name,
3091
 
            settings = client,
 
2645
            name = client_name, settings = client,
3092
2646
            server_settings = server_settings)
3093
2647
    
3094
2648
    if not tcp_server.clients:
3096
2650
    
3097
2651
    if not foreground:
3098
2652
        if pidfile is not None:
3099
 
            pid = os.getpid()
3100
2653
            try:
3101
2654
                with pidfile:
3102
 
                    print(pid, file=pidfile)
 
2655
                    pid = os.getpid()
 
2656
                    pidfile.write(str(pid) + "\n".encode("utf-8"))
3103
2657
            except IOError:
3104
2658
                logger.error("Could not write to file %r with PID %d",
3105
2659
                             pidfilename, pid)
3110
2664
    signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit())
3111
2665
    
3112
2666
    if use_dbus:
3113
 
        
3114
 
        @alternate_dbus_interfaces(
3115
 
            { "se.recompile.Mandos": "se.bsnet.fukt.Mandos" })
3116
 
        class MandosDBusService(DBusObjectWithObjectManager):
 
2667
        @alternate_dbus_interfaces({"se.recompile.Mandos":
 
2668
                                        "se.bsnet.fukt.Mandos"})
 
2669
        class MandosDBusService(DBusObjectWithProperties):
3117
2670
            """A D-Bus proxy object"""
3118
 
            
3119
2671
            def __init__(self):
3120
2672
                dbus.service.Object.__init__(self, bus, "/")
3121
 
            
3122
2673
            _interface = "se.recompile.Mandos"
3123
2674
            
 
2675
            @dbus_interface_annotations(_interface)
 
2676
            def _foo(self):
 
2677
                return { "org.freedesktop.DBus.Property"
 
2678
                         ".EmitsChangedSignal":
 
2679
                             "false"}
 
2680
            
3124
2681
            @dbus.service.signal(_interface, signature="o")
3125
2682
            def ClientAdded(self, objpath):
3126
2683
                "D-Bus signal"
3131
2688
                "D-Bus signal"
3132
2689
                pass
3133
2690
            
3134
 
            @dbus_annotations({"org.freedesktop.DBus.Deprecated":
3135
 
                               "true"})
3136
2691
            @dbus.service.signal(_interface, signature="os")
3137
2692
            def ClientRemoved(self, objpath, name):
3138
2693
                "D-Bus signal"
3139
2694
                pass
3140
2695
            
3141
 
            @dbus_annotations({"org.freedesktop.DBus.Deprecated":
3142
 
                               "true"})
3143
2696
            @dbus.service.method(_interface, out_signature="ao")
3144
2697
            def GetAllClients(self):
3145
2698
                "D-Bus method"
3146
 
                return dbus.Array(c.dbus_object_path for c in
 
2699
                return dbus.Array(c.dbus_object_path
 
2700
                                  for c in
3147
2701
                                  tcp_server.clients.itervalues())
3148
2702
            
3149
 
            @dbus_annotations({"org.freedesktop.DBus.Deprecated":
3150
 
                               "true"})
3151
2703
            @dbus.service.method(_interface,
3152
2704
                                 out_signature="a{oa{sv}}")
3153
2705
            def GetAllClientsWithProperties(self):
3154
2706
                "D-Bus method"
3155
2707
                return dbus.Dictionary(
3156
 
                    { c.dbus_object_path: c.GetAll(
3157
 
                        "se.recompile.Mandos.Client")
3158
 
                      for c in tcp_server.clients.itervalues() },
 
2708
                    ((c.dbus_object_path, c.GetAll(""))
 
2709
                     for c in tcp_server.clients.itervalues()),
3159
2710
                    signature="oa{sv}")
3160
2711
            
3161
2712
            @dbus.service.method(_interface, in_signature="o")
3165
2716
                    if c.dbus_object_path == object_path:
3166
2717
                        del tcp_server.clients[c.name]
3167
2718
                        c.remove_from_connection()
3168
 
                        # Don't signal the disabling
 
2719
                        # Don't signal anything except ClientRemoved
3169
2720
                        c.disable(quiet=True)
3170
 
                        # Emit D-Bus signal for removal
3171
 
                        self.client_removed_signal(c)
 
2721
                        # Emit D-Bus signal
 
2722
                        self.ClientRemoved(object_path, c.name)
3172
2723
                        return
3173
2724
                raise KeyError(object_path)
3174
2725
            
3175
2726
            del _interface
3176
 
            
3177
 
            @dbus.service.method(dbus.OBJECT_MANAGER_IFACE,
3178
 
                                 out_signature = "a{oa{sa{sv}}}")
3179
 
            def GetManagedObjects(self):
3180
 
                """D-Bus method"""
3181
 
                return dbus.Dictionary(
3182
 
                    { client.dbus_object_path:
3183
 
                      dbus.Dictionary(
3184
 
                          { interface: client.GetAll(interface)
3185
 
                            for interface in
3186
 
                                 client._get_all_interface_names()})
3187
 
                      for client in tcp_server.clients.values()})
3188
 
            
3189
 
            def client_added_signal(self, client):
3190
 
                """Send the new standard signal and the old signal"""
3191
 
                if use_dbus:
3192
 
                    # New standard signal
3193
 
                    self.InterfacesAdded(
3194
 
                        client.dbus_object_path,
3195
 
                        dbus.Dictionary(
3196
 
                            { interface: client.GetAll(interface)
3197
 
                              for interface in
3198
 
                              client._get_all_interface_names()}))
3199
 
                    # Old signal
3200
 
                    self.ClientAdded(client.dbus_object_path)
3201
 
            
3202
 
            def client_removed_signal(self, client):
3203
 
                """Send the new standard signal and the old signal"""
3204
 
                if use_dbus:
3205
 
                    # New standard signal
3206
 
                    self.InterfacesRemoved(
3207
 
                        client.dbus_object_path,
3208
 
                        client._get_all_interface_names())
3209
 
                    # Old signal
3210
 
                    self.ClientRemoved(client.dbus_object_path,
3211
 
                                       client.name)
3212
2727
        
3213
2728
        mandos_dbus_service = MandosDBusService()
3214
2729
    
3215
2730
    def cleanup():
3216
2731
        "Cleanup function; run on exit"
3217
 
        if zeroconf:
3218
 
            service.cleanup()
 
2732
        service.cleanup()
3219
2733
        
3220
2734
        multiprocessing.active_children()
3221
2735
        wnull.close()
3235
2749
                
3236
2750
                # A list of attributes that can not be pickled
3237
2751
                # + secret.
3238
 
                exclude = { "bus", "changedstate", "secret",
3239
 
                            "checker", "server_settings" }
3240
 
                for name, typ in inspect.getmembers(dbus.service
3241
 
                                                    .Object):
 
2752
                exclude = set(("bus", "changedstate", "secret",
 
2753
                               "checker", "server_settings"))
 
2754
                for name, typ in (inspect.getmembers
 
2755
                                  (dbus.service.Object)):
3242
2756
                    exclude.add(name)
3243
2757
                
3244
2758
                client_dict["encrypted_secret"] = (client
3251
2765
                del client_settings[client.name]["secret"]
3252
2766
        
3253
2767
        try:
3254
 
            with tempfile.NamedTemporaryFile(
3255
 
                    mode='wb',
3256
 
                    suffix=".pickle",
3257
 
                    prefix='clients-',
3258
 
                    dir=os.path.dirname(stored_state_path),
3259
 
                    delete=False) as stored_state:
 
2768
            with (tempfile.NamedTemporaryFile
 
2769
                  (mode='wb', suffix=".pickle", prefix='clients-',
 
2770
                   dir=os.path.dirname(stored_state_path),
 
2771
                   delete=False)) as stored_state:
3260
2772
                pickle.dump((clients, client_settings), stored_state)
3261
 
                tempname = stored_state.name
 
2773
                tempname=stored_state.name
3262
2774
            os.rename(tempname, stored_state_path)
3263
2775
        except (IOError, OSError) as e:
3264
2776
            if not debug:
3267
2779
                except NameError:
3268
2780
                    pass
3269
2781
            if e.errno in (errno.ENOENT, errno.EACCES, errno.EEXIST):
3270
 
                logger.warning("Could not save persistent state: {}"
 
2782
                logger.warning("Could not save persistent state: {0}"
3271
2783
                               .format(os.strerror(e.errno)))
3272
2784
            else:
3273
2785
                logger.warning("Could not save persistent state:",
3274
2786
                               exc_info=e)
3275
 
                raise
 
2787
                raise e
3276
2788
        
3277
2789
        # Delete all clients, and settings from config
3278
2790
        while tcp_server.clients:
3279
2791
            name, client = tcp_server.clients.popitem()
3280
2792
            if use_dbus:
3281
2793
                client.remove_from_connection()
3282
 
            # Don't signal the disabling
 
2794
            # Don't signal anything except ClientRemoved
3283
2795
            client.disable(quiet=True)
3284
 
            # Emit D-Bus signal for removal
3285
2796
            if use_dbus:
3286
 
                mandos_dbus_service.client_removed_signal(client)
 
2797
                # Emit D-Bus signal
 
2798
                mandos_dbus_service.ClientRemoved(client
 
2799
                                                  .dbus_object_path,
 
2800
                                                  client.name)
3287
2801
        client_settings.clear()
3288
2802
    
3289
2803
    atexit.register(cleanup)
3290
2804
    
3291
2805
    for client in tcp_server.clients.itervalues():
3292
2806
        if use_dbus:
3293
 
            # Emit D-Bus signal for adding
3294
 
            mandos_dbus_service.client_added_signal(client)
 
2807
            # Emit D-Bus signal
 
2808
            mandos_dbus_service.ClientAdded(client.dbus_object_path)
3295
2809
        # Need to initiate checking of clients
3296
2810
        if client.enabled:
3297
2811
            client.init_checker()
3300
2814
    tcp_server.server_activate()
3301
2815
    
3302
2816
    # Find out what port we got
3303
 
    if zeroconf:
3304
 
        service.port = tcp_server.socket.getsockname()[1]
 
2817
    service.port = tcp_server.socket.getsockname()[1]
3305
2818
    if use_ipv6:
3306
2819
        logger.info("Now listening on address %r, port %d,"
3307
2820
                    " flowinfo %d, scope_id %d",
3313
2826
    #service.interface = tcp_server.socket.getsockname()[3]
3314
2827
    
3315
2828
    try:
3316
 
        if zeroconf:
3317
 
            # From the Avahi example code
3318
 
            try:
3319
 
                service.activate()
3320
 
            except dbus.exceptions.DBusException as error:
3321
 
                logger.critical("D-Bus Exception", exc_info=error)
3322
 
                cleanup()
3323
 
                sys.exit(1)
3324
 
            # End of Avahi example code
 
2829
        # From the Avahi example code
 
2830
        try:
 
2831
            service.activate()
 
2832
        except dbus.exceptions.DBusException as error:
 
2833
            logger.critical("D-Bus Exception", exc_info=error)
 
2834
            cleanup()
 
2835
            sys.exit(1)
 
2836
        # End of Avahi example code
3325
2837
        
3326
2838
        gobject.io_add_watch(tcp_server.fileno(), gobject.IO_IN,
3327
2839
                             lambda *args, **kwargs:
3342
2854
    # Must run before the D-Bus bus name gets deregistered
3343
2855
    cleanup()
3344
2856
 
3345
 
 
3346
2857
if __name__ == '__main__':
3347
2858
    main()