/mandos/trunk

To get this branch, use:
bzr branch http://bzr.recompile.se/loggerhead/mandos/trunk
3 by Björn Påhlsson
Python based server
1
#!/usr/bin/python
15 by Teddy Hogeborn
* mandos-clients.conf ([foo]): Uncommented.
2
# -*- mode: python; coding: utf-8 -*-
16 by Teddy Hogeborn
* Makefile: Include targets for all binaries.
3
# 
4
# Mandos server - give out binary blobs to connecting clients.
5
# 
6
# This program is partly derived from an example program for an Avahi
7
# service publisher, downloaded from
8
# <http://avahi.org/wiki/PythonPublishExample>.  This includes the
336 by Teddy Hogeborn
Code cleanup.
9
# methods "add", "remove", "server_state_changed",
10
# "entry_group_state_changed", "cleanup", and "activate" in the
11
# "AvahiService" class, and some lines in "main".
16 by Teddy Hogeborn
* Makefile: Include targets for all binaries.
12
# 
28 by Teddy Hogeborn
* server.conf: New file.
13
# Everything else is
466 by Teddy Hogeborn
Update copyright year to "2011" wherever appropriate.
14
# Copyright © 2008-2011 Teddy Hogeborn
15
# Copyright © 2008-2011 Björn Påhlsson
16 by Teddy Hogeborn
* Makefile: Include targets for all binaries.
16
# 
17
# This program is free software: you can redistribute it and/or modify
18
# it under the terms of the GNU General Public License as published by
19
# the Free Software Foundation, either version 3 of the License, or
20
# (at your option) any later version.
21
#
22
#     This program is distributed in the hope that it will be useful,
23
#     but WITHOUT ANY WARRANTY; without even the implied warranty of
24
#     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
25
#     GNU General Public License for more details.
26
# 
27
# You should have received a copy of the GNU General Public License
109 by Teddy Hogeborn
* .bzrignore: New.
28
# along with this program.  If not, see
29
# <http://www.gnu.org/licenses/>.
16 by Teddy Hogeborn
* Makefile: Include targets for all binaries.
30
# 
505.1.2 by Teddy Hogeborn
Change "fukt.bsnet.se" to "recompile.se" throughout.
31
# Contact the authors at <mandos@recompile.se>.
16 by Teddy Hogeborn
* Makefile: Include targets for all binaries.
32
# 
3 by Björn Påhlsson
Python based server
33
463.1.5 by teddy at bsnet
* mandos: Use unicode string literals.
34
from __future__ import (division, absolute_import, print_function,
35
                        unicode_literals)
10 by Teddy Hogeborn
* server.py: Bug fix: Do "from __future__ import division".
36
335 by Teddy Hogeborn
* mandos: Import "SocketServer" as "socketserver" and "ConfigParser"
37
import SocketServer as socketserver
3 by Björn Påhlsson
Python based server
38
import socket
474 by teddy at bsnet
* mandos: Use the new argparse library instead of optparse.
39
import argparse
3 by Björn Påhlsson
Python based server
40
import datetime
41
import errno
42
import gnutls.crypto
43
import gnutls.connection
44
import gnutls.errors
12 by Teddy Hogeborn
* mandos-clients.conf ([foo]/dn, [foo]/password, [braxen_client]/dn,
45
import gnutls.library.functions
46
import gnutls.library.constants
47
import gnutls.library.types
335 by Teddy Hogeborn
* mandos: Import "SocketServer" as "socketserver" and "ConfigParser"
48
import ConfigParser as configparser
4 by Teddy Hogeborn
* server.py (Client.created, Client.next_check): New.
49
import sys
9 by Teddy Hogeborn
* client.cpp (main): Get t_old early since it is used on error exits.
50
import re
51
import os
52
import signal
10 by Teddy Hogeborn
* server.py: Bug fix: Do "from __future__ import division".
53
import subprocess
15 by Teddy Hogeborn
* mandos-clients.conf ([foo]): Uncommented.
54
import atexit
55
import stat
16 by Teddy Hogeborn
* Makefile: Include targets for all binaries.
56
import logging
57
import logging.handlers
163 by Teddy Hogeborn
* Makefile (PIDDIR, USER, GROUP): Removed.
58
import pwd
411 by Teddy Hogeborn
More consistent terminology: Clients are no longer "invalid" - they
59
import contextlib
333 by Teddy Hogeborn
Minor code cleanup; one minor bug fix.
60
import struct
61
import fcntl
337 by Teddy Hogeborn
Code cleanup. Move some global stuff into main.
62
import functools
411 by Teddy Hogeborn
More consistent terminology: Clients are no longer "invalid" - they
63
import cPickle as pickle
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
64
import multiprocessing
24.1.185 by Björn Påhlsson
working transition code for going between se.bsnet.fukt to se.recompile
65
import types
518.1.1 by Björn Påhlsson
Persistent state: New feature. Client state is now stored when mandos
66
import hashlib
5 by Teddy Hogeborn
* server.py (server_metaclass): New.
67
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
68
import dbus
237.1.1 by Teddy Hogeborn
First steps of a D-Bus interface to the server.
69
import dbus.service
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
70
import gobject
71
import avahi
72
from dbus.mainloop.glib import DBusGMainLoop
12 by Teddy Hogeborn
* mandos-clients.conf ([foo]/dn, [foo]/password, [braxen_client]/dn,
73
import ctypes
215 by Teddy Hogeborn
* mandos: Remove unused "select" module. Import "ctypes.util".
74
import ctypes.util
380 by Teddy Hogeborn
Use D-Bus properties instead of our own methods.
75
import xml.dom.minidom
76
import inspect
518.1.1 by Björn Påhlsson
Persistent state: New feature. Client state is now stored when mandos
77
import Crypto.Cipher.AES
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
78
331 by Teddy Hogeborn
Minor code cleanup, and a bug fix.
79
try:
80
    SO_BINDTODEVICE = socket.SO_BINDTODEVICE
81
except AttributeError:
82
    try:
83
        from IN import SO_BINDTODEVICE
84
    except ImportError:
338 by Teddy Hogeborn
* mandos: Minor doc string fixes.
85
        SO_BINDTODEVICE = None
331 by Teddy Hogeborn
Minor code cleanup, and a bug fix.
86
87
237.4.20 by Björn Påhlsson
* Makefile (version): Changed to "1.4.1".
88
version = "1.4.1"
13 by Björn Påhlsson
Added following support:
89
518.1.1 by Björn Påhlsson
Persistent state: New feature. Client state is now stored when mandos
90
stored_state_path = "/var/lib/mandos/clients.pickle"
91
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
92
#logger = logging.getLogger('mandos')
93
logger = logging.Logger('mandos')
237.1.2 by Teddy Hogeborn
Further steps towards a D-Bus server interface, plus minor syntax
94
syslogger = (logging.handlers.SysLogHandler
95
             (facility = logging.handlers.SysLogHandler.LOG_DAEMON,
463.1.6 by teddy at bsnet
* mandos: Bug fix: pass str("/dev/log") to logging.SysLogHandler(),
96
              address = str("/dev/log")))
237.1.2 by Teddy Hogeborn
Further steps towards a D-Bus server interface, plus minor syntax
97
syslogger.setFormatter(logging.Formatter
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
98
                       ('Mandos [%(process)d]: %(levelname)s:'
99
                        ' %(message)s'))
15 by Teddy Hogeborn
* mandos-clients.conf ([foo]): Uncommented.
100
logger.addHandler(syslogger)
13 by Björn Påhlsson
Added following support:
101
61 by Teddy Hogeborn
* mandos (console): Define handler globally.
102
console = logging.StreamHandler()
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
103
console.setFormatter(logging.Formatter('%(name)s [%(process)d]:'
104
                                       ' %(levelname)s:'
105
                                       ' %(message)s'))
61 by Teddy Hogeborn
* mandos (console): Define handler globally.
106
logger.addHandler(console)
28 by Teddy Hogeborn
* server.conf: New file.
107
108
class AvahiError(Exception):
242 by Teddy Hogeborn
* mandos (AvahiError): Converted to use unicode. All users changed.
109
    def __init__(self, value, *args, **kwargs):
28 by Teddy Hogeborn
* server.conf: New file.
110
        self.value = value
242 by Teddy Hogeborn
* mandos (AvahiError): Converted to use unicode. All users changed.
111
        super(AvahiError, self).__init__(value, *args, **kwargs)
112
    def __unicode__(self):
113
        return unicode(repr(self.value))
28 by Teddy Hogeborn
* server.conf: New file.
114
115
class AvahiServiceError(AvahiError):
116
    pass
117
118
class AvahiGroupError(AvahiError):
119
    pass
120
121
122
class AvahiService(object):
45 by Teddy Hogeborn
* server.py: Cosmetic changes.
123
    """An Avahi (Zeroconf) service.
331 by Teddy Hogeborn
Minor code cleanup, and a bug fix.
124
    
45 by Teddy Hogeborn
* server.py: Cosmetic changes.
125
    Attributes:
28 by Teddy Hogeborn
* server.conf: New file.
126
    interface: integer; avahi.IF_UNSPEC or an interface index.
127
               Used to optionally bind to the specified interface.
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
128
    name: string; Example: 'Mandos'
129
    type: string; Example: '_mandos._tcp'.
45 by Teddy Hogeborn
* server.py: Cosmetic changes.
130
                  See <http://www.dns-sd.org/ServiceTypes.html>
131
    port: integer; what port to announce
132
    TXT: list of strings; TXT record for the service
133
    domain: string; Domain to publish on, default to .local if empty.
134
    host: string; Host to publish records for, default is localhost
135
    max_renames: integer; maximum number of renames
136
    rename_count: integer; counter so we only rename after collisions
137
                  a sensible number of times
336 by Teddy Hogeborn
Code cleanup.
138
    group: D-Bus Entry Group
139
    server: D-Bus Server
338 by Teddy Hogeborn
* mandos: Minor doc string fixes.
140
    bus: dbus.SystemBus()
28 by Teddy Hogeborn
* server.conf: New file.
141
    """
142
    def __init__(self, interface = avahi.IF_UNSPEC, name = None,
237.1.2 by Teddy Hogeborn
Further steps towards a D-Bus server interface, plus minor syntax
143
                 servicetype = None, port = None, TXT = None,
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
144
                 domain = "", host = "", max_renames = 32768,
337 by Teddy Hogeborn
Code cleanup. Move some global stuff into main.
145
                 protocol = avahi.PROTO_UNSPEC, bus = None):
28 by Teddy Hogeborn
* server.conf: New file.
146
        self.interface = interface
147
        self.name = name
215 by Teddy Hogeborn
* mandos: Remove unused "select" module. Import "ctypes.util".
148
        self.type = servicetype
28 by Teddy Hogeborn
* server.conf: New file.
149
        self.port = port
237.1.2 by Teddy Hogeborn
Further steps towards a D-Bus server interface, plus minor syntax
150
        self.TXT = TXT if TXT is not None else []
28 by Teddy Hogeborn
* server.conf: New file.
151
        self.domain = domain
152
        self.host = host
153
        self.rename_count = 0
76 by Teddy Hogeborn
* plugins.d/password-request.c (init_gnutls_global): Renamed
154
        self.max_renames = max_renames
314 by Teddy Hogeborn
Support not using IPv6 in server:
155
        self.protocol = protocol
336 by Teddy Hogeborn
Code cleanup.
156
        self.group = None       # our entry group
157
        self.server = None
337 by Teddy Hogeborn
Code cleanup. Move some global stuff into main.
158
        self.bus = bus
482 by Teddy Hogeborn
* mandos: Tolerate restarting Avahi servers. Also Changed to new
159
        self.entry_group_state_changed_match = None
28 by Teddy Hogeborn
* server.conf: New file.
160
    def rename(self):
161
        """Derived from the Avahi example code"""
162
        if self.rename_count >= self.max_renames:
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
163
            logger.critical("No suitable Zeroconf service name found"
164
                            " after %i retries, exiting.",
215 by Teddy Hogeborn
* mandos: Remove unused "select" module. Import "ctypes.util".
165
                            self.rename_count)
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
166
            raise AvahiServiceError("Too many renames")
505.1.3 by Teddy Hogeborn
* mandos: Break long lines.
167
        self.name = unicode(self.server
168
                            .GetAlternativeServiceName(self.name))
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
169
        logger.info("Changing Zeroconf service name to %r ...",
24.1.155 by Björn Påhlsson
mandos server: Added debuglevel that adjust at what level information
170
                    self.name)
237.1.2 by Teddy Hogeborn
Further steps towards a D-Bus server interface, plus minor syntax
171
        syslogger.setFormatter(logging.Formatter
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
172
                               ('Mandos (%s) [%%(process)d]:'
173
                                ' %%(levelname)s: %%(message)s'
327 by Teddy Hogeborn
Merge from pipe IPC branch.
174
                                % self.name))
28 by Teddy Hogeborn
* server.conf: New file.
175
        self.remove()
24.1.160 by Björn Påhlsson
fixed bug with local name collisions after a non-local name collision
176
        try:
177
            self.add()
482 by Teddy Hogeborn
* mandos: Tolerate restarting Avahi servers. Also Changed to new
178
        except dbus.exceptions.DBusException as error:
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
179
            logger.critical("DBusException: %s", error)
24.1.160 by Björn Påhlsson
fixed bug with local name collisions after a non-local name collision
180
            self.cleanup()
181
            os._exit(1)
28 by Teddy Hogeborn
* server.conf: New file.
182
        self.rename_count += 1
183
    def remove(self):
184
        """Derived from the Avahi example code"""
482 by Teddy Hogeborn
* mandos: Tolerate restarting Avahi servers. Also Changed to new
185
        if self.entry_group_state_changed_match is not None:
186
            self.entry_group_state_changed_match.remove()
187
            self.entry_group_state_changed_match = None
483 by Teddy Hogeborn
* mandos: Never call .Reset() on a defunct Avahi entry group.
188
        if self.group is not None:
189
            self.group.Reset()
28 by Teddy Hogeborn
* server.conf: New file.
190
    def add(self):
191
        """Derived from the Avahi example code"""
482 by Teddy Hogeborn
* mandos: Tolerate restarting Avahi servers. Also Changed to new
192
        self.remove()
483 by Teddy Hogeborn
* mandos: Never call .Reset() on a defunct Avahi entry group.
193
        if self.group is None:
194
            self.group = dbus.Interface(
195
                self.bus.get_object(avahi.DBUS_NAME,
196
                                    self.server.EntryGroupNew()),
197
                avahi.DBUS_INTERFACE_ENTRY_GROUP)
482 by Teddy Hogeborn
* mandos: Tolerate restarting Avahi servers. Also Changed to new
198
        self.entry_group_state_changed_match = (
199
            self.group.connect_to_signal(
200
                'StateChanged', self .entry_group_state_changed))
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
201
        logger.debug("Adding Zeroconf service '%s' of type '%s' ...",
336 by Teddy Hogeborn
Code cleanup.
202
                     self.name, self.type)
203
        self.group.AddService(
204
            self.interface,
205
            self.protocol,
206
            dbus.UInt32(0),     # flags
207
            self.name, self.type,
208
            self.domain, self.host,
209
            dbus.UInt16(self.port),
210
            avahi.string_array_to_txt_array(self.TXT))
211
        self.group.Commit()
212
    def entry_group_state_changed(self, state, error):
213
        """Derived from the Avahi example code"""
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
214
        logger.debug("Avahi entry group state change: %i", state)
336 by Teddy Hogeborn
Code cleanup.
215
        
216
        if state == avahi.ENTRY_GROUP_ESTABLISHED:
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
217
            logger.debug("Zeroconf service established.")
336 by Teddy Hogeborn
Code cleanup.
218
        elif state == avahi.ENTRY_GROUP_COLLISION:
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
219
            logger.info("Zeroconf service name collision.")
336 by Teddy Hogeborn
Code cleanup.
220
            self.rename()
221
        elif state == avahi.ENTRY_GROUP_FAILURE:
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
222
            logger.critical("Avahi: Error in group state changed %s",
336 by Teddy Hogeborn
Code cleanup.
223
                            unicode(error))
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
224
            raise AvahiGroupError("State changed: %s"
336 by Teddy Hogeborn
Code cleanup.
225
                                  % unicode(error))
226
    def cleanup(self):
227
        """Derived from the Avahi example code"""
483 by Teddy Hogeborn
* mandos: Never call .Reset() on a defunct Avahi entry group.
228
        if self.group is not None:
229
            try:
230
                self.group.Free()
231
            except (dbus.exceptions.UnknownMethodException,
232
                    dbus.exceptions.DBusException) as e:
233
                pass
234
            self.group = None
482 by Teddy Hogeborn
* mandos: Tolerate restarting Avahi servers. Also Changed to new
235
        self.remove()
236
    def server_state_changed(self, state, error=None):
336 by Teddy Hogeborn
Code cleanup.
237
        """Derived from the Avahi example code"""
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
238
        logger.debug("Avahi server state change: %i", state)
482 by Teddy Hogeborn
* mandos: Tolerate restarting Avahi servers. Also Changed to new
239
        bad_states = { avahi.SERVER_INVALID:
240
                           "Zeroconf server invalid",
241
                       avahi.SERVER_REGISTERING: None,
242
                       avahi.SERVER_COLLISION:
243
                           "Zeroconf server name collision",
244
                       avahi.SERVER_FAILURE:
245
                           "Zeroconf server failure" }
246
        if state in bad_states:
483 by Teddy Hogeborn
* mandos: Never call .Reset() on a defunct Avahi entry group.
247
            if bad_states[state] is not None:
248
                if error is None:
249
                    logger.error(bad_states[state])
250
                else:
251
                    logger.error(bad_states[state] + ": %r", error)
252
            self.cleanup()
336 by Teddy Hogeborn
Code cleanup.
253
        elif state == avahi.SERVER_RUNNING:
254
            self.add()
482 by Teddy Hogeborn
* mandos: Tolerate restarting Avahi servers. Also Changed to new
255
        else:
483 by Teddy Hogeborn
* mandos: Never call .Reset() on a defunct Avahi entry group.
256
            if error is None:
257
                logger.debug("Unknown state: %r", state)
258
            else:
259
                logger.debug("Unknown state: %r: %r", state, error)
336 by Teddy Hogeborn
Code cleanup.
260
    def activate(self):
261
        """Derived from the Avahi example code"""
262
        if self.server is None:
263
            self.server = dbus.Interface(
337 by Teddy Hogeborn
Code cleanup. Move some global stuff into main.
264
                self.bus.get_object(avahi.DBUS_NAME,
482 by Teddy Hogeborn
* mandos: Tolerate restarting Avahi servers. Also Changed to new
265
                                    avahi.DBUS_PATH_SERVER,
266
                                    follow_name_owner_changes=True),
336 by Teddy Hogeborn
Code cleanup.
267
                avahi.DBUS_INTERFACE_SERVER)
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
268
        self.server.connect_to_signal("StateChanged",
336 by Teddy Hogeborn
Code cleanup.
269
                                 self.server_state_changed)
270
        self.server_state_changed(self.server.GetState())
238 by Teddy Hogeborn
First version of a somewhat complete D-Bus server interface. Also
271
272
24.1.182 by Björn Påhlsson
Refactoring code related to PropertyChanged dbus signal. Made sending
273
def _timedelta_to_milliseconds(td):
274
    "Convert a datetime.timedelta() to milliseconds"
275
    return ((td.days * 24 * 60 * 60 * 1000)
276
            + (td.seconds * 1000)
277
            + (td.microseconds // 1000))
278
        
328 by Teddy Hogeborn
* mandos (Client): Move all D-Bus code to new "ClientDBus" class.
279
class Client(object):
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
280
    """A representation of a client host served by this server.
331 by Teddy Hogeborn
Minor code cleanup, and a bug fix.
281
    
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
282
    Attributes:
438 by Teddy Hogeborn
* mandos (Client.runtime_expansions): New attribute containing the
283
    _approved:   bool(); 'None' if not yet approved/disapproved
284
    approval_delay: datetime.timedelta(); Time to wait for approval
285
    approval_duration: datetime.timedelta(); Duration of one approval
238 by Teddy Hogeborn
First version of a somewhat complete D-Bus server interface. Also
286
    checker:    subprocess.Popen(); a running checker process used
287
                                    to see if the client lives.
288
                                    'None' if no process is running.
442 by Teddy Hogeborn
* DBUS-API: Document new "LastApprovalRequest" client property.
289
    checker_callback_tag: a gobject event source tag, or None
438 by Teddy Hogeborn
* mandos (Client.runtime_expansions): New attribute containing the
290
    checker_command: string; External command which is run to check
291
                     if client lives.  %() expansions are done at
12 by Teddy Hogeborn
* mandos-clients.conf ([foo]/dn, [foo]/password, [braxen_client]/dn,
292
                     runtime with vars(self) as dict, so that for
293
                     instance %(name)s can be used in the command.
438 by Teddy Hogeborn
* mandos (Client.runtime_expansions): New attribute containing the
294
    checker_initiator_tag: a gobject event source tag, or None
295
    created:    datetime.datetime(); (UTC) object creation
518.1.1 by Björn Påhlsson
Persistent state: New feature. Client state is now stored when mandos
296
    client_structure: Object describing what attributes a client has
297
                      and is used for storing the client at exit
315 by Teddy Hogeborn
* mandos (Client.current_checker_command): New attribute.
298
    current_checker_command: string; current running checker_command
442 by Teddy Hogeborn
* DBUS-API: Document new "LastApprovalRequest" client property.
299
    disable_initiator_tag: a gobject event source tag, or None
438 by Teddy Hogeborn
* mandos (Client.runtime_expansions): New attribute containing the
300
    enabled:    bool()
301
    fingerprint: string (40 or 32 hexadecimal digits); used to
302
                 uniquely identify the client
303
    host:       string; available for use by the checker command
304
    interval:   datetime.timedelta(); How often to start a new checker
442 by Teddy Hogeborn
* DBUS-API: Document new "LastApprovalRequest" client property.
305
    last_approval_request: datetime.datetime(); (UTC) or None
438 by Teddy Hogeborn
* mandos (Client.runtime_expansions): New attribute containing the
306
    last_checked_ok: datetime.datetime(); (UTC) or None
518.1.1 by Björn Påhlsson
Persistent state: New feature. Client state is now stored when mandos
307
    Last_checker_status: integer between 0 and 255 reflecting exit status
308
                         of last checker. -1 reflect crashed checker.
438 by Teddy Hogeborn
* mandos (Client.runtime_expansions): New attribute containing the
309
    last_enabled: datetime.datetime(); (UTC)
310
    name:       string; from the config file, used in log messages and
311
                        D-Bus identifiers
312
    secret:     bytestring; sent verbatim (over TLS) to client
313
    timeout:    datetime.timedelta(); How long from last_checked_ok
314
                                      until this client is disabled
24.1.179 by Björn Påhlsson
New feature:
315
    extended_timeout:   extra long timeout when password has been sent
438 by Teddy Hogeborn
* mandos (Client.runtime_expansions): New attribute containing the
316
    runtime_expansions: Allowed attributes for runtime expansion.
497 by Teddy Hogeborn
* DBUS-API: Document new "Expires" and "ExtendedTimeout" properties.
317
    expires:    datetime.datetime(); time (UTC) when a client will be
24.1.179 by Björn Påhlsson
New feature:
318
                disabled, or None
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
319
    """
333 by Teddy Hogeborn
Minor code cleanup; one minor bug fix.
320
    
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
321
    runtime_expansions = ("approval_delay", "approval_duration",
322
                          "created", "enabled", "fingerprint",
323
                          "host", "interval", "last_checked_ok",
324
                          "last_enabled", "name", "timeout")
24.1.185 by Björn Påhlsson
working transition code for going between se.bsnet.fukt to se.recompile
325
    
243 by Teddy Hogeborn
* mandos (Client.timeout, Client.interval): Changed from being a
326
    def timeout_milliseconds(self):
327
        "Return the 'timeout' attribute in milliseconds"
24.1.182 by Björn Påhlsson
Refactoring code related to PropertyChanged dbus signal. Made sending
328
        return _timedelta_to_milliseconds(self.timeout)
24.1.185 by Björn Påhlsson
working transition code for going between se.bsnet.fukt to se.recompile
329
    
24.1.179 by Björn Påhlsson
New feature:
330
    def extended_timeout_milliseconds(self):
331
        "Return the 'extended_timeout' attribute in milliseconds"
505.1.4 by Teddy Hogeborn
Removed superflous white space.
332
        return _timedelta_to_milliseconds(self.extended_timeout)
243 by Teddy Hogeborn
* mandos (Client.timeout, Client.interval): Changed from being a
333
    
334
    def interval_milliseconds(self):
335
        "Return the 'interval' attribute in milliseconds"
24.1.182 by Björn Påhlsson
Refactoring code related to PropertyChanged dbus signal. Made sending
336
        return _timedelta_to_milliseconds(self.interval)
24.1.185 by Björn Påhlsson
working transition code for going between se.bsnet.fukt to se.recompile
337
    
422 by Teddy Hogeborn
Rename all D-Bus properties to conform to D-Bus naming conventions;
338
    def approval_delay_milliseconds(self):
24.1.182 by Björn Påhlsson
Refactoring code related to PropertyChanged dbus signal. Made sending
339
        return _timedelta_to_milliseconds(self.approval_delay)
243 by Teddy Hogeborn
* mandos (Client.timeout, Client.interval): Changed from being a
340
    
518.1.1 by Björn Påhlsson
Persistent state: New feature. Client state is now stored when mandos
341
    def __init__(self, name = None, config=None):
45 by Teddy Hogeborn
* server.py: Cosmetic changes.
342
        """Note: the 'checker' key in 'config' sets the
343
        'checker_command' attribute and *not* the 'checker'
344
        attribute."""
243 by Teddy Hogeborn
* mandos (Client.timeout, Client.interval): Changed from being a
345
        self.name = name
215 by Teddy Hogeborn
* mandos: Remove unused "select" module. Import "ctypes.util".
346
        if config is None:
347
            config = {}
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
348
        logger.debug("Creating client %r", self.name)
45 by Teddy Hogeborn
* server.py: Cosmetic changes.
349
        # Uppercase and remove spaces from fingerprint for later
350
        # comparison purposes with return value from the fingerprint()
351
        # function
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
352
        self.fingerprint = (config["fingerprint"].upper()
353
                            .replace(" ", ""))
354
        logger.debug("  Fingerprint: %s", self.fingerprint)
355
        if "secret" in config:
356
            self.secret = config["secret"].decode("base64")
357
        elif "secfile" in config:
411 by Teddy Hogeborn
More consistent terminology: Clients are no longer "invalid" - they
358
            with open(os.path.expanduser(os.path.expandvars
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
359
                                         (config["secfile"])),
360
                      "rb") as secfile:
237 by Teddy Hogeborn
* mandos: Also import "with_statement" and "absolute_import" from
361
                self.secret = secfile.read()
3 by Björn Påhlsson
Python based server
362
        else:
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
363
            raise TypeError("No secret or secfile for client %s"
28 by Teddy Hogeborn
* server.conf: New file.
364
                            % self.name)
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
365
        self.host = config.get("host", "")
237.1.2 by Teddy Hogeborn
Further steps towards a D-Bus server interface, plus minor syntax
366
        self.created = datetime.datetime.utcnow()
518.1.1 by Björn Påhlsson
Persistent state: New feature. Client state is now stored when mandos
367
        self.enabled = True
442 by Teddy Hogeborn
* DBUS-API: Document new "LastApprovalRequest" client property.
368
        self.last_approval_request = None
518.1.1 by Björn Påhlsson
Persistent state: New feature. Client state is now stored when mandos
369
        self.last_enabled = datetime.datetime.utcnow()
28 by Teddy Hogeborn
* server.conf: New file.
370
        self.last_checked_ok = None
518.1.1 by Björn Påhlsson
Persistent state: New feature. Client state is now stored when mandos
371
        self.last_checker_status = 0
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
372
        self.timeout = string_to_delta(config["timeout"])
505.1.3 by Teddy Hogeborn
* mandos: Break long lines.
373
        self.extended_timeout = string_to_delta(config
374
                                                ["extended_timeout"])
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
375
        self.interval = string_to_delta(config["interval"])
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
376
        self.checker = None
377
        self.checker_initiator_tag = None
239 by Teddy Hogeborn
* mandos (_datetime_to_dbus_struct): Renamed to "_datetime_to_dbus";
378
        self.disable_initiator_tag = None
518.1.1 by Björn Påhlsson
Persistent state: New feature. Client state is now stored when mandos
379
        self.expires = datetime.datetime.utcnow() + self.timeout
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
380
        self.checker_callback_tag = None
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
381
        self.checker_command = config["checker"]
315 by Teddy Hogeborn
* mandos (Client.current_checker_command): New attribute.
382
        self.current_checker_command = None
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
383
        self._approved = None
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
384
        self.approved_by_default = config.get("approved_by_default",
24.2.1 by teddy at bsnet
* debian/control (mandos/Depends): Added "python-urwid".
385
                                              True)
24.1.150 by Björn Påhlsson
* mandos: Added ClientDBus.approve_pending property. Exposed
386
        self.approvals_pending = 0
422 by Teddy Hogeborn
Rename all D-Bus properties to conform to D-Bus naming conventions;
387
        self.approval_delay = string_to_delta(
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
388
            config["approval_delay"])
422 by Teddy Hogeborn
Rename all D-Bus properties to conform to D-Bus naming conventions;
389
        self.approval_duration = string_to_delta(
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
390
            config["approval_duration"])
505.1.3 by Teddy Hogeborn
* mandos: Break long lines.
391
        self.changedstate = (multiprocessing_manager
392
                             .Condition(multiprocessing_manager
393
                                        .Lock()))
518.1.1 by Björn Påhlsson
Persistent state: New feature. Client state is now stored when mandos
394
        self.client_structure = [attr for attr in self.__dict__.iterkeys() if not attr.startswith("_")]
395
        self.client_structure.append("client_structure")
396
397
398
        for name, t in inspect.getmembers(type(self),
399
                                          lambda obj: isinstance(obj, property)):
400
            if not name.startswith("_"):
401
                self.client_structure.append(name)
402
    
24.2.4 by teddy at bsnet
* mandos (ClientDBus.approvals_pending): Changed to be a property
403
    
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
404
    def send_changedstate(self):
405
        self.changedstate.acquire()
406
        self.changedstate.notify_all()
407
        self.changedstate.release()
505.1.3 by Teddy Hogeborn
* mandos: Break long lines.
408
    
239 by Teddy Hogeborn
* mandos (_datetime_to_dbus_struct): Renamed to "_datetime_to_dbus";
409
    def enable(self):
16 by Teddy Hogeborn
* Makefile: Include targets for all binaries.
410
        """Start this client's checker and timeout hooks"""
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
411
        if getattr(self, "enabled", False):
341 by Teddy Hogeborn
Code cleanup and one bug fix.
412
            # Already enabled
413
            return
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
414
        self.send_changedstate()
24.1.179 by Björn Påhlsson
New feature:
415
        self.expires = datetime.datetime.utcnow() + self.timeout
239 by Teddy Hogeborn
* mandos (_datetime_to_dbus_struct): Renamed to "_datetime_to_dbus";
416
        self.enabled = True
24.1.182 by Björn Påhlsson
Refactoring code related to PropertyChanged dbus signal. Made sending
417
        self.last_enabled = datetime.datetime.utcnow()
518.1.1 by Björn Påhlsson
Persistent state: New feature. Client state is now stored when mandos
418
        self.init_checker()
237.1.1 by Teddy Hogeborn
First steps of a D-Bus interface to the server.
419
    
402 by Teddy Hogeborn
* mandos (Client.disable): Rename keyword argument "log" to "quiet",
420
    def disable(self, quiet=True):
239 by Teddy Hogeborn
* mandos (_datetime_to_dbus_struct): Renamed to "_datetime_to_dbus";
421
        """Disable this client."""
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
422
        if not getattr(self, "enabled", False):
16 by Teddy Hogeborn
* Makefile: Include targets for all binaries.
423
            return False
402 by Teddy Hogeborn
* mandos (Client.disable): Rename keyword argument "log" to "quiet",
424
        if not quiet:
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
425
            self.send_changedstate()
426
        if not quiet:
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
427
            logger.info("Disabling client %s", self.name)
428
        if getattr(self, "disable_initiator_tag", False):
239 by Teddy Hogeborn
* mandos (_datetime_to_dbus_struct): Renamed to "_datetime_to_dbus";
429
            gobject.source_remove(self.disable_initiator_tag)
430
            self.disable_initiator_tag = None
24.1.179 by Björn Påhlsson
New feature:
431
        self.expires = None
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
432
        if getattr(self, "checker_initiator_tag", False):
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
433
            gobject.source_remove(self.checker_initiator_tag)
434
            self.checker_initiator_tag = None
435
        self.stop_checker()
239 by Teddy Hogeborn
* mandos (_datetime_to_dbus_struct): Renamed to "_datetime_to_dbus";
436
        self.enabled = False
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
437
        # Do not run this again if called by a gobject.timeout_add
438
        return False
237.1.1 by Teddy Hogeborn
First steps of a D-Bus interface to the server.
439
    
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
440
    def __del__(self):
239 by Teddy Hogeborn
* mandos (_datetime_to_dbus_struct): Renamed to "_datetime_to_dbus";
441
        self.disable()
518.1.1 by Björn Påhlsson
Persistent state: New feature. Client state is now stored when mandos
442
443
    def init_checker(self):
444
        # Schedule a new checker to be started an 'interval' from now,
445
        # and every interval from then on.
446
        self.checker_initiator_tag = (gobject.timeout_add
447
                                      (self.interval_milliseconds(),
448
                                       self.start_checker))
449
        # Schedule a disable() when 'timeout' has passed
450
        self.disable_initiator_tag = (gobject.timeout_add
451
                                   (self.timeout_milliseconds(),
452
                                    self.disable))
453
        # Also start a new checker *right now*.
454
        self.start_checker()
455
456
        
238 by Teddy Hogeborn
First version of a somewhat complete D-Bus server interface. Also
457
    def checker_callback(self, pid, condition, command):
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
458
        """The checker has completed, so take appropriate actions."""
16 by Teddy Hogeborn
* Makefile: Include targets for all binaries.
459
        self.checker_callback_tag = None
460
        self.checker = None
280 by Teddy Hogeborn
* mandos (Client.CheckerCompleted): Changed signature to "nxs"; return
461
        if os.WIFEXITED(condition):
518.1.1 by Björn Påhlsson
Persistent state: New feature. Client state is now stored when mandos
462
            self.last_checker_status =  os.WEXITSTATUS(condition)
463
            if self.last_checker_status == 0:
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
464
                logger.info("Checker for %(name)s succeeded",
280 by Teddy Hogeborn
* mandos (Client.CheckerCompleted): Changed signature to "nxs"; return
465
                            vars(self))
281 by Teddy Hogeborn
* mandos (Client.bump_timeout): Renamed to "checked_ok". All callers
466
                self.checked_ok()
280 by Teddy Hogeborn
* mandos (Client.CheckerCompleted): Changed signature to "nxs"; return
467
            else:
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
468
                logger.info("Checker for %(name)s failed",
280 by Teddy Hogeborn
* mandos (Client.CheckerCompleted): Changed signature to "nxs"; return
469
                            vars(self))
470
        else:
518.1.1 by Björn Påhlsson
Persistent state: New feature. Client state is now stored when mandos
471
            self.last_checker_status = -1
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
472
            logger.warning("Checker for %(name)s crashed?",
13 by Björn Påhlsson
Added following support:
473
                           vars(self))
237.1.1 by Teddy Hogeborn
First steps of a D-Bus interface to the server.
474
    
24.1.179 by Björn Påhlsson
New feature:
475
    def checked_ok(self, timeout=None):
237 by Teddy Hogeborn
* mandos: Also import "with_statement" and "absolute_import" from
476
        """Bump up the timeout for this client.
331 by Teddy Hogeborn
Minor code cleanup, and a bug fix.
477
        
237 by Teddy Hogeborn
* mandos: Also import "with_statement" and "absolute_import" from
478
        This should only be called when the client has been seen,
479
        alive and well.
480
        """
24.1.179 by Björn Påhlsson
New feature:
481
        if timeout is None:
482
            timeout = self.timeout
237.1.2 by Teddy Hogeborn
Further steps towards a D-Bus server interface, plus minor syntax
483
        self.last_checked_ok = datetime.datetime.utcnow()
505.1.17 by Teddy Hogeborn
* mandos (Client.checked_ok): Bug fix: Handle disabled client.
484
        if self.disable_initiator_tag is not None:
485
            gobject.source_remove(self.disable_initiator_tag)
486
        if getattr(self, "enabled", False):
487
            self.disable_initiator_tag = (gobject.timeout_add
488
                                          (_timedelta_to_milliseconds
489
                                           (timeout), self.disable))
490
            self.expires = datetime.datetime.utcnow() + timeout
237.1.1 by Teddy Hogeborn
First steps of a D-Bus interface to the server.
491
    
442 by Teddy Hogeborn
* DBUS-API: Document new "LastApprovalRequest" client property.
492
    def need_approval(self):
493
        self.last_approval_request = datetime.datetime.utcnow()
494
    
9 by Teddy Hogeborn
* client.cpp (main): Get t_old early since it is used on error exits.
495
    def start_checker(self):
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
496
        """Start a new checker subprocess if one is not running.
331 by Teddy Hogeborn
Minor code cleanup, and a bug fix.
497
        
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
498
        If a checker already exists, leave it running and do
499
        nothing."""
16 by Teddy Hogeborn
* Makefile: Include targets for all binaries.
500
        # The reason for not killing a running checker is that if we
501
        # did that, then if a checker (for some reason) started
502
        # running slowly and taking more than 'interval' time, the
503
        # client would inevitably timeout, since no checker would get
504
        # a chance to run to completion.  If we instead leave running
505
        # checkers alone, the checker would have to take more time
411 by Teddy Hogeborn
More consistent terminology: Clients are no longer "invalid" - they
506
        # than 'timeout' for the client to be disabled, which is as it
507
        # should be.
315 by Teddy Hogeborn
* mandos (Client.current_checker_command): New attribute.
508
        
509
        # If a checker exists, make sure it is not a zombie
383 by Teddy Hogeborn
* mandos (Client.start_checker): Bug fix: Fix race condition with
510
        try:
315 by Teddy Hogeborn
* mandos (Client.current_checker_command): New attribute.
511
            pid, status = os.waitpid(self.checker.pid, os.WNOHANG)
482 by Teddy Hogeborn
* mandos: Tolerate restarting Avahi servers. Also Changed to new
512
        except (AttributeError, OSError) as error:
383 by Teddy Hogeborn
* mandos (Client.start_checker): Bug fix: Fix race condition with
513
            if (isinstance(error, OSError)
514
                and error.errno != errno.ECHILD):
515
                raise error
516
        else:
315 by Teddy Hogeborn
* mandos (Client.current_checker_command): New attribute.
517
            if pid:
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
518
                logger.warning("Checker was a zombie")
315 by Teddy Hogeborn
* mandos (Client.current_checker_command): New attribute.
519
                gobject.source_remove(self.checker_callback_tag)
520
                self.checker_callback(pid, status,
521
                                      self.current_checker_command)
522
        # Start a new checker if needed
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
523
        if self.checker is None:
12 by Teddy Hogeborn
* mandos-clients.conf ([foo]/dn, [foo]/password, [braxen_client]/dn,
524
            try:
238 by Teddy Hogeborn
First version of a somewhat complete D-Bus server interface. Also
525
                # In case checker_command has exactly one % operator
526
                command = self.checker_command % self.host
12 by Teddy Hogeborn
* mandos-clients.conf ([foo]/dn, [foo]/password, [braxen_client]/dn,
527
            except TypeError:
28 by Teddy Hogeborn
* server.conf: New file.
528
                # Escape attributes for the shell
438 by Teddy Hogeborn
* mandos (Client.runtime_expansions): New attribute containing the
529
                escaped_attrs = dict(
530
                    (attr,
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
531
                     re.escape(unicode(str(getattr(self, attr, "")),
438 by Teddy Hogeborn
* mandos (Client.runtime_expansions): New attribute containing the
532
                                       errors=
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
533
                                       'replace')))
438 by Teddy Hogeborn
* mandos (Client.runtime_expansions): New attribute containing the
534
                    for attr in
535
                    self.runtime_expansions)
24.1.185 by Björn Påhlsson
working transition code for going between se.bsnet.fukt to se.recompile
536
                
13 by Björn Påhlsson
Added following support:
537
                try:
238 by Teddy Hogeborn
First version of a somewhat complete D-Bus server interface. Also
538
                    command = self.checker_command % escaped_attrs
482 by Teddy Hogeborn
* mandos: Tolerate restarting Avahi servers. Also Changed to new
539
                except TypeError as error:
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
540
                    logger.error('Could not format string "%s":'
541
                                 ' %s', self.checker_command, error)
13 by Björn Påhlsson
Added following support:
542
                    return True # Try again later
328 by Teddy Hogeborn
* mandos (Client): Move all D-Bus code to new "ClientDBus" class.
543
            self.current_checker_command = command
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
544
            try:
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
545
                logger.info("Starting checker %r for %s",
44 by Teddy Hogeborn
* ca.pem: Removed.
546
                            command, self.name)
94 by Teddy Hogeborn
* clients.conf ([DEFAULT]/checker): Update to new default value.
547
                # We don't need to redirect stdout and stderr, since
548
                # in normal mode, that is already done by daemon(),
549
                # and in debug mode we don't want to.  (Stdin is
550
                # always replaced by /dev/null.)
28 by Teddy Hogeborn
* server.conf: New file.
551
                self.checker = subprocess.Popen(command,
552
                                                close_fds=True,
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
553
                                                shell=True, cwd="/")
237.1.2 by Teddy Hogeborn
Further steps towards a D-Bus server interface, plus minor syntax
554
                self.checker_callback_tag = (gobject.child_watch_add
555
                                             (self.checker.pid,
238 by Teddy Hogeborn
First version of a somewhat complete D-Bus server interface. Also
556
                                              self.checker_callback,
557
                                              data=command))
310 by Teddy Hogeborn
* mandos (Client.start_checker): Bug fix: Add extra check in case the
558
                # The checker may have completed before the gobject
559
                # watch was added.  Check for this.
560
                pid, status = os.waitpid(self.checker.pid, os.WNOHANG)
561
                if pid:
562
                    gobject.source_remove(self.checker_callback_tag)
563
                    self.checker_callback(pid, status, command)
482 by Teddy Hogeborn
* mandos: Tolerate restarting Avahi servers. Also Changed to new
564
            except OSError as error:
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
565
                logger.error("Failed to start subprocess: %s",
13 by Björn Påhlsson
Added following support:
566
                             error)
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
567
        # Re-run this periodically if run by gobject.timeout_add
568
        return True
237.1.1 by Teddy Hogeborn
First steps of a D-Bus interface to the server.
569
    
9 by Teddy Hogeborn
* client.cpp (main): Get t_old early since it is used on error exits.
570
    def stop_checker(self):
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
571
        """Force the checker process, if any, to stop."""
16 by Teddy Hogeborn
* Makefile: Include targets for all binaries.
572
        if self.checker_callback_tag:
573
            gobject.source_remove(self.checker_callback_tag)
574
            self.checker_callback_tag = None
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
575
        if getattr(self, "checker", None) is None:
9 by Teddy Hogeborn
* client.cpp (main): Get t_old early since it is used on error exits.
576
            return
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
577
        logger.debug("Stopping checker for %(name)s", vars(self))
16 by Teddy Hogeborn
* Makefile: Include targets for all binaries.
578
        try:
579
            os.kill(self.checker.pid, signal.SIGTERM)
400 by Teddy Hogeborn
* mandos (Client.enable): Bug fix: Start new immediate checker last to
580
            #time.sleep(0.5)
16 by Teddy Hogeborn
* Makefile: Include targets for all binaries.
581
            #if self.checker.poll() is None:
582
            #    os.kill(self.checker.pid, signal.SIGKILL)
482 by Teddy Hogeborn
* mandos: Tolerate restarting Avahi servers. Also Changed to new
583
        except OSError as error:
28 by Teddy Hogeborn
* server.conf: New file.
584
            if error.errno != errno.ESRCH: # No such process
16 by Teddy Hogeborn
* Makefile: Include targets for all binaries.
585
                raise
9 by Teddy Hogeborn
* client.cpp (main): Get t_old early since it is used on error exits.
586
        self.checker = None
328 by Teddy Hogeborn
* mandos (Client): Move all D-Bus code to new "ClientDBus" class.
587
518.1.1 by Björn Påhlsson
Persistent state: New feature. Client state is now stored when mandos
588
    # Encrypts a client secret and stores it in a varible encrypted_secret
589
    def encrypt_secret(self, key):
590
        # Encryption-key need to be specific size, so we hash inputed key
591
        hasheng = hashlib.sha256()
592
        hasheng.update(key)
593
        encryptionkey = hasheng.digest()
594
595
        # Create validation hash so we know at decryption if it was sucessful
596
        hasheng = hashlib.sha256()
597
        hasheng.update(self.secret)
598
        validationhash = hasheng.digest()
599
600
        # Encrypt secret
601
        iv = os.urandom(Crypto.Cipher.AES.block_size)
602
        ciphereng = Crypto.Cipher.AES.new(encryptionkey,
603
                                        Crypto.Cipher.AES.MODE_CFB, iv)
604
        ciphertext = ciphereng.encrypt(validationhash+self.secret)
605
        self.encrypted_secret = (ciphertext, iv)
606
607
    # Decrypt a encrypted client secret
608
    def decrypt_secret(self, key):
609
        # Decryption-key need to be specific size, so we hash inputed key
610
        hasheng = hashlib.sha256()
611
        hasheng.update(key)
612
        encryptionkey = hasheng.digest()
613
614
        # Decrypt encrypted secret
615
        ciphertext, iv = self.encrypted_secret
616
        ciphereng = Crypto.Cipher.AES.new(encryptionkey,
617
                                        Crypto.Cipher.AES.MODE_CFB, iv)
618
        plain = ciphereng.decrypt(ciphertext)
619
620
        # Validate decrypted secret to know if it was succesful
621
        hasheng = hashlib.sha256()
622
        validationhash = plain[:hasheng.digest_size]
623
        secret = plain[hasheng.digest_size:]
624
        hasheng.update(secret)
625
626
        # if validation fails, we use key as new secret. Otherwhise, we use
627
        # the decrypted secret
628
        if hasheng.digest() == validationhash:
629
            self.secret = secret
630
        else:
631
            self.secret = key
632
        del self.encrypted_secret
633
24.1.185 by Björn Påhlsson
working transition code for going between se.bsnet.fukt to se.recompile
634
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
635
def dbus_service_property(dbus_interface, signature="v",
636
                          access="readwrite", byte_arrays=False):
380 by Teddy Hogeborn
Use D-Bus properties instead of our own methods.
637
    """Decorators for marking methods of a DBusObjectWithProperties to
638
    become properties on the D-Bus.
639
    
640
    The decorated method will be called with no arguments by "Get"
641
    and with one argument by "Set".
642
    
643
    The parameters, where they are supported, are the same as
644
    dbus.service.method, except there is only "signature", since the
645
    type from Get() and the type sent to Set() is the same.
646
    """
411 by Teddy Hogeborn
More consistent terminology: Clients are no longer "invalid" - they
647
    # Encoding deeply encoded byte arrays is not supported yet by the
648
    # "Set" method, so we fail early here:
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
649
    if byte_arrays and signature != "ay":
650
        raise ValueError("Byte arrays not supported for non-'ay'"
651
                         " signature %r" % signature)
380 by Teddy Hogeborn
Use D-Bus properties instead of our own methods.
652
    def decorator(func):
653
        func._dbus_is_property = True
654
        func._dbus_interface = dbus_interface
655
        func._dbus_signature = signature
656
        func._dbus_access = access
657
        func._dbus_name = func.__name__
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
658
        if func._dbus_name.endswith("_dbus_property"):
380 by Teddy Hogeborn
Use D-Bus properties instead of our own methods.
659
            func._dbus_name = func._dbus_name[:-14]
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
660
        func._dbus_get_args_options = {'byte_arrays': byte_arrays }
380 by Teddy Hogeborn
Use D-Bus properties instead of our own methods.
661
        return func
662
    return decorator
663
664
665
class DBusPropertyException(dbus.exceptions.DBusException):
666
    """A base class for D-Bus property-related exceptions
667
    """
668
    def __unicode__(self):
669
        return unicode(str(self))
670
671
672
class DBusPropertyAccessException(DBusPropertyException):
673
    """A property's access permissions disallows an operation.
674
    """
675
    pass
676
677
678
class DBusPropertyNotFound(DBusPropertyException):
679
    """An attempt was made to access a non-existing property.
680
    """
681
    pass
682
683
684
class DBusObjectWithProperties(dbus.service.Object):
685
    """A D-Bus object with properties.
24.1.185 by Björn Påhlsson
working transition code for going between se.bsnet.fukt to se.recompile
686
    
380 by Teddy Hogeborn
Use D-Bus properties instead of our own methods.
687
    Classes inheriting from this can use the dbus_service_property
688
    decorator to expose methods as D-Bus properties.  It exposes the
689
    standard Get(), Set(), and GetAll() methods on the D-Bus.
690
    """
691
    
692
    @staticmethod
693
    def _is_dbus_property(obj):
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
694
        return getattr(obj, "_dbus_is_property", False)
380 by Teddy Hogeborn
Use D-Bus properties instead of our own methods.
695
    
696
    def _get_all_dbus_properties(self):
697
        """Returns a generator of (name, attribute) pairs
698
        """
24.1.186 by Björn Påhlsson
transitional stuff actually working
699
        return ((prop.__get__(self)._dbus_name, prop.__get__(self))
700
                for cls in self.__class__.__mro__
505.1.3 by Teddy Hogeborn
* mandos: Break long lines.
701
                for name, prop in
702
                inspect.getmembers(cls, self._is_dbus_property))
380 by Teddy Hogeborn
Use D-Bus properties instead of our own methods.
703
    
704
    def _get_dbus_property(self, interface_name, property_name):
705
        """Returns a bound method if one exists which is a D-Bus
706
        property with the specified name and interface.
707
        """
24.1.186 by Björn Påhlsson
transitional stuff actually working
708
        for cls in  self.__class__.__mro__:
505.1.3 by Teddy Hogeborn
* mandos: Break long lines.
709
            for name, value in (inspect.getmembers
710
                                (cls, self._is_dbus_property)):
711
                if (value._dbus_name == property_name
712
                    and value._dbus_interface == interface_name):
24.1.186 by Björn Påhlsson
transitional stuff actually working
713
                    return value.__get__(self)
24.1.185 by Björn Påhlsson
working transition code for going between se.bsnet.fukt to se.recompile
714
        
380 by Teddy Hogeborn
Use D-Bus properties instead of our own methods.
715
        # No such property
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
716
        raise DBusPropertyNotFound(self.dbus_object_path + ":"
717
                                   + interface_name + "."
380 by Teddy Hogeborn
Use D-Bus properties instead of our own methods.
718
                                   + property_name)
719
    
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
720
    @dbus.service.method(dbus.PROPERTIES_IFACE, in_signature="ss",
721
                         out_signature="v")
380 by Teddy Hogeborn
Use D-Bus properties instead of our own methods.
722
    def Get(self, interface_name, property_name):
723
        """Standard D-Bus property Get() method, see D-Bus standard.
724
        """
725
        prop = self._get_dbus_property(interface_name, property_name)
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
726
        if prop._dbus_access == "write":
380 by Teddy Hogeborn
Use D-Bus properties instead of our own methods.
727
            raise DBusPropertyAccessException(property_name)
728
        value = prop()
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
729
        if not hasattr(value, "variant_level"):
380 by Teddy Hogeborn
Use D-Bus properties instead of our own methods.
730
            return value
731
        return type(value)(value, variant_level=value.variant_level+1)
732
    
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
733
    @dbus.service.method(dbus.PROPERTIES_IFACE, in_signature="ssv")
380 by Teddy Hogeborn
Use D-Bus properties instead of our own methods.
734
    def Set(self, interface_name, property_name, value):
735
        """Standard D-Bus property Set() method, see D-Bus standard.
736
        """
737
        prop = self._get_dbus_property(interface_name, property_name)
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
738
        if prop._dbus_access == "read":
380 by Teddy Hogeborn
Use D-Bus properties instead of our own methods.
739
            raise DBusPropertyAccessException(property_name)
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
740
        if prop._dbus_get_args_options["byte_arrays"]:
411 by Teddy Hogeborn
More consistent terminology: Clients are no longer "invalid" - they
741
            # The byte_arrays option is not supported yet on
742
            # signatures other than "ay".
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
743
            if prop._dbus_signature != "ay":
411 by Teddy Hogeborn
More consistent terminology: Clients are no longer "invalid" - they
744
                raise ValueError
380 by Teddy Hogeborn
Use D-Bus properties instead of our own methods.
745
            value = dbus.ByteArray(''.join(unichr(byte)
746
                                           for byte in value))
747
        prop(value)
748
    
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
749
    @dbus.service.method(dbus.PROPERTIES_IFACE, in_signature="s",
750
                         out_signature="a{sv}")
380 by Teddy Hogeborn
Use D-Bus properties instead of our own methods.
751
    def GetAll(self, interface_name):
752
        """Standard D-Bus property GetAll() method, see D-Bus
753
        standard.
24.1.185 by Björn Påhlsson
working transition code for going between se.bsnet.fukt to se.recompile
754
        
380 by Teddy Hogeborn
Use D-Bus properties instead of our own methods.
755
        Note: Will not include properties with access="write".
756
        """
757
        all = {}
758
        for name, prop in self._get_all_dbus_properties():
759
            if (interface_name
760
                and interface_name != prop._dbus_interface):
761
                # Interface non-empty but did not match
762
                continue
763
            # Ignore write-only properties
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
764
            if prop._dbus_access == "write":
380 by Teddy Hogeborn
Use D-Bus properties instead of our own methods.
765
                continue
766
            value = prop()
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
767
            if not hasattr(value, "variant_level"):
380 by Teddy Hogeborn
Use D-Bus properties instead of our own methods.
768
                all[name] = value
769
                continue
770
            all[name] = type(value)(value, variant_level=
771
                                    value.variant_level+1)
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
772
        return dbus.Dictionary(all, signature="sv")
380 by Teddy Hogeborn
Use D-Bus properties instead of our own methods.
773
    
774
    @dbus.service.method(dbus.INTROSPECTABLE_IFACE,
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
775
                         out_signature="s",
776
                         path_keyword='object_path',
777
                         connection_keyword='connection')
380 by Teddy Hogeborn
Use D-Bus properties instead of our own methods.
778
    def Introspect(self, object_path, connection):
779
        """Standard D-Bus method, overloaded to insert property tags.
780
        """
781
        xmlstring = dbus.service.Object.Introspect(self, object_path,
386 by Teddy Hogeborn
* mandos (DBusObjectWithProperties.Introspect): Add the name
782
                                                   connection)
387 by Teddy Hogeborn
* mandos (ClientDBus.ReceivedSecret): Renamed to "GotSecret". All
783
        try:
784
            document = xml.dom.minidom.parseString(xmlstring)
785
            def make_tag(document, name, prop):
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
786
                e = document.createElement("property")
787
                e.setAttribute("name", name)
788
                e.setAttribute("type", prop._dbus_signature)
789
                e.setAttribute("access", prop._dbus_access)
387 by Teddy Hogeborn
* mandos (ClientDBus.ReceivedSecret): Renamed to "GotSecret". All
790
                return e
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
791
            for if_tag in document.getElementsByTagName("interface"):
387 by Teddy Hogeborn
* mandos (ClientDBus.ReceivedSecret): Renamed to "GotSecret". All
792
                for tag in (make_tag(document, name, prop)
793
                            for name, prop
794
                            in self._get_all_dbus_properties()
795
                            if prop._dbus_interface
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
796
                            == if_tag.getAttribute("name")):
387 by Teddy Hogeborn
* mandos (ClientDBus.ReceivedSecret): Renamed to "GotSecret". All
797
                    if_tag.appendChild(tag)
798
                # Add the names to the return values for the
799
                # "org.freedesktop.DBus.Properties" methods
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
800
                if (if_tag.getAttribute("name")
801
                    == "org.freedesktop.DBus.Properties"):
802
                    for cn in if_tag.getElementsByTagName("method"):
803
                        if cn.getAttribute("name") == "Get":
804
                            for arg in cn.getElementsByTagName("arg"):
805
                                if (arg.getAttribute("direction")
806
                                    == "out"):
807
                                    arg.setAttribute("name", "value")
808
                        elif cn.getAttribute("name") == "GetAll":
809
                            for arg in cn.getElementsByTagName("arg"):
810
                                if (arg.getAttribute("direction")
811
                                    == "out"):
812
                                    arg.setAttribute("name", "props")
813
            xmlstring = document.toxml("utf-8")
387 by Teddy Hogeborn
* mandos (ClientDBus.ReceivedSecret): Renamed to "GotSecret". All
814
            document.unlink()
815
        except (AttributeError, xml.dom.DOMException,
482 by Teddy Hogeborn
* mandos: Tolerate restarting Avahi servers. Also Changed to new
816
                xml.parsers.expat.ExpatError) as error:
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
817
            logger.error("Failed to override Introspection method",
387 by Teddy Hogeborn
* mandos (ClientDBus.ReceivedSecret): Renamed to "GotSecret". All
818
                         error)
380 by Teddy Hogeborn
Use D-Bus properties instead of our own methods.
819
        return xmlstring
820
821
24.1.182 by Björn Påhlsson
Refactoring code related to PropertyChanged dbus signal. Made sending
822
def datetime_to_dbus (dt, variant_level=0):
823
    """Convert a UTC datetime.datetime() to a D-Bus type."""
824
    if dt is None:
825
        return dbus.String("", variant_level = variant_level)
826
    return dbus.String(dt.isoformat(),
827
                       variant_level=variant_level)
828
505.1.3 by Teddy Hogeborn
* mandos: Break long lines.
829
class AlternateDBusNamesMetaclass(DBusObjectWithProperties
830
                                  .__metaclass__):
505.1.1 by Teddy Hogeborn
* mandos (transitional_dbus_metaclass): Renamed to
831
    """Applied to an empty subclass of a D-Bus object, this metaclass
832
    will add additional D-Bus attributes matching a certain pattern.
833
    """
24.1.185 by Björn Påhlsson
working transition code for going between se.bsnet.fukt to se.recompile
834
    def __new__(mcs, name, bases, attr):
505.1.1 by Teddy Hogeborn
* mandos (transitional_dbus_metaclass): Renamed to
835
        # Go through all the base classes which could have D-Bus
836
        # methods, signals, or properties in them
837
        for base in (b for b in bases
838
                     if issubclass(b, dbus.service.Object)):
839
            # Go though all attributes of the base class
840
            for attrname, attribute in inspect.getmembers(base):
841
                # Ignore non-D-Bus attributes, and D-Bus attributes
842
                # with the wrong interface name
843
                if (not hasattr(attribute, "_dbus_interface")
844
                    or not attribute._dbus_interface
845
                    .startswith("se.recompile.Mandos")):
846
                    continue
847
                # Create an alternate D-Bus interface name based on
848
                # the current name
849
                alt_interface = (attribute._dbus_interface
850
                                 .replace("se.recompile.Mandos",
851
                                          "se.bsnet.fukt.Mandos"))
852
                # Is this a D-Bus signal?
853
                if getattr(attribute, "_dbus_is_signal", False):
854
                    # Extract the original non-method function by
855
                    # black magic
856
                    nonmethod_func = (dict(
857
                            zip(attribute.func_code.co_freevars,
858
                                attribute.__closure__))["func"]
859
                                      .cell_contents)
860
                    # Create a new, but exactly alike, function
861
                    # object, and decorate it to be a new D-Bus signal
862
                    # with the alternate D-Bus interface name
863
                    new_function = (dbus.service.signal
864
                                    (alt_interface,
865
                                     attribute._dbus_signature)
866
                                    (types.FunctionType(
867
                                nonmethod_func.func_code,
868
                                nonmethod_func.func_globals,
869
                                nonmethod_func.func_name,
870
                                nonmethod_func.func_defaults,
871
                                nonmethod_func.func_closure)))
872
                    # Define a creator of a function to call both the
873
                    # old and new functions, so both the old and new
874
                    # signals gets sent when the function is called
875
                    def fixscope(func1, func2):
876
                        """This function is a scope container to pass
877
                        func1 and func2 to the "call_both" function
878
                        outside of its arguments"""
879
                        def call_both(*args, **kwargs):
880
                            """This function will emit two D-Bus
881
                            signals by calling func1 and func2"""
882
                            func1(*args, **kwargs)
883
                            func2(*args, **kwargs)
884
                        return call_both
885
                    # Create the "call_both" function and add it to
886
                    # the class
887
                    attr[attrname] = fixscope(attribute,
888
                                              new_function)
889
                # Is this a D-Bus method?
890
                elif getattr(attribute, "_dbus_is_method", False):
891
                    # Create a new, but exactly alike, function
892
                    # object.  Decorate it to be a new D-Bus method
893
                    # with the alternate D-Bus interface name.  Add it
894
                    # to the class.
895
                    attr[attrname] = (dbus.service.method
896
                                      (alt_interface,
897
                                       attribute._dbus_in_signature,
898
                                       attribute._dbus_out_signature)
899
                                      (types.FunctionType
900
                                       (attribute.func_code,
901
                                        attribute.func_globals,
902
                                        attribute.func_name,
903
                                        attribute.func_defaults,
904
                                        attribute.func_closure)))
905
                # Is this a D-Bus property?
906
                elif getattr(attribute, "_dbus_is_property", False):
907
                    # Create a new, but exactly alike, function
908
                    # object, and decorate it to be a new D-Bus
909
                    # property with the alternate D-Bus interface
910
                    # name.  Add it to the class.
911
                    attr[attrname] = (dbus_service_property
912
                                      (alt_interface,
913
                                       attribute._dbus_signature,
914
                                       attribute._dbus_access,
915
                                       attribute
916
                                       ._dbus_get_args_options
917
                                       ["byte_arrays"])
918
                                      (types.FunctionType
919
                                       (attribute.func_code,
920
                                        attribute.func_globals,
921
                                        attribute.func_name,
922
                                        attribute.func_defaults,
923
                                        attribute.func_closure)))
24.1.185 by Björn Påhlsson
working transition code for going between se.bsnet.fukt to se.recompile
924
        return type.__new__(mcs, name, bases, attr)
925
380 by Teddy Hogeborn
Use D-Bus properties instead of our own methods.
926
class ClientDBus(Client, DBusObjectWithProperties):
328 by Teddy Hogeborn
* mandos (Client): Move all D-Bus code to new "ClientDBus" class.
927
    """A Client class using D-Bus
331 by Teddy Hogeborn
Minor code cleanup, and a bug fix.
928
    
328 by Teddy Hogeborn
* mandos (Client): Move all D-Bus code to new "ClientDBus" class.
929
    Attributes:
338 by Teddy Hogeborn
* mandos: Minor doc string fixes.
930
    dbus_object_path: dbus.ObjectPath
931
    bus: dbus.SystemBus()
328 by Teddy Hogeborn
* mandos (Client): Move all D-Bus code to new "ClientDBus" class.
932
    """
438 by Teddy Hogeborn
* mandos (Client.runtime_expansions): New attribute containing the
933
    
934
    runtime_expansions = (Client.runtime_expansions
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
935
                          + ("dbus_object_path",))
438 by Teddy Hogeborn
* mandos (Client.runtime_expansions): New attribute containing the
936
    
328 by Teddy Hogeborn
* mandos (Client): Move all D-Bus code to new "ClientDBus" class.
937
    # dbus.service.Object doesn't use super(), so we can't either.
938
    
337 by Teddy Hogeborn
Code cleanup. Move some global stuff into main.
939
    def __init__(self, bus = None, *args, **kwargs):
518.1.1 by Björn Påhlsson
Persistent state: New feature. Client state is now stored when mandos
940
        self.bus = bus
941
        Client.__init__(self, *args, **kwargs)
942
24.2.4 by teddy at bsnet
* mandos (ClientDBus.approvals_pending): Changed to be a property
943
        self._approvals_pending = 0
328 by Teddy Hogeborn
* mandos (Client): Move all D-Bus code to new "ClientDBus" class.
944
        # Only now, when this client is initialized, can it show up on
945
        # the D-Bus
441 by Teddy Hogeborn
* mandos (ClientDBus.__init__): Bug fix: Translate "-" in client names
946
        client_object_name = unicode(self.name).translate(
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
947
            {ord("."): ord("_"),
948
             ord("-"): ord("_")})
328 by Teddy Hogeborn
* mandos (Client): Move all D-Bus code to new "ClientDBus" class.
949
        self.dbus_object_path = (dbus.ObjectPath
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
950
                                 ("/clients/" + client_object_name))
380 by Teddy Hogeborn
Use D-Bus properties instead of our own methods.
951
        DBusObjectWithProperties.__init__(self, self.bus,
952
                                          self.dbus_object_path)
422 by Teddy Hogeborn
Rename all D-Bus properties to conform to D-Bus naming conventions;
953
        
24.1.182 by Björn Påhlsson
Refactoring code related to PropertyChanged dbus signal. Made sending
954
    def notifychangeproperty(transform_func,
955
                             dbus_name, type_func=lambda x: x,
956
                             variant_level=1):
505.1.1 by Teddy Hogeborn
* mandos (transitional_dbus_metaclass): Renamed to
957
        """ Modify a variable so that it's a property which announces
958
        its changes to DBus.
959
505.1.15 by Teddy Hogeborn
Bug fix: Make D-Bus properties settable again.
960
        transform_fun: Function that takes a value and a variant_level
961
                       and transforms it to a D-Bus type.
505.1.1 by Teddy Hogeborn
* mandos (transitional_dbus_metaclass): Renamed to
962
        dbus_name: D-Bus name of the variable
24.1.182 by Björn Påhlsson
Refactoring code related to PropertyChanged dbus signal. Made sending
963
        type_func: Function that transform the value before sending it
505.1.1 by Teddy Hogeborn
* mandos (transitional_dbus_metaclass): Renamed to
964
                   to the D-Bus.  Default: no transform
965
        variant_level: D-Bus variant level.  Default: 1
24.1.182 by Björn Påhlsson
Refactoring code related to PropertyChanged dbus signal. Made sending
966
        """
505.1.6 by Teddy Hogeborn
* mandos (ClientDBus.notifychangeproperty): Bug fix: Use instance
967
        attrname = "_{0}".format(dbus_name)
24.1.182 by Björn Påhlsson
Refactoring code related to PropertyChanged dbus signal. Made sending
968
        def setter(self, value):
969
            if hasattr(self, "dbus_object_path"):
505.1.6 by Teddy Hogeborn
* mandos (ClientDBus.notifychangeproperty): Bug fix: Use instance
970
                if (not hasattr(self, attrname) or
971
                    type_func(getattr(self, attrname, None))
972
                    != type_func(value)):
973
                    dbus_value = transform_func(type_func(value),
505.1.15 by Teddy Hogeborn
Bug fix: Make D-Bus properties settable again.
974
                                                variant_level
975
                                                =variant_level)
24.1.182 by Björn Påhlsson
Refactoring code related to PropertyChanged dbus signal. Made sending
976
                    self.PropertyChanged(dbus.String(dbus_name),
977
                                         dbus_value)
505.1.6 by Teddy Hogeborn
* mandos (ClientDBus.notifychangeproperty): Bug fix: Use instance
978
            setattr(self, attrname, value)
24.1.185 by Björn Påhlsson
working transition code for going between se.bsnet.fukt to se.recompile
979
        
505.1.6 by Teddy Hogeborn
* mandos (ClientDBus.notifychangeproperty): Bug fix: Use instance
980
        return property(lambda self: getattr(self, attrname), setter)
24.1.185 by Björn Påhlsson
working transition code for going between se.bsnet.fukt to se.recompile
981
    
982
    
24.1.182 by Björn Påhlsson
Refactoring code related to PropertyChanged dbus signal. Made sending
983
    expires = notifychangeproperty(datetime_to_dbus, "Expires")
984
    approvals_pending = notifychangeproperty(dbus.Boolean,
985
                                             "ApprovalPending",
986
                                             type_func = bool)
987
    enabled = notifychangeproperty(dbus.Boolean, "Enabled")
988
    last_enabled = notifychangeproperty(datetime_to_dbus,
989
                                        "LastEnabled")
990
    checker = notifychangeproperty(dbus.Boolean, "CheckerRunning",
505.1.3 by Teddy Hogeborn
* mandos: Break long lines.
991
                                   type_func = lambda checker:
992
                                       checker is not None)
24.1.182 by Björn Påhlsson
Refactoring code related to PropertyChanged dbus signal. Made sending
993
    last_checked_ok = notifychangeproperty(datetime_to_dbus,
994
                                           "LastCheckedOK")
505.1.3 by Teddy Hogeborn
* mandos: Break long lines.
995
    last_approval_request = notifychangeproperty(
996
        datetime_to_dbus, "LastApprovalRequest")
24.1.182 by Björn Påhlsson
Refactoring code related to PropertyChanged dbus signal. Made sending
997
    approved_by_default = notifychangeproperty(dbus.Boolean,
998
                                               "ApprovedByDefault")
505.1.3 by Teddy Hogeborn
* mandos: Break long lines.
999
    approval_delay = notifychangeproperty(dbus.UInt16,
1000
                                          "ApprovalDelay",
1001
                                          type_func =
1002
                                          _timedelta_to_milliseconds)
1003
    approval_duration = notifychangeproperty(
1004
        dbus.UInt16, "ApprovalDuration",
1005
        type_func = _timedelta_to_milliseconds)
24.1.182 by Björn Påhlsson
Refactoring code related to PropertyChanged dbus signal. Made sending
1006
    host = notifychangeproperty(dbus.String, "Host")
1007
    timeout = notifychangeproperty(dbus.UInt16, "Timeout",
505.1.3 by Teddy Hogeborn
* mandos: Break long lines.
1008
                                   type_func =
1009
                                   _timedelta_to_milliseconds)
1010
    extended_timeout = notifychangeproperty(
1011
        dbus.UInt16, "ExtendedTimeout",
1012
        type_func = _timedelta_to_milliseconds)
1013
    interval = notifychangeproperty(dbus.UInt16,
1014
                                    "Interval",
1015
                                    type_func =
1016
                                    _timedelta_to_milliseconds)
24.1.182 by Björn Påhlsson
Refactoring code related to PropertyChanged dbus signal. Made sending
1017
    checker_command = notifychangeproperty(dbus.String, "Checker")
1018
    
1019
    del notifychangeproperty
328 by Teddy Hogeborn
* mandos (Client): Move all D-Bus code to new "ClientDBus" class.
1020
    
1021
    def __del__(self, *args, **kwargs):
1022
        try:
1023
            self.remove_from_connection()
329 by Teddy Hogeborn
* mandos (ClientDBus.__del__): Bug fix: Correct mispasted code, and do
1024
        except LookupError:
328 by Teddy Hogeborn
* mandos (Client): Move all D-Bus code to new "ClientDBus" class.
1025
            pass
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1026
        if hasattr(DBusObjectWithProperties, "__del__"):
380 by Teddy Hogeborn
Use D-Bus properties instead of our own methods.
1027
            DBusObjectWithProperties.__del__(self, *args, **kwargs)
328 by Teddy Hogeborn
* mandos (Client): Move all D-Bus code to new "ClientDBus" class.
1028
        Client.__del__(self, *args, **kwargs)
1029
    
1030
    def checker_callback(self, pid, condition, command,
1031
                         *args, **kwargs):
1032
        self.checker_callback_tag = None
1033
        self.checker = None
1034
        if os.WIFEXITED(condition):
1035
            exitstatus = os.WEXITSTATUS(condition)
1036
            # Emit D-Bus signal
1037
            self.CheckerCompleted(dbus.Int16(exitstatus),
1038
                                  dbus.Int64(condition),
1039
                                  dbus.String(command))
1040
        else:
1041
            # Emit D-Bus signal
1042
            self.CheckerCompleted(dbus.Int16(-1),
1043
                                  dbus.Int64(condition),
1044
                                  dbus.String(command))
1045
        
1046
        return Client.checker_callback(self, pid, condition, command,
1047
                                       *args, **kwargs)
24.1.185 by Björn Påhlsson
working transition code for going between se.bsnet.fukt to se.recompile
1048
    
328 by Teddy Hogeborn
* mandos (Client): Move all D-Bus code to new "ClientDBus" class.
1049
    def start_checker(self, *args, **kwargs):
1050
        old_checker = self.checker
1051
        if self.checker is not None:
1052
            old_checker_pid = self.checker.pid
1053
        else:
1054
            old_checker_pid = None
1055
        r = Client.start_checker(self, *args, **kwargs)
329 by Teddy Hogeborn
* mandos (ClientDBus.__del__): Bug fix: Correct mispasted code, and do
1056
        # Only if new checker process was started
1057
        if (self.checker is not None
1058
            and old_checker_pid != self.checker.pid):
1059
            # Emit D-Bus signal
328 by Teddy Hogeborn
* mandos (Client): Move all D-Bus code to new "ClientDBus" class.
1060
            self.CheckerStarted(self.current_checker_command)
1061
        return r
1062
    
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1063
    def _reset_approved(self):
1064
        self._approved = None
1065
        return False
1066
    
1067
    def approve(self, value=True):
24.1.154 by Björn Påhlsson
merge
1068
        self.send_changedstate()
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1069
        self._approved = value
24.1.182 by Björn Påhlsson
Refactoring code related to PropertyChanged dbus signal. Made sending
1070
        gobject.timeout_add(_timedelta_to_milliseconds
422 by Teddy Hogeborn
Rename all D-Bus properties to conform to D-Bus naming conventions;
1071
                            (self.approval_duration),
24.1.154 by Björn Påhlsson
merge
1072
                            self._reset_approved)
24.2.1 by teddy at bsnet
* debian/control (mandos/Depends): Added "python-urwid".
1073
    
237.1.2 by Teddy Hogeborn
Further steps towards a D-Bus server interface, plus minor syntax
1074
    
24.1.147 by Björn Påhlsson
The IPC pipes are now file objects, not file descriptors:
1075
    ## D-Bus methods, signals & properties
505.1.1 by Teddy Hogeborn
* mandos (transitional_dbus_metaclass): Renamed to
1076
    _interface = "se.recompile.Mandos.Client"
237.1.2 by Teddy Hogeborn
Further steps towards a D-Bus server interface, plus minor syntax
1077
    
24.1.147 by Björn Påhlsson
The IPC pipes are now file objects, not file descriptors:
1078
    ## Signals
381 by Teddy Hogeborn
Restore some poor D-Bus methods who got a bit hastily deleted. Enable
1079
    
237.1.2 by Teddy Hogeborn
Further steps towards a D-Bus server interface, plus minor syntax
1080
    # CheckerCompleted - signal
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1081
    @dbus.service.signal(_interface, signature="nxs")
280 by Teddy Hogeborn
* mandos (Client.CheckerCompleted): Changed signature to "nxs"; return
1082
    def CheckerCompleted(self, exitcode, waitstatus, command):
237.1.2 by Teddy Hogeborn
Further steps towards a D-Bus server interface, plus minor syntax
1083
        "D-Bus signal"
1084
        pass
1085
    
1086
    # CheckerStarted - signal
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1087
    @dbus.service.signal(_interface, signature="s")
237.1.2 by Teddy Hogeborn
Further steps towards a D-Bus server interface, plus minor syntax
1088
    def CheckerStarted(self, command):
1089
        "D-Bus signal"
1090
        pass
1091
    
238 by Teddy Hogeborn
First version of a somewhat complete D-Bus server interface. Also
1092
    # PropertyChanged - signal
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1093
    @dbus.service.signal(_interface, signature="sv")
238 by Teddy Hogeborn
First version of a somewhat complete D-Bus server interface. Also
1094
    def PropertyChanged(self, property, value):
1095
        "D-Bus signal"
1096
        pass
237.1.2 by Teddy Hogeborn
Further steps towards a D-Bus server interface, plus minor syntax
1097
    
387 by Teddy Hogeborn
* mandos (ClientDBus.ReceivedSecret): Renamed to "GotSecret". All
1098
    # GotSecret - signal
327 by Teddy Hogeborn
Merge from pipe IPC branch.
1099
    @dbus.service.signal(_interface)
387 by Teddy Hogeborn
* mandos (ClientDBus.ReceivedSecret): Renamed to "GotSecret". All
1100
    def GotSecret(self):
24.1.155 by Björn Påhlsson
mandos server: Added debuglevel that adjust at what level information
1101
        """D-Bus signal
1102
        Is sent after a successful transfer of secret from the Mandos
1103
        server to mandos-client
1104
        """
24.2.4 by teddy at bsnet
* mandos (ClientDBus.approvals_pending): Changed to be a property
1105
        pass
327 by Teddy Hogeborn
Merge from pipe IPC branch.
1106
    
1107
    # Rejected - signal
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1108
    @dbus.service.signal(_interface, signature="s")
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1109
    def Rejected(self, reason):
1110
        "D-Bus signal"
24.2.4 by teddy at bsnet
* mandos (ClientDBus.approvals_pending): Changed to be a property
1111
        pass
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1112
    
1113
    # NeedApproval - signal
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1114
    @dbus.service.signal(_interface, signature="tb")
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1115
    def NeedApproval(self, timeout, default):
327 by Teddy Hogeborn
Merge from pipe IPC branch.
1116
        "D-Bus signal"
442 by Teddy Hogeborn
* DBUS-API: Document new "LastApprovalRequest" client property.
1117
        return self.need_approval()
327 by Teddy Hogeborn
Merge from pipe IPC branch.
1118
    
24.1.147 by Björn Påhlsson
The IPC pipes are now file objects, not file descriptors:
1119
    ## Methods
442 by Teddy Hogeborn
* DBUS-API: Document new "LastApprovalRequest" client property.
1120
    
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1121
    # Approve - method
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1122
    @dbus.service.method(_interface, in_signature="b")
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1123
    def Approve(self, value):
1124
        self.approve(value)
442 by Teddy Hogeborn
* DBUS-API: Document new "LastApprovalRequest" client property.
1125
    
24.1.147 by Björn Påhlsson
The IPC pipes are now file objects, not file descriptors:
1126
    # CheckedOK - method
1127
    @dbus.service.method(_interface)
1128
    def CheckedOK(self):
482 by Teddy Hogeborn
* mandos: Tolerate restarting Avahi servers. Also Changed to new
1129
        self.checked_ok()
24.1.147 by Björn Påhlsson
The IPC pipes are now file objects, not file descriptors:
1130
    
381 by Teddy Hogeborn
Restore some poor D-Bus methods who got a bit hastily deleted. Enable
1131
    # Enable - method
1132
    @dbus.service.method(_interface)
1133
    def Enable(self):
1134
        "D-Bus method"
1135
        self.enable()
1136
    
1137
    # StartChecker - method
1138
    @dbus.service.method(_interface)
1139
    def StartChecker(self):
1140
        "D-Bus method"
1141
        self.start_checker()
1142
    
1143
    # Disable - method
1144
    @dbus.service.method(_interface)
1145
    def Disable(self):
1146
        "D-Bus method"
1147
        self.disable()
1148
    
1149
    # StopChecker - method
1150
    @dbus.service.method(_interface)
1151
    def StopChecker(self):
1152
        self.stop_checker()
1153
    
24.1.147 by Björn Påhlsson
The IPC pipes are now file objects, not file descriptors:
1154
    ## Properties
1155
    
422 by Teddy Hogeborn
Rename all D-Bus properties to conform to D-Bus naming conventions;
1156
    # ApprovalPending - property
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1157
    @dbus_service_property(_interface, signature="b", access="read")
422 by Teddy Hogeborn
Rename all D-Bus properties to conform to D-Bus naming conventions;
1158
    def ApprovalPending_dbus_property(self):
24.2.4 by teddy at bsnet
* mandos (ClientDBus.approvals_pending): Changed to be a property
1159
        return dbus.Boolean(bool(self.approvals_pending))
24.1.150 by Björn Påhlsson
* mandos: Added ClientDBus.approve_pending property. Exposed
1160
    
422 by Teddy Hogeborn
Rename all D-Bus properties to conform to D-Bus naming conventions;
1161
    # ApprovedByDefault - property
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1162
    @dbus_service_property(_interface, signature="b",
1163
                           access="readwrite")
422 by Teddy Hogeborn
Rename all D-Bus properties to conform to D-Bus naming conventions;
1164
    def ApprovedByDefault_dbus_property(self, value=None):
1165
        if value is None:       # get
1166
            return dbus.Boolean(self.approved_by_default)
1167
        self.approved_by_default = bool(value)
1168
    
1169
    # ApprovalDelay - property
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1170
    @dbus_service_property(_interface, signature="t",
1171
                           access="readwrite")
422 by Teddy Hogeborn
Rename all D-Bus properties to conform to D-Bus naming conventions;
1172
    def ApprovalDelay_dbus_property(self, value=None):
1173
        if value is None:       # get
1174
            return dbus.UInt64(self.approval_delay_milliseconds())
1175
        self.approval_delay = datetime.timedelta(0, 0, 0, value)
1176
    
1177
    # ApprovalDuration - property
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1178
    @dbus_service_property(_interface, signature="t",
1179
                           access="readwrite")
422 by Teddy Hogeborn
Rename all D-Bus properties to conform to D-Bus naming conventions;
1180
    def ApprovalDuration_dbus_property(self, value=None):
1181
        if value is None:       # get
24.1.182 by Björn Påhlsson
Refactoring code related to PropertyChanged dbus signal. Made sending
1182
            return dbus.UInt64(_timedelta_to_milliseconds(
422 by Teddy Hogeborn
Rename all D-Bus properties to conform to D-Bus naming conventions;
1183
                    self.approval_duration))
1184
        self.approval_duration = datetime.timedelta(0, 0, 0, value)
1185
    
1186
    # Name - property
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1187
    @dbus_service_property(_interface, signature="s", access="read")
422 by Teddy Hogeborn
Rename all D-Bus properties to conform to D-Bus naming conventions;
1188
    def Name_dbus_property(self):
380 by Teddy Hogeborn
Use D-Bus properties instead of our own methods.
1189
        return dbus.String(self.name)
1190
    
422 by Teddy Hogeborn
Rename all D-Bus properties to conform to D-Bus naming conventions;
1191
    # Fingerprint - property
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1192
    @dbus_service_property(_interface, signature="s", access="read")
422 by Teddy Hogeborn
Rename all D-Bus properties to conform to D-Bus naming conventions;
1193
    def Fingerprint_dbus_property(self):
380 by Teddy Hogeborn
Use D-Bus properties instead of our own methods.
1194
        return dbus.String(self.fingerprint)
1195
    
422 by Teddy Hogeborn
Rename all D-Bus properties to conform to D-Bus naming conventions;
1196
    # Host - property
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1197
    @dbus_service_property(_interface, signature="s",
1198
                           access="readwrite")
422 by Teddy Hogeborn
Rename all D-Bus properties to conform to D-Bus naming conventions;
1199
    def Host_dbus_property(self, value=None):
380 by Teddy Hogeborn
Use D-Bus properties instead of our own methods.
1200
        if value is None:       # get
1201
            return dbus.String(self.host)
1202
        self.host = value
1203
    
422 by Teddy Hogeborn
Rename all D-Bus properties to conform to D-Bus naming conventions;
1204
    # Created - property
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1205
    @dbus_service_property(_interface, signature="s", access="read")
422 by Teddy Hogeborn
Rename all D-Bus properties to conform to D-Bus naming conventions;
1206
    def Created_dbus_property(self):
24.1.182 by Björn Påhlsson
Refactoring code related to PropertyChanged dbus signal. Made sending
1207
        return dbus.String(datetime_to_dbus(self.created))
380 by Teddy Hogeborn
Use D-Bus properties instead of our own methods.
1208
    
422 by Teddy Hogeborn
Rename all D-Bus properties to conform to D-Bus naming conventions;
1209
    # LastEnabled - property
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1210
    @dbus_service_property(_interface, signature="s", access="read")
422 by Teddy Hogeborn
Rename all D-Bus properties to conform to D-Bus naming conventions;
1211
    def LastEnabled_dbus_property(self):
24.1.182 by Björn Påhlsson
Refactoring code related to PropertyChanged dbus signal. Made sending
1212
        return datetime_to_dbus(self.last_enabled)
380 by Teddy Hogeborn
Use D-Bus properties instead of our own methods.
1213
    
422 by Teddy Hogeborn
Rename all D-Bus properties to conform to D-Bus naming conventions;
1214
    # Enabled - property
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1215
    @dbus_service_property(_interface, signature="b",
1216
                           access="readwrite")
422 by Teddy Hogeborn
Rename all D-Bus properties to conform to D-Bus naming conventions;
1217
    def Enabled_dbus_property(self, value=None):
380 by Teddy Hogeborn
Use D-Bus properties instead of our own methods.
1218
        if value is None:       # get
1219
            return dbus.Boolean(self.enabled)
1220
        if value:
1221
            self.enable()
1222
        else:
1223
            self.disable()
1224
    
422 by Teddy Hogeborn
Rename all D-Bus properties to conform to D-Bus naming conventions;
1225
    # LastCheckedOK - property
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1226
    @dbus_service_property(_interface, signature="s",
1227
                           access="readwrite")
422 by Teddy Hogeborn
Rename all D-Bus properties to conform to D-Bus naming conventions;
1228
    def LastCheckedOK_dbus_property(self, value=None):
381 by Teddy Hogeborn
Restore some poor D-Bus methods who got a bit hastily deleted. Enable
1229
        if value is not None:
1230
            self.checked_ok()
1231
            return
24.1.182 by Björn Påhlsson
Refactoring code related to PropertyChanged dbus signal. Made sending
1232
        return datetime_to_dbus(self.last_checked_ok)
24.1.179 by Björn Påhlsson
New feature:
1233
    
1234
    # Expires - property
1235
    @dbus_service_property(_interface, signature="s", access="read")
1236
    def Expires_dbus_property(self):
24.1.182 by Björn Påhlsson
Refactoring code related to PropertyChanged dbus signal. Made sending
1237
        return datetime_to_dbus(self.expires)
380 by Teddy Hogeborn
Use D-Bus properties instead of our own methods.
1238
    
442 by Teddy Hogeborn
* DBUS-API: Document new "LastApprovalRequest" client property.
1239
    # LastApprovalRequest - property
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1240
    @dbus_service_property(_interface, signature="s", access="read")
442 by Teddy Hogeborn
* DBUS-API: Document new "LastApprovalRequest" client property.
1241
    def LastApprovalRequest_dbus_property(self):
24.1.182 by Björn Påhlsson
Refactoring code related to PropertyChanged dbus signal. Made sending
1242
        return datetime_to_dbus(self.last_approval_request)
442 by Teddy Hogeborn
* DBUS-API: Document new "LastApprovalRequest" client property.
1243
    
422 by Teddy Hogeborn
Rename all D-Bus properties to conform to D-Bus naming conventions;
1244
    # Timeout - property
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1245
    @dbus_service_property(_interface, signature="t",
1246
                           access="readwrite")
422 by Teddy Hogeborn
Rename all D-Bus properties to conform to D-Bus naming conventions;
1247
    def Timeout_dbus_property(self, value=None):
380 by Teddy Hogeborn
Use D-Bus properties instead of our own methods.
1248
        if value is None:       # get
1249
            return dbus.UInt64(self.timeout_milliseconds())
1250
        self.timeout = datetime.timedelta(0, 0, 0, value)
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1251
        if getattr(self, "disable_initiator_tag", None) is None:
380 by Teddy Hogeborn
Use D-Bus properties instead of our own methods.
1252
            return
1253
        # Reschedule timeout
1254
        gobject.source_remove(self.disable_initiator_tag)
1255
        self.disable_initiator_tag = None
24.1.179 by Björn Påhlsson
New feature:
1256
        self.expires = None
505.1.15 by Teddy Hogeborn
Bug fix: Make D-Bus properties settable again.
1257
        time_to_die = _timedelta_to_milliseconds((self
1258
                                                  .last_checked_ok
1259
                                                  + self.timeout)
1260
                                                 - datetime.datetime
1261
                                                 .utcnow())
380 by Teddy Hogeborn
Use D-Bus properties instead of our own methods.
1262
        if time_to_die <= 0:
1263
            # The timeout has passed
1264
            self.disable()
1265
        else:
24.1.179 by Björn Påhlsson
New feature:
1266
            self.expires = (datetime.datetime.utcnow()
505.1.3 by Teddy Hogeborn
* mandos: Break long lines.
1267
                            + datetime.timedelta(milliseconds =
1268
                                                 time_to_die))
380 by Teddy Hogeborn
Use D-Bus properties instead of our own methods.
1269
            self.disable_initiator_tag = (gobject.timeout_add
1270
                                          (time_to_die, self.disable))
24.1.185 by Björn Påhlsson
working transition code for going between se.bsnet.fukt to se.recompile
1271
    
24.1.179 by Björn Påhlsson
New feature:
1272
    # ExtendedTimeout - property
1273
    @dbus_service_property(_interface, signature="t",
1274
                           access="readwrite")
1275
    def ExtendedTimeout_dbus_property(self, value=None):
1276
        if value is None:       # get
1277
            return dbus.UInt64(self.extended_timeout_milliseconds())
1278
        self.extended_timeout = datetime.timedelta(0, 0, 0, value)
24.1.185 by Björn Påhlsson
working transition code for going between se.bsnet.fukt to se.recompile
1279
    
422 by Teddy Hogeborn
Rename all D-Bus properties to conform to D-Bus naming conventions;
1280
    # Interval - property
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1281
    @dbus_service_property(_interface, signature="t",
1282
                           access="readwrite")
422 by Teddy Hogeborn
Rename all D-Bus properties to conform to D-Bus naming conventions;
1283
    def Interval_dbus_property(self, value=None):
380 by Teddy Hogeborn
Use D-Bus properties instead of our own methods.
1284
        if value is None:       # get
1285
            return dbus.UInt64(self.interval_milliseconds())
1286
        self.interval = datetime.timedelta(0, 0, 0, value)
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1287
        if getattr(self, "checker_initiator_tag", None) is None:
380 by Teddy Hogeborn
Use D-Bus properties instead of our own methods.
1288
            return
1289
        # Reschedule checker run
1290
        gobject.source_remove(self.checker_initiator_tag)
1291
        self.checker_initiator_tag = (gobject.timeout_add
1292
                                      (value, self.start_checker))
1293
        self.start_checker()    # Start one now, too
24.1.185 by Björn Påhlsson
working transition code for going between se.bsnet.fukt to se.recompile
1294
    
422 by Teddy Hogeborn
Rename all D-Bus properties to conform to D-Bus naming conventions;
1295
    # Checker - property
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1296
    @dbus_service_property(_interface, signature="s",
1297
                           access="readwrite")
422 by Teddy Hogeborn
Rename all D-Bus properties to conform to D-Bus naming conventions;
1298
    def Checker_dbus_property(self, value=None):
380 by Teddy Hogeborn
Use D-Bus properties instead of our own methods.
1299
        if value is None:       # get
1300
            return dbus.String(self.checker_command)
1301
        self.checker_command = value
237.1.2 by Teddy Hogeborn
Further steps towards a D-Bus server interface, plus minor syntax
1302
    
422 by Teddy Hogeborn
Rename all D-Bus properties to conform to D-Bus naming conventions;
1303
    # CheckerRunning - property
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1304
    @dbus_service_property(_interface, signature="b",
1305
                           access="readwrite")
422 by Teddy Hogeborn
Rename all D-Bus properties to conform to D-Bus naming conventions;
1306
    def CheckerRunning_dbus_property(self, value=None):
380 by Teddy Hogeborn
Use D-Bus properties instead of our own methods.
1307
        if value is None:       # get
1308
            return dbus.Boolean(self.checker is not None)
1309
        if value:
1310
            self.start_checker()
1311
        else:
1312
            self.stop_checker()
1313
    
422 by Teddy Hogeborn
Rename all D-Bus properties to conform to D-Bus naming conventions;
1314
    # ObjectPath - property
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1315
    @dbus_service_property(_interface, signature="o", access="read")
422 by Teddy Hogeborn
Rename all D-Bus properties to conform to D-Bus naming conventions;
1316
    def ObjectPath_dbus_property(self):
380 by Teddy Hogeborn
Use D-Bus properties instead of our own methods.
1317
        return self.dbus_object_path # is already a dbus.ObjectPath
1318
    
422 by Teddy Hogeborn
Rename all D-Bus properties to conform to D-Bus naming conventions;
1319
    # Secret = property
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1320
    @dbus_service_property(_interface, signature="ay",
1321
                           access="write", byte_arrays=True)
422 by Teddy Hogeborn
Rename all D-Bus properties to conform to D-Bus naming conventions;
1322
    def Secret_dbus_property(self, value):
380 by Teddy Hogeborn
Use D-Bus properties instead of our own methods.
1323
        self.secret = str(value)
237.1.2 by Teddy Hogeborn
Further steps towards a D-Bus server interface, plus minor syntax
1324
    
1325
    del _interface
3 by Björn Påhlsson
Python based server
1326
1327
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1328
class ProxyClient(object):
1329
    def __init__(self, child_pipe, fpr, address):
1330
        self._pipe = child_pipe
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1331
        self._pipe.send(('init', fpr, address))
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1332
        if not self._pipe.recv():
1333
            raise KeyError()
24.1.185 by Björn Påhlsson
working transition code for going between se.bsnet.fukt to se.recompile
1334
    
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1335
    def __getattribute__(self, name):
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1336
        if(name == '_pipe'):
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1337
            return super(ProxyClient, self).__getattribute__(name)
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1338
        self._pipe.send(('getattr', name))
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1339
        data = self._pipe.recv()
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1340
        if data[0] == 'data':
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1341
            return data[1]
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1342
        if data[0] == 'function':
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1343
            def func(*args, **kwargs):
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1344
                self._pipe.send(('funcall', name, args, kwargs))
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1345
                return self._pipe.recv()[1]
1346
            return func
24.1.185 by Björn Påhlsson
working transition code for going between se.bsnet.fukt to se.recompile
1347
    
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1348
    def __setattr__(self, name, value):
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1349
        if(name == '_pipe'):
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1350
            return super(ProxyClient, self).__setattr__(name, value)
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1351
        self._pipe.send(('setattr', name, value))
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1352
24.1.186 by Björn Påhlsson
transitional stuff actually working
1353
class ClientDBusTransitional(ClientDBus):
505.1.1 by Teddy Hogeborn
* mandos (transitional_dbus_metaclass): Renamed to
1354
    __metaclass__ = AlternateDBusNamesMetaclass
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1355
335 by Teddy Hogeborn
* mandos: Import "SocketServer" as "socketserver" and "ConfigParser"
1356
class ClientHandler(socketserver.BaseRequestHandler, object):
331 by Teddy Hogeborn
Minor code cleanup, and a bug fix.
1357
    """A class to handle client connections.
1358
    
1359
    Instantiated once for each connection to handle it.
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
1360
    Note: This will run in its own forked process."""
12 by Teddy Hogeborn
* mandos-clients.conf ([foo]/dn, [foo]/password, [braxen_client]/dn,
1361
    
3 by Björn Påhlsson
Python based server
1362
    def handle(self):
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1363
        with contextlib.closing(self.server.child_pipe) as child_pipe:
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1364
            logger.info("TCP connection from: %s",
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1365
                        unicode(self.client_address))
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1366
            logger.debug("Pipe FD: %d",
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1367
                         self.server.child_pipe.fileno())
24.1.185 by Björn Påhlsson
working transition code for going between se.bsnet.fukt to se.recompile
1368
            
288.1.1 by Teddy Hogeborn
Start of new pipe-based IPC mechanism.
1369
            session = (gnutls.connection
1370
                       .ClientSession(self.request,
1371
                                      gnutls.connection
1372
                                      .X509Credentials()))
24.1.185 by Björn Påhlsson
working transition code for going between se.bsnet.fukt to se.recompile
1373
            
288.1.1 by Teddy Hogeborn
Start of new pipe-based IPC mechanism.
1374
            # Note: gnutls.connection.X509Credentials is really a
1375
            # generic GnuTLS certificate credentials object so long as
1376
            # no X.509 keys are added to it.  Therefore, we can use it
1377
            # here despite using OpenPGP certificates.
24.1.185 by Björn Påhlsson
working transition code for going between se.bsnet.fukt to se.recompile
1378
            
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1379
            #priority = ':'.join(("NONE", "+VERS-TLS1.1",
1380
            #                      "+AES-256-CBC", "+SHA1",
1381
            #                      "+COMP-NULL", "+CTYPE-OPENPGP",
1382
            #                      "+DHE-DSS"))
288.1.1 by Teddy Hogeborn
Start of new pipe-based IPC mechanism.
1383
            # Use a fallback default, since this MUST be set.
331 by Teddy Hogeborn
Minor code cleanup, and a bug fix.
1384
            priority = self.server.gnutls_priority
1385
            if priority is None:
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1386
                priority = "NORMAL"
288.1.1 by Teddy Hogeborn
Start of new pipe-based IPC mechanism.
1387
            (gnutls.library.functions
1388
             .gnutls_priority_set_direct(session._c_object,
1389
                                         priority, None))
24.1.185 by Björn Påhlsson
working transition code for going between se.bsnet.fukt to se.recompile
1390
            
416.1.2 by Teddy Hogeborn
* mandos (ClientHandler.handle): Set up the GnuTLS session object
1391
            # Start communication using the Mandos protocol
1392
            # Get protocol number
1393
            line = self.request.makefile().readline()
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1394
            logger.debug("Protocol version: %r", line)
416.1.2 by Teddy Hogeborn
* mandos (ClientHandler.handle): Set up the GnuTLS session object
1395
            try:
1396
                if int(line.strip().split()[0]) > 1:
1397
                    raise RuntimeError
482 by Teddy Hogeborn
* mandos: Tolerate restarting Avahi servers. Also Changed to new
1398
            except (ValueError, IndexError, RuntimeError) as error:
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1399
                logger.error("Unknown protocol version: %s", error)
416.1.2 by Teddy Hogeborn
* mandos (ClientHandler.handle): Set up the GnuTLS session object
1400
                return
24.1.185 by Björn Påhlsson
working transition code for going between se.bsnet.fukt to se.recompile
1401
            
416.1.2 by Teddy Hogeborn
* mandos (ClientHandler.handle): Set up the GnuTLS session object
1402
            # Start GnuTLS connection
288.1.1 by Teddy Hogeborn
Start of new pipe-based IPC mechanism.
1403
            try:
1404
                session.handshake()
482 by Teddy Hogeborn
* mandos: Tolerate restarting Avahi servers. Also Changed to new
1405
            except gnutls.errors.GNUTLSError as error:
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1406
                logger.warning("Handshake failed: %s", error)
288.1.1 by Teddy Hogeborn
Start of new pipe-based IPC mechanism.
1407
                # Do not run session.bye() here: the session is not
1408
                # established.  Just abandon the request.
1409
                return
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1410
            logger.debug("Handshake succeeded")
24.1.185 by Björn Påhlsson
working transition code for going between se.bsnet.fukt to se.recompile
1411
            
24.1.150 by Björn Påhlsson
* mandos: Added ClientDBus.approve_pending property. Exposed
1412
            approval_required = False
288.1.1 by Teddy Hogeborn
Start of new pipe-based IPC mechanism.
1413
            try:
411 by Teddy Hogeborn
More consistent terminology: Clients are no longer "invalid" - they
1414
                try:
1415
                    fpr = self.fingerprint(self.peer_certificate
1416
                                           (session))
482 by Teddy Hogeborn
* mandos: Tolerate restarting Avahi servers. Also Changed to new
1417
                except (TypeError,
1418
                        gnutls.errors.GNUTLSError) as error:
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1419
                    logger.warning("Bad certificate: %s", error)
411 by Teddy Hogeborn
More consistent terminology: Clients are no longer "invalid" - they
1420
                    return
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1421
                logger.debug("Fingerprint: %s", fpr)
24.1.185 by Björn Påhlsson
working transition code for going between se.bsnet.fukt to se.recompile
1422
                
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1423
                try:
1424
                    client = ProxyClient(child_pipe, fpr,
1425
                                         self.client_address)
1426
                except KeyError:
411 by Teddy Hogeborn
More consistent terminology: Clients are no longer "invalid" - they
1427
                    return
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1428
                
422 by Teddy Hogeborn
Rename all D-Bus properties to conform to D-Bus naming conventions;
1429
                if client.approval_delay:
1430
                    delay = client.approval_delay
24.1.150 by Björn Påhlsson
* mandos: Added ClientDBus.approve_pending property. Exposed
1431
                    client.approvals_pending += 1
1432
                    approval_required = True
1433
                
24.1.148 by Björn Påhlsson
half working on-demand password and approved code
1434
                while True:
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1435
                    if not client.enabled:
24.1.174 by Björn Påhlsson
* Makefile (CFLAGS): Added "-lrt" to include real time library.
1436
                        logger.info("Client %s is disabled",
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1437
                                       client.name)
1438
                        if self.server.use_dbus:
1439
                            # Emit D-Bus signal
505.1.3 by Teddy Hogeborn
* mandos: Break long lines.
1440
                            client.Rejected("Disabled")
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1441
                        return
24.1.150 by Björn Påhlsson
* mandos: Added ClientDBus.approve_pending property. Exposed
1442
                    
422 by Teddy Hogeborn
Rename all D-Bus properties to conform to D-Bus naming conventions;
1443
                    if client._approved or not client.approval_delay:
24.1.150 by Björn Påhlsson
* mandos: Added ClientDBus.approve_pending property. Exposed
1444
                        #We are approved or approval is disabled
1445
                        break
1446
                    elif client._approved is None:
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1447
                        logger.info("Client %s needs approval",
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1448
                                    client.name)
1449
                        if self.server.use_dbus:
1450
                            # Emit D-Bus signal
1451
                            client.NeedApproval(
422 by Teddy Hogeborn
Rename all D-Bus properties to conform to D-Bus naming conventions;
1452
                                client.approval_delay_milliseconds(),
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1453
                                client.approved_by_default)
1454
                    else:
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1455
                        logger.warning("Client %s was not approved",
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1456
                                       client.name)
1457
                        if self.server.use_dbus:
24.1.150 by Björn Påhlsson
* mandos: Added ClientDBus.approve_pending property. Exposed
1458
                            # Emit D-Bus signal
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1459
                            client.Rejected("Denied")
24.1.148 by Björn Påhlsson
half working on-demand password and approved code
1460
                        return
1461
                    
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1462
                    #wait until timeout or approved
1463
                    time = datetime.datetime.now()
1464
                    client.changedstate.acquire()
505.1.3 by Teddy Hogeborn
* mandos: Break long lines.
1465
                    (client.changedstate.wait
1466
                     (float(client._timedelta_to_milliseconds(delay)
1467
                            / 1000)))
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1468
                    client.changedstate.release()
1469
                    time2 = datetime.datetime.now()
1470
                    if (time2 - time) >= delay:
1471
                        if not client.approved_by_default:
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1472
                            logger.warning("Client %s timed out while"
1473
                                           " waiting for approval",
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1474
                                           client.name)
1475
                            if self.server.use_dbus:
1476
                                # Emit D-Bus signal
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1477
                                client.Rejected("Approval timed out")
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1478
                            return
1479
                        else:
1480
                            break
1481
                    else:
1482
                        delay -= time2 - time
1483
                
411 by Teddy Hogeborn
More consistent terminology: Clients are no longer "invalid" - they
1484
                sent_size = 0
1485
                while sent_size < len(client.secret):
24.1.155 by Björn Påhlsson
mandos server: Added debuglevel that adjust at what level information
1486
                    try:
1487
                        sent = session.send(client.secret[sent_size:])
482 by Teddy Hogeborn
* mandos: Tolerate restarting Avahi servers. Also Changed to new
1488
                    except gnutls.errors.GNUTLSError as error:
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1489
                        logger.warning("gnutls send failed")
24.1.155 by Björn Påhlsson
mandos server: Added debuglevel that adjust at what level information
1490
                        return
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1491
                    logger.debug("Sent: %d, remaining: %d",
411 by Teddy Hogeborn
More consistent terminology: Clients are no longer "invalid" - they
1492
                                 sent, len(client.secret)
1493
                                 - (sent_size + sent))
1494
                    sent_size += sent
24.1.185 by Björn Påhlsson
working transition code for going between se.bsnet.fukt to se.recompile
1495
                
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1496
                logger.info("Sending secret to %s", client.name)
505.1.13 by Teddy Hogeborn
Miscellaneous fixes prompted by lintian:
1497
                # bump the timeout using extended_timeout
24.1.179 by Björn Påhlsson
New feature:
1498
                client.checked_ok(client.extended_timeout)
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1499
                if self.server.use_dbus:
1500
                    # Emit D-Bus signal
1501
                    client.GotSecret()
24.1.150 by Björn Påhlsson
* mandos: Added ClientDBus.approve_pending property. Exposed
1502
            
411 by Teddy Hogeborn
More consistent terminology: Clients are no longer "invalid" - they
1503
            finally:
24.1.150 by Björn Påhlsson
* mandos: Added ClientDBus.approve_pending property. Exposed
1504
                if approval_required:
1505
                    client.approvals_pending -= 1
24.1.155 by Björn Påhlsson
mandos server: Added debuglevel that adjust at what level information
1506
                try:
1507
                    session.bye()
482 by Teddy Hogeborn
* mandos: Tolerate restarting Avahi servers. Also Changed to new
1508
                except gnutls.errors.GNUTLSError as error:
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1509
                    logger.warning("GnuTLS bye failed")
330 by Teddy Hogeborn
* mandos (peer_certificate, fingerprint): Moved into "TCP_handler"
1510
    
1511
    @staticmethod
1512
    def peer_certificate(session):
1513
        "Return the peer's OpenPGP certificate as a bytestring"
1514
        # If not an OpenPGP certificate...
1515
        if (gnutls.library.functions
1516
            .gnutls_certificate_type_get(session._c_object)
1517
            != gnutls.library.constants.GNUTLS_CRT_OPENPGP):
1518
            # ...do the normal thing
1519
            return session.peer_certificate
1520
        list_size = ctypes.c_uint(1)
1521
        cert_list = (gnutls.library.functions
1522
                     .gnutls_certificate_get_peers
1523
                     (session._c_object, ctypes.byref(list_size)))
1524
        if not bool(cert_list) and list_size.value != 0:
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1525
            raise gnutls.errors.GNUTLSError("error getting peer"
1526
                                            " certificate")
330 by Teddy Hogeborn
* mandos (peer_certificate, fingerprint): Moved into "TCP_handler"
1527
        if list_size.value == 0:
1528
            return None
1529
        cert = cert_list[0]
1530
        return ctypes.string_at(cert.data, cert.size)
1531
    
1532
    @staticmethod
1533
    def fingerprint(openpgp):
1534
        "Convert an OpenPGP bytestring to a hexdigit fingerprint"
1535
        # New GnuTLS "datum" with the OpenPGP public key
1536
        datum = (gnutls.library.types
1537
                 .gnutls_datum_t(ctypes.cast(ctypes.c_char_p(openpgp),
1538
                                             ctypes.POINTER
1539
                                             (ctypes.c_ubyte)),
1540
                                 ctypes.c_uint(len(openpgp))))
1541
        # New empty GnuTLS certificate
1542
        crt = gnutls.library.types.gnutls_openpgp_crt_t()
1543
        (gnutls.library.functions
1544
         .gnutls_openpgp_crt_init(ctypes.byref(crt)))
1545
        # Import the OpenPGP public key into the certificate
1546
        (gnutls.library.functions
1547
         .gnutls_openpgp_crt_import(crt, ctypes.byref(datum),
1548
                                    gnutls.library.constants
1549
                                    .GNUTLS_OPENPGP_FMT_RAW))
1550
        # Verify the self signature in the key
1551
        crtverify = ctypes.c_uint()
1552
        (gnutls.library.functions
1553
         .gnutls_openpgp_crt_verify_self(crt, 0,
1554
                                         ctypes.byref(crtverify)))
1555
        if crtverify.value != 0:
1556
            gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
1557
            raise (gnutls.errors.CertificateSecurityError
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1558
                   ("Verify failed"))
330 by Teddy Hogeborn
* mandos (peer_certificate, fingerprint): Moved into "TCP_handler"
1559
        # New buffer for the fingerprint
1560
        buf = ctypes.create_string_buffer(20)
1561
        buf_len = ctypes.c_size_t()
1562
        # Get the fingerprint from the certificate into the buffer
1563
        (gnutls.library.functions
1564
         .gnutls_openpgp_crt_get_fingerprint(crt, ctypes.byref(buf),
1565
                                             ctypes.byref(buf_len)))
1566
        # Deinit the certificate
1567
        gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
1568
        # Convert the buffer to a Python bytestring
1569
        fpr = ctypes.string_at(buf, buf_len.value)
1570
        # Convert the bytestring to hexadecimal notation
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1571
        hex_fpr = ''.join("%02X" % ord(char) for char in fpr)
330 by Teddy Hogeborn
* mandos (peer_certificate, fingerprint): Moved into "TCP_handler"
1572
        return hex_fpr
288.1.1 by Teddy Hogeborn
Start of new pipe-based IPC mechanism.
1573
1574
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1575
class MultiprocessingMixIn(object):
1576
    """Like socketserver.ThreadingMixIn, but with multiprocessing"""
1577
    def sub_process_main(self, request, address):
1578
        try:
1579
            self.finish_request(request, address)
1580
        except:
1581
            self.handle_error(request, address)
1582
        self.close_request(request)
505.1.11 by Teddy Hogeborn
* mandos (Client.checked_ok): Set "expires" after setting timeout.
1583
    
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1584
    def process_request(self, request, address):
1585
        """Start a new process to process the request."""
505.1.11 by Teddy Hogeborn
* mandos (Client.checked_ok): Set "expires" after setting timeout.
1586
        proc = multiprocessing.Process(target = self.sub_process_main,
1587
                                       args = (request,
1588
                                               address))
1589
        proc.start()
1590
        return proc
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1591
24.1.185 by Björn Påhlsson
working transition code for going between se.bsnet.fukt to se.recompile
1592
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1593
class MultiprocessingMixInWithPipe(MultiprocessingMixIn, object):
1594
    """ adds a pipe to the MixIn """
288.1.1 by Teddy Hogeborn
Start of new pipe-based IPC mechanism.
1595
    def process_request(self, request, client_address):
331 by Teddy Hogeborn
Minor code cleanup, and a bug fix.
1596
        """Overrides and wraps the original process_request().
1597
        
355 by Teddy Hogeborn
* mandos: White-space fixes only.
1598
        This function creates a new pipe in self.pipe
288.1.1 by Teddy Hogeborn
Start of new pipe-based IPC mechanism.
1599
        """
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1600
        parent_pipe, self.child_pipe = multiprocessing.Pipe()
24.1.185 by Björn Påhlsson
working transition code for going between se.bsnet.fukt to se.recompile
1601
        
505.1.11 by Teddy Hogeborn
* mandos (Client.checked_ok): Set "expires" after setting timeout.
1602
        proc = MultiprocessingMixIn.process_request(self, request,
1603
                                                    client_address)
24.1.152 by Björn Påhlsson
bug fixes that prevent problems when runing server as root
1604
        self.child_pipe.close()
505.1.11 by Teddy Hogeborn
* mandos (Client.checked_ok): Set "expires" after setting timeout.
1605
        self.add_pipe(parent_pipe, proc)
24.1.185 by Björn Påhlsson
working transition code for going between se.bsnet.fukt to se.recompile
1606
    
505.1.11 by Teddy Hogeborn
* mandos (Client.checked_ok): Set "expires" after setting timeout.
1607
    def add_pipe(self, parent_pipe, proc):
288.1.1 by Teddy Hogeborn
Start of new pipe-based IPC mechanism.
1608
        """Dummy function; override as necessary"""
464 by Teddy Hogeborn
* debian/mandos-client.postrm (purge): Bug fix: update initramfs also
1609
        raise NotImplementedError
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1610
24.1.185 by Björn Påhlsson
working transition code for going between se.bsnet.fukt to se.recompile
1611
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1612
class IPv6_TCPServer(MultiprocessingMixInWithPipe,
335 by Teddy Hogeborn
* mandos: Import "SocketServer" as "socketserver" and "ConfigParser"
1613
                     socketserver.TCPServer, object):
237.2.13 by Teddy Hogeborn
Merge from trunk. Notable changes:
1614
    """IPv6-capable TCP server.  Accepts 'None' as address and/or port
331 by Teddy Hogeborn
Minor code cleanup, and a bug fix.
1615
    
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
1616
    Attributes:
331 by Teddy Hogeborn
Minor code cleanup, and a bug fix.
1617
        enabled:        Boolean; whether this server is activated yet
1618
        interface:      None or a network interface name (string)
1619
        use_ipv6:       Boolean; to use IPv6 or not
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
1620
    """
331 by Teddy Hogeborn
Minor code cleanup, and a bug fix.
1621
    def __init__(self, server_address, RequestHandlerClass,
339 by Teddy Hogeborn
Code cleanup.
1622
                 interface=None, use_ipv6=True):
331 by Teddy Hogeborn
Minor code cleanup, and a bug fix.
1623
        self.interface = interface
1624
        if use_ipv6:
1625
            self.address_family = socket.AF_INET6
335 by Teddy Hogeborn
* mandos: Import "SocketServer" as "socketserver" and "ConfigParser"
1626
        socketserver.TCPServer.__init__(self, server_address,
331 by Teddy Hogeborn
Minor code cleanup, and a bug fix.
1627
                                        RequestHandlerClass)
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
1628
    def server_bind(self):
1629
        """This overrides the normal server_bind() function
1630
        to bind to an interface if one was specified, and also NOT to
1631
        bind to an address or port if they were not specified."""
331 by Teddy Hogeborn
Minor code cleanup, and a bug fix.
1632
        if self.interface is not None:
338 by Teddy Hogeborn
* mandos: Minor doc string fixes.
1633
            if SO_BINDTODEVICE is None:
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1634
                logger.error("SO_BINDTODEVICE does not exist;"
1635
                             " cannot bind to interface %s",
338 by Teddy Hogeborn
* mandos: Minor doc string fixes.
1636
                             self.interface)
1637
            else:
1638
                try:
1639
                    self.socket.setsockopt(socket.SOL_SOCKET,
1640
                                           SO_BINDTODEVICE,
1641
                                           str(self.interface
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1642
                                               + '\0'))
482 by Teddy Hogeborn
* mandos: Tolerate restarting Avahi servers. Also Changed to new
1643
                except socket.error as error:
338 by Teddy Hogeborn
* mandos: Minor doc string fixes.
1644
                    if error[0] == errno.EPERM:
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1645
                        logger.error("No permission to"
1646
                                     " bind to interface %s",
338 by Teddy Hogeborn
* mandos: Minor doc string fixes.
1647
                                     self.interface)
1648
                    elif error[0] == errno.ENOPROTOOPT:
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1649
                        logger.error("SO_BINDTODEVICE not available;"
1650
                                     " cannot bind to interface %s",
338 by Teddy Hogeborn
* mandos: Minor doc string fixes.
1651
                                     self.interface)
1652
                    else:
1653
                        raise
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
1654
        # Only bind(2) the socket if we really need to.
1655
        if self.server_address[0] or self.server_address[1]:
1656
            if not self.server_address[0]:
314 by Teddy Hogeborn
Support not using IPv6 in server:
1657
                if self.address_family == socket.AF_INET6:
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1658
                    any_address = "::" # in6addr_any
314 by Teddy Hogeborn
Support not using IPv6 in server:
1659
                else:
1660
                    any_address = socket.INADDR_ANY
1661
                self.server_address = (any_address,
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
1662
                                       self.server_address[1])
49 by Teddy Hogeborn
* mandos (IPv6_TCPServer.server_bind): Bug fix: allow port to be empty
1663
            elif not self.server_address[1]:
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
1664
                self.server_address = (self.server_address[0],
1665
                                       0)
331 by Teddy Hogeborn
Minor code cleanup, and a bug fix.
1666
#                 if self.interface:
49 by Teddy Hogeborn
* mandos (IPv6_TCPServer.server_bind): Bug fix: allow port to be empty
1667
#                     self.server_address = (self.server_address[0],
1668
#                                            0, # port
1669
#                                            0, # flowinfo
1670
#                                            if_nametoindex
331 by Teddy Hogeborn
Minor code cleanup, and a bug fix.
1671
#                                            (self.interface))
335 by Teddy Hogeborn
* mandos: Import "SocketServer" as "socketserver" and "ConfigParser"
1672
            return socketserver.TCPServer.server_bind(self)
339 by Teddy Hogeborn
Code cleanup.
1673
1674
1675
class MandosServer(IPv6_TCPServer):
1676
    """Mandos server.
1677
    
1678
    Attributes:
1679
        clients:        set of Client objects
1680
        gnutls_priority GnuTLS priority string
1681
        use_dbus:       Boolean; to emit D-Bus signals or not
340 by Teddy Hogeborn
Code cleanup.
1682
    
1683
    Assumes a gobject.MainLoop event loop.
339 by Teddy Hogeborn
Code cleanup.
1684
    """
1685
    def __init__(self, server_address, RequestHandlerClass,
1686
                 interface=None, use_ipv6=True, clients=None,
1687
                 gnutls_priority=None, use_dbus=True):
1688
        self.enabled = False
1689
        self.clients = clients
341 by Teddy Hogeborn
Code cleanup and one bug fix.
1690
        if self.clients is None:
518.1.1 by Björn Påhlsson
Persistent state: New feature. Client state is now stored when mandos
1691
            self.clients = {}
339 by Teddy Hogeborn
Code cleanup.
1692
        self.use_dbus = use_dbus
1693
        self.gnutls_priority = gnutls_priority
1694
        IPv6_TCPServer.__init__(self, server_address,
1695
                                RequestHandlerClass,
1696
                                interface = interface,
1697
                                use_ipv6 = use_ipv6)
163 by Teddy Hogeborn
* Makefile (PIDDIR, USER, GROUP): Removed.
1698
    def server_activate(self):
1699
        if self.enabled:
335 by Teddy Hogeborn
* mandos: Import "SocketServer" as "socketserver" and "ConfigParser"
1700
            return socketserver.TCPServer.server_activate(self)
505.1.11 by Teddy Hogeborn
* mandos (Client.checked_ok): Set "expires" after setting timeout.
1701
    
163 by Teddy Hogeborn
* Makefile (PIDDIR, USER, GROUP): Removed.
1702
    def enable(self):
1703
        self.enabled = True
505.1.11 by Teddy Hogeborn
* mandos (Client.checked_ok): Set "expires" after setting timeout.
1704
    
1705
    def add_pipe(self, parent_pipe, proc):
340 by Teddy Hogeborn
Code cleanup.
1706
        # Call "handle_ipc" for both data and EOF events
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1707
        gobject.io_add_watch(parent_pipe.fileno(),
411 by Teddy Hogeborn
More consistent terminology: Clients are no longer "invalid" - they
1708
                             gobject.IO_IN | gobject.IO_HUP,
1709
                             functools.partial(self.handle_ipc,
505.1.3 by Teddy Hogeborn
* mandos: Break long lines.
1710
                                               parent_pipe =
505.1.11 by Teddy Hogeborn
* mandos (Client.checked_ok): Set "expires" after setting timeout.
1711
                                               parent_pipe,
1712
                                               proc = proc))
505.1.9 by Teddy Hogeborn
Whitespace
1713
    
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1714
    def handle_ipc(self, source, condition, parent_pipe=None,
505.1.11 by Teddy Hogeborn
* mandos (Client.checked_ok): Set "expires" after setting timeout.
1715
                   proc = None, client_object=None):
327 by Teddy Hogeborn
Merge from pipe IPC branch.
1716
        condition_names = {
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1717
            gobject.IO_IN: "IN",   # There is data to read.
1718
            gobject.IO_OUT: "OUT", # Data can be written (without
333 by Teddy Hogeborn
Minor code cleanup; one minor bug fix.
1719
                                    # blocking).
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1720
            gobject.IO_PRI: "PRI", # There is urgent data to read.
1721
            gobject.IO_ERR: "ERR", # Error condition.
1722
            gobject.IO_HUP: "HUP"  # Hung up (the connection has been
333 by Teddy Hogeborn
Minor code cleanup; one minor bug fix.
1723
                                    # broken, usually for pipes and
1724
                                    # sockets).
327 by Teddy Hogeborn
Merge from pipe IPC branch.
1725
            }
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1726
        conditions_string = ' | '.join(name
327 by Teddy Hogeborn
Merge from pipe IPC branch.
1727
                                       for cond, name in
1728
                                       condition_names.iteritems()
1729
                                       if cond & condition)
505.1.13 by Teddy Hogeborn
Miscellaneous fixes prompted by lintian:
1730
        # error, or the other end of multiprocessing.Pipe has closed
24.1.155 by Björn Påhlsson
mandos server: Added debuglevel that adjust at what level information
1731
        if condition & (gobject.IO_ERR | condition & gobject.IO_HUP):
505.1.13 by Teddy Hogeborn
Miscellaneous fixes prompted by lintian:
1732
            # Wait for other process to exit
505.1.11 by Teddy Hogeborn
* mandos (Client.checked_ok): Set "expires" after setting timeout.
1733
            proc.join()
24.1.152 by Björn Påhlsson
bug fixes that prevent problems when runing server as root
1734
            return False
288.1.1 by Teddy Hogeborn
Start of new pipe-based IPC mechanism.
1735
        
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1736
        # Read a request from the child
1737
        request = parent_pipe.recv()
1738
        command = request[0]
1739
        
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1740
        if command == 'init':
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1741
            fpr = request[1]
1742
            address = request[2]
1743
            
518.1.1 by Björn Påhlsson
Persistent state: New feature. Client state is now stored when mandos
1744
            for c in self.clients.itervalues():
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1745
                if c.fingerprint == fpr:
1746
                    client = c
1747
                    break
1748
            else:
24.1.174 by Björn Påhlsson
* Makefile (CFLAGS): Added "-lrt" to include real time library.
1749
                logger.info("Client not found for fingerprint: %s, ad"
1750
                            "dress: %s", fpr, address)
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1751
                if self.use_dbus:
1752
                    # Emit D-Bus signal
505.1.3 by Teddy Hogeborn
* mandos: Break long lines.
1753
                    mandos_dbus_service.ClientNotFound(fpr,
1754
                                                       address[0])
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1755
                parent_pipe.send(False)
1756
                return False
1757
            
1758
            gobject.io_add_watch(parent_pipe.fileno(),
1759
                                 gobject.IO_IN | gobject.IO_HUP,
1760
                                 functools.partial(self.handle_ipc,
505.1.3 by Teddy Hogeborn
* mandos: Break long lines.
1761
                                                   parent_pipe =
1762
                                                   parent_pipe,
505.1.11 by Teddy Hogeborn
* mandos (Client.checked_ok): Set "expires" after setting timeout.
1763
                                                   proc = proc,
505.1.3 by Teddy Hogeborn
* mandos: Break long lines.
1764
                                                   client_object =
1765
                                                   client))
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1766
            parent_pipe.send(True)
505.1.3 by Teddy Hogeborn
* mandos: Break long lines.
1767
            # remove the old hook in favor of the new above hook on
1768
            # same fileno
288.1.1 by Teddy Hogeborn
Start of new pipe-based IPC mechanism.
1769
            return False
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1770
        if command == 'funcall':
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1771
            funcname = request[1]
1772
            args = request[2]
1773
            kwargs = request[3]
1774
            
505.1.3 by Teddy Hogeborn
* mandos: Break long lines.
1775
            parent_pipe.send(('data', getattr(client_object,
1776
                                              funcname)(*args,
1777
                                                         **kwargs)))
24.1.185 by Björn Påhlsson
working transition code for going between se.bsnet.fukt to se.recompile
1778
        
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1779
        if command == 'getattr':
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1780
            attrname = request[1]
1781
            if callable(client_object.__getattribute__(attrname)):
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1782
                parent_pipe.send(('function',))
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1783
            else:
505.1.3 by Teddy Hogeborn
* mandos: Break long lines.
1784
                parent_pipe.send(('data', client_object
1785
                                  .__getattribute__(attrname)))
24.2.4 by teddy at bsnet
* mandos (ClientDBus.approvals_pending): Changed to be a property
1786
        
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1787
        if command == 'setattr':
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
1788
            attrname = request[1]
1789
            value = request[2]
1790
            setattr(client_object, attrname, value)
24.1.185 by Björn Påhlsson
working transition code for going between se.bsnet.fukt to se.recompile
1791
        
288.1.1 by Teddy Hogeborn
Start of new pipe-based IPC mechanism.
1792
        return True
10 by Teddy Hogeborn
* server.py: Bug fix: Do "from __future__ import division".
1793
3 by Björn Påhlsson
Python based server
1794
4 by Teddy Hogeborn
* server.py (Client.created, Client.next_check): New.
1795
def string_to_delta(interval):
1796
    """Parse a string and return a datetime.timedelta
290 by Teddy Hogeborn
* mandos (main): Bug fix: Do setgid before setuid. Add verbose GnuTLS
1797
    
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1798
    >>> string_to_delta('7d')
4 by Teddy Hogeborn
* server.py (Client.created, Client.next_check): New.
1799
    datetime.timedelta(7)
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1800
    >>> string_to_delta('60s')
4 by Teddy Hogeborn
* server.py (Client.created, Client.next_check): New.
1801
    datetime.timedelta(0, 60)
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1802
    >>> string_to_delta('60m')
4 by Teddy Hogeborn
* server.py (Client.created, Client.next_check): New.
1803
    datetime.timedelta(0, 3600)
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1804
    >>> string_to_delta('24h')
4 by Teddy Hogeborn
* server.py (Client.created, Client.next_check): New.
1805
    datetime.timedelta(1)
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1806
    >>> string_to_delta('1w')
4 by Teddy Hogeborn
* server.py (Client.created, Client.next_check): New.
1807
    datetime.timedelta(7)
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1808
    >>> string_to_delta('5m 30s')
93 by Teddy Hogeborn
* mandos (string_to_delta): Accept a whitespace-separated sequence of
1809
    datetime.timedelta(0, 330)
4 by Teddy Hogeborn
* server.py (Client.created, Client.next_check): New.
1810
    """
93 by Teddy Hogeborn
* mandos (string_to_delta): Accept a whitespace-separated sequence of
1811
    timevalue = datetime.timedelta(0)
1812
    for s in interval.split():
1813
        try:
215 by Teddy Hogeborn
* mandos: Remove unused "select" module. Import "ctypes.util".
1814
            suffix = unicode(s[-1])
1815
            value = int(s[:-1])
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1816
            if suffix == "d":
93 by Teddy Hogeborn
* mandos (string_to_delta): Accept a whitespace-separated sequence of
1817
                delta = datetime.timedelta(value)
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1818
            elif suffix == "s":
93 by Teddy Hogeborn
* mandos (string_to_delta): Accept a whitespace-separated sequence of
1819
                delta = datetime.timedelta(0, value)
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1820
            elif suffix == "m":
93 by Teddy Hogeborn
* mandos (string_to_delta): Accept a whitespace-separated sequence of
1821
                delta = datetime.timedelta(0, 0, 0, 0, value)
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1822
            elif suffix == "h":
93 by Teddy Hogeborn
* mandos (string_to_delta): Accept a whitespace-separated sequence of
1823
                delta = datetime.timedelta(0, 0, 0, 0, 0, value)
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1824
            elif suffix == "w":
93 by Teddy Hogeborn
* mandos (string_to_delta): Accept a whitespace-separated sequence of
1825
                delta = datetime.timedelta(0, 0, 0, 0, 0, 0, value)
1826
            else:
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1827
                raise ValueError("Unknown suffix %r" % suffix)
482 by Teddy Hogeborn
* mandos: Tolerate restarting Avahi servers. Also Changed to new
1828
        except (ValueError, IndexError) as e:
464 by Teddy Hogeborn
* debian/mandos-client.postrm (purge): Bug fix: update initramfs also
1829
            raise ValueError(*(e.args))
93 by Teddy Hogeborn
* mandos (string_to_delta): Accept a whitespace-separated sequence of
1830
        timevalue += delta
1831
    return timevalue
4 by Teddy Hogeborn
* server.py (Client.created, Client.next_check): New.
1832
8 by Teddy Hogeborn
* Makefile (client_debug): Bug fix; add quotes and / to CERT_ROOT.
1833
24.1.13 by Björn Påhlsson
mandosclient
1834
def if_nametoindex(interface):
333 by Teddy Hogeborn
Minor code cleanup; one minor bug fix.
1835
    """Call the C function if_nametoindex(), or equivalent
1836
    
1837
    Note: This function cannot accept a unicode string."""
24.1.13 by Björn Påhlsson
mandosclient
1838
    global if_nametoindex
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
1839
    try:
237.1.2 by Teddy Hogeborn
Further steps towards a D-Bus server interface, plus minor syntax
1840
        if_nametoindex = (ctypes.cdll.LoadLibrary
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1841
                          (ctypes.util.find_library("c"))
237.1.2 by Teddy Hogeborn
Further steps towards a D-Bus server interface, plus minor syntax
1842
                          .if_nametoindex)
12 by Teddy Hogeborn
* mandos-clients.conf ([foo]/dn, [foo]/password, [braxen_client]/dn,
1843
    except (OSError, AttributeError):
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1844
        logger.warning("Doing if_nametoindex the hard way")
24.1.13 by Björn Påhlsson
mandosclient
1845
        def if_nametoindex(interface):
28 by Teddy Hogeborn
* server.conf: New file.
1846
            "Get an interface index the hard way, i.e. using fcntl()"
1847
            SIOCGIFINDEX = 0x8933  # From /usr/include/linux/sockios.h
411 by Teddy Hogeborn
More consistent terminology: Clients are no longer "invalid" - they
1848
            with contextlib.closing(socket.socket()) as s:
237 by Teddy Hogeborn
* mandos: Also import "with_statement" and "absolute_import" from
1849
                ifreq = fcntl.ioctl(s, SIOCGIFINDEX,
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1850
                                    struct.pack(str("16s16x"),
333 by Teddy Hogeborn
Minor code cleanup; one minor bug fix.
1851
                                                interface))
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1852
            interface_index = struct.unpack(str("I"),
333 by Teddy Hogeborn
Minor code cleanup; one minor bug fix.
1853
                                            ifreq[16:20])[0]
28 by Teddy Hogeborn
* server.conf: New file.
1854
            return interface_index
24.1.13 by Björn Påhlsson
mandosclient
1855
    return if_nametoindex(interface)
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
1856
1857
47 by Teddy Hogeborn
* plugbasedclient.c: Renamed to "mandos-client.c". All users changed.
1858
def daemon(nochdir = False, noclose = False):
15 by Teddy Hogeborn
* mandos-clients.conf ([foo]): Uncommented.
1859
    """See daemon(3).  Standard BSD Unix function.
331 by Teddy Hogeborn
Minor code cleanup, and a bug fix.
1860
    
15 by Teddy Hogeborn
* mandos-clients.conf ([foo]): Uncommented.
1861
    This should really exist as os.daemon, but it doesn't (yet)."""
1862
    if os.fork():
1863
        sys.exit()
1864
    os.setsid()
1865
    if not nochdir:
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1866
        os.chdir("/")
46 by Teddy Hogeborn
* network-protocol.txt: New.
1867
    if os.fork():
1868
        sys.exit()
15 by Teddy Hogeborn
* mandos-clients.conf ([foo]): Uncommented.
1869
    if not noclose:
1870
        # Close all standard open file descriptors
28 by Teddy Hogeborn
* server.conf: New file.
1871
        null = os.open(os.path.devnull, os.O_NOCTTY | os.O_RDWR)
15 by Teddy Hogeborn
* mandos-clients.conf ([foo]): Uncommented.
1872
        if not stat.S_ISCHR(os.fstat(null).st_mode):
1873
            raise OSError(errno.ENODEV,
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1874
                          "%s not a character device"
388 by Teddy Hogeborn
* mandos (daemon): Use "os.path.devnull" in the error message.
1875
                          % os.path.devnull)
15 by Teddy Hogeborn
* mandos-clients.conf ([foo]): Uncommented.
1876
        os.dup2(null, sys.stdin.fileno())
1877
        os.dup2(null, sys.stdout.fileno())
1878
        os.dup2(null, sys.stderr.fileno())
1879
        if null > 2:
1880
            os.close(null)
1881
1882
16 by Teddy Hogeborn
* Makefile: Include targets for all binaries.
1883
def main():
327 by Teddy Hogeborn
Merge from pipe IPC branch.
1884
    
379 by Teddy Hogeborn
* mandos: Fix line lengths.
1885
    ##################################################################
327 by Teddy Hogeborn
Merge from pipe IPC branch.
1886
    # Parsing of options, both command line and config file
1887
    
474 by teddy at bsnet
* mandos: Use the new argparse library instead of optparse.
1888
    parser = argparse.ArgumentParser()
1889
    parser.add_argument("-v", "--version", action="version",
1890
                        version = "%%(prog)s %s" % version,
1891
                        help="show version number and exit")
1892
    parser.add_argument("-i", "--interface", metavar="IF",
1893
                        help="Bind to interface IF")
1894
    parser.add_argument("-a", "--address",
1895
                        help="Address to listen for requests on")
1896
    parser.add_argument("-p", "--port", type=int,
1897
                        help="Port number to receive requests on")
1898
    parser.add_argument("--check", action="store_true",
1899
                        help="Run self-test")
1900
    parser.add_argument("--debug", action="store_true",
1901
                        help="Debug mode; run in foreground and log"
1902
                        " to terminal")
1903
    parser.add_argument("--debuglevel", metavar="LEVEL",
1904
                        help="Debug level for stdout output")
1905
    parser.add_argument("--priority", help="GnuTLS"
1906
                        " priority string (see GnuTLS documentation)")
1907
    parser.add_argument("--servicename",
1908
                        metavar="NAME", help="Zeroconf service name")
1909
    parser.add_argument("--configdir",
1910
                        default="/etc/mandos", metavar="DIR",
1911
                        help="Directory to search for configuration"
1912
                        " files")
1913
    parser.add_argument("--no-dbus", action="store_false",
1914
                        dest="use_dbus", help="Do not provide D-Bus"
1915
                        " system bus interface")
1916
    parser.add_argument("--no-ipv6", action="store_false",
1917
                        dest="use_ipv6", help="Do not use IPv6")
518.1.1 by Björn Påhlsson
Persistent state: New feature. Client state is now stored when mandos
1918
    parser.add_argument("--no-restore", action="store_false",
1919
                        dest="restore", help="Do not restore old state",
1920
                        default=True)
1921
474 by teddy at bsnet
* mandos: Use the new argparse library instead of optparse.
1922
    options = parser.parse_args()
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
1923
    
4 by Teddy Hogeborn
* server.py (Client.created, Client.next_check): New.
1924
    if options.check:
1925
        import doctest
1926
        doctest.testmod()
1927
        sys.exit()
3 by Björn Påhlsson
Python based server
1928
    
28 by Teddy Hogeborn
* server.conf: New file.
1929
    # Default values for config file for server-global settings
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1930
    server_defaults = { "interface": "",
1931
                        "address": "",
1932
                        "port": "",
1933
                        "debug": "False",
1934
                        "priority":
1935
                        "SECURE256:!CTYPE-X.509:+CTYPE-OPENPGP",
1936
                        "servicename": "Mandos",
1937
                        "use_dbus": "True",
1938
                        "use_ipv6": "True",
1939
                        "debuglevel": "",
28 by Teddy Hogeborn
* server.conf: New file.
1940
                        }
1941
    
1942
    # Parse config file for server-global settings
335 by Teddy Hogeborn
* mandos: Import "SocketServer" as "socketserver" and "ConfigParser"
1943
    server_config = configparser.SafeConfigParser(server_defaults)
28 by Teddy Hogeborn
* server.conf: New file.
1944
    del server_defaults
333 by Teddy Hogeborn
Minor code cleanup; one minor bug fix.
1945
    server_config.read(os.path.join(options.configdir,
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1946
                                    "mandos.conf"))
28 by Teddy Hogeborn
* server.conf: New file.
1947
    # Convert the SafeConfigParser object to a dict
89 by Teddy Hogeborn
* Makefile: Bug fix: fixed creation of man pages for section 5 pages.
1948
    server_settings = server_config.defaults()
282 by Teddy Hogeborn
* mandos (main): Bug fix: use "getint" on the "port" config file
1949
    # Use the appropriate methods on the non-string config options
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1950
    for option in ("debug", "use_dbus", "use_ipv6"):
1951
        server_settings[option] = server_config.getboolean("DEFAULT",
333 by Teddy Hogeborn
Minor code cleanup; one minor bug fix.
1952
                                                           option)
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1953
    if server_settings["port"]:
1954
        server_settings["port"] = server_config.getint("DEFAULT",
1955
                                                       "port")
28 by Teddy Hogeborn
* server.conf: New file.
1956
    del server_config
1957
    
1958
    # Override the settings from the config file with command line
1959
    # options, if set.
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1960
    for option in ("interface", "address", "port", "debug",
1961
                   "priority", "servicename", "configdir",
518.1.1 by Björn Påhlsson
Persistent state: New feature. Client state is now stored when mandos
1962
                   "use_dbus", "use_ipv6", "debuglevel", "restore"):
28 by Teddy Hogeborn
* server.conf: New file.
1963
        value = getattr(options, option)
1964
        if value is not None:
1965
            server_settings[option] = value
1966
    del options
333 by Teddy Hogeborn
Minor code cleanup; one minor bug fix.
1967
    # Force all strings to be unicode
1968
    for option in server_settings.keys():
1969
        if type(server_settings[option]) is str:
1970
            server_settings[option] = unicode(server_settings[option])
28 by Teddy Hogeborn
* server.conf: New file.
1971
    # Now we have our good server settings in "server_settings"
1972
    
327 by Teddy Hogeborn
Merge from pipe IPC branch.
1973
    ##################################################################
1974
    
243 by Teddy Hogeborn
* mandos (Client.timeout, Client.interval): Changed from being a
1975
    # For convenience
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1976
    debug = server_settings["debug"]
1977
    debuglevel = server_settings["debuglevel"]
1978
    use_dbus = server_settings["use_dbus"]
1979
    use_ipv6 = server_settings["use_ipv6"]
24.1.185 by Björn Påhlsson
working transition code for going between se.bsnet.fukt to se.recompile
1980
    
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1981
    if server_settings["servicename"] != "Mandos":
237.1.2 by Teddy Hogeborn
Further steps towards a D-Bus server interface, plus minor syntax
1982
        syslogger.setFormatter(logging.Formatter
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1983
                               ('Mandos (%s) [%%(process)d]:'
1984
                                ' %%(levelname)s: %%(message)s'
1985
                                % server_settings["servicename"]))
52 by Teddy Hogeborn
* mandos: Make syslog use "/dev/log" instead of UDP to localhost.
1986
    
28 by Teddy Hogeborn
* server.conf: New file.
1987
    # Parse config file with clients
24.1.179 by Björn Påhlsson
New feature:
1988
    client_defaults = { "timeout": "5m",
1989
                        "extended_timeout": "15m",
1990
                        "interval": "2m",
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1991
                        "checker": "fping -q -- %%(host)s",
1992
                        "host": "",
1993
                        "approval_delay": "0s",
1994
                        "approval_duration": "1s",
28 by Teddy Hogeborn
* server.conf: New file.
1995
                        }
335 by Teddy Hogeborn
* mandos: Import "SocketServer" as "socketserver" and "ConfigParser"
1996
    client_config = configparser.SafeConfigParser(client_defaults)
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
1997
    client_config.read(os.path.join(server_settings["configdir"],
1998
                                    "clients.conf"))
333 by Teddy Hogeborn
Minor code cleanup; one minor bug fix.
1999
    
327 by Teddy Hogeborn
Merge from pipe IPC branch.
2000
    global mandos_dbus_service
2001
    mandos_dbus_service = None
28 by Teddy Hogeborn
* server.conf: New file.
2002
    
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
2003
    tcp_server = MandosServer((server_settings["address"],
2004
                               server_settings["port"]),
339 by Teddy Hogeborn
Code cleanup.
2005
                              ClientHandler,
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
2006
                              interface=(server_settings["interface"]
237.2.35 by teddy at bsnet
* mandos (main): Bug fix: Don't try to bind to an empty string
2007
                                         or None),
339 by Teddy Hogeborn
Code cleanup.
2008
                              use_ipv6=use_ipv6,
2009
                              gnutls_priority=
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
2010
                              server_settings["priority"],
339 by Teddy Hogeborn
Code cleanup.
2011
                              use_dbus=use_dbus)
439 by Teddy Hogeborn
* mandos: Do not write pid file if --debug is passed.
2012
    if not debug:
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
2013
        pidfilename = "/var/run/mandos.pid"
439 by Teddy Hogeborn
* mandos: Do not write pid file if --debug is passed.
2014
        try:
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
2015
            pidfile = open(pidfilename, "w")
439 by Teddy Hogeborn
* mandos: Do not write pid file if --debug is passed.
2016
        except IOError:
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
2017
            logger.error("Could not open file %r", pidfilename)
164 by Teddy Hogeborn
* mandos: Open the PID file before daemonizing, but write to it
2018
    
238 by Teddy Hogeborn
First version of a somewhat complete D-Bus server interface. Also
2019
    try:
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
2020
        uid = pwd.getpwnam("_mandos").pw_uid
2021
        gid = pwd.getpwnam("_mandos").pw_gid
238 by Teddy Hogeborn
First version of a somewhat complete D-Bus server interface. Also
2022
    except KeyError:
2023
        try:
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
2024
            uid = pwd.getpwnam("mandos").pw_uid
2025
            gid = pwd.getpwnam("mandos").pw_gid
238 by Teddy Hogeborn
First version of a somewhat complete D-Bus server interface. Also
2026
        except KeyError:
2027
            try:
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
2028
                uid = pwd.getpwnam("nobody").pw_uid
2029
                gid = pwd.getpwnam("nobody").pw_gid
238 by Teddy Hogeborn
First version of a somewhat complete D-Bus server interface. Also
2030
            except KeyError:
2031
                uid = 65534
2032
                gid = 65534
163 by Teddy Hogeborn
* Makefile (PIDDIR, USER, GROUP): Removed.
2033
    try:
290 by Teddy Hogeborn
* mandos (main): Bug fix: Do setgid before setuid. Add verbose GnuTLS
2034
        os.setgid(gid)
163 by Teddy Hogeborn
* Makefile (PIDDIR, USER, GROUP): Removed.
2035
        os.setuid(uid)
482 by Teddy Hogeborn
* mandos: Tolerate restarting Avahi servers. Also Changed to new
2036
    except OSError as error:
163 by Teddy Hogeborn
* Makefile (PIDDIR, USER, GROUP): Removed.
2037
        if error[0] != errno.EPERM:
2038
            raise error
164 by Teddy Hogeborn
* mandos: Open the PID file before daemonizing, but write to it
2039
    
24.1.155 by Björn Påhlsson
mandos server: Added debuglevel that adjust at what level information
2040
    if not debug and not debuglevel:
2041
        syslogger.setLevel(logging.WARNING)
2042
        console.setLevel(logging.WARNING)
2043
    if debuglevel:
2044
        level = getattr(logging, debuglevel.upper())
2045
        syslogger.setLevel(level)
2046
        console.setLevel(level)
24.1.185 by Björn Påhlsson
working transition code for going between se.bsnet.fukt to se.recompile
2047
    
290 by Teddy Hogeborn
* mandos (main): Bug fix: Do setgid before setuid. Add verbose GnuTLS
2048
    if debug:
422 by Teddy Hogeborn
Rename all D-Bus properties to conform to D-Bus naming conventions;
2049
        # Enable all possible GnuTLS debugging
2050
        
290 by Teddy Hogeborn
* mandos (main): Bug fix: Do setgid before setuid. Add verbose GnuTLS
2051
        # "Use a log level over 10 to enable all debugging options."
2052
        # - GnuTLS manual
2053
        gnutls.library.functions.gnutls_global_set_log_level(11)
2054
        
2055
        @gnutls.library.types.gnutls_log_func
2056
        def debug_gnutls(level, string):
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
2057
            logger.debug("GnuTLS: %s", string[:-1])
290 by Teddy Hogeborn
* mandos (main): Bug fix: Do setgid before setuid. Add verbose GnuTLS
2058
        
2059
        (gnutls.library.functions
2060
         .gnutls_global_set_log_function(debug_gnutls))
422 by Teddy Hogeborn
Rename all D-Bus properties to conform to D-Bus naming conventions;
2061
        
24.1.155 by Björn Påhlsson
mandos server: Added debuglevel that adjust at what level information
2062
        # Redirect stdin so all checkers get /dev/null
2063
        null = os.open(os.path.devnull, os.O_NOCTTY | os.O_RDWR)
2064
        os.dup2(null, sys.stdin.fileno())
2065
        if null > 2:
2066
            os.close(null)
2067
    else:
2068
        # No console logging
2069
        logger.removeHandler(console)
422 by Teddy Hogeborn
Rename all D-Bus properties to conform to D-Bus naming conventions;
2070
    
458 by teddy at bsnet
* mandos (main): Bug fix: Fork before connecting to D-Bus.
2071
    # Need to fork before connecting to D-Bus
2072
    if not debug:
2073
        # Close all input and output, do double fork, etc.
2074
        daemon()
290 by Teddy Hogeborn
* mandos (main): Bug fix: Do setgid before setuid. Add verbose GnuTLS
2075
    
16 by Teddy Hogeborn
* Makefile: Include targets for all binaries.
2076
    global main_loop
2077
    # From the Avahi example code
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
2078
    DBusGMainLoop(set_as_default=True )
2079
    main_loop = gobject.MainLoop()
2080
    bus = dbus.SystemBus()
2081
    # End of Avahi example code
243 by Teddy Hogeborn
* mandos (Client.timeout, Client.interval): Changed from being a
2082
    if use_dbus:
402 by Teddy Hogeborn
* mandos (Client.disable): Rename keyword argument "log" to "quiet",
2083
        try:
505 by Björn Påhlsson
The domain name has changed, so the D-Bus bus and interface names must
2084
            bus_name = dbus.service.BusName("se.recompile.Mandos",
402 by Teddy Hogeborn
* mandos (Client.disable): Rename keyword argument "log" to "quiet",
2085
                                            bus, do_not_queue=True)
505.1.3 by Teddy Hogeborn
* mandos: Break long lines.
2086
            old_bus_name = (dbus.service.BusName
2087
                            ("se.bsnet.fukt.Mandos", bus,
2088
                             do_not_queue=True))
482 by Teddy Hogeborn
* mandos: Tolerate restarting Avahi servers. Also Changed to new
2089
        except dbus.exceptions.NameExistsException as e:
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
2090
            logger.error(unicode(e) + ", disabling D-Bus")
402 by Teddy Hogeborn
* mandos (Client.disable): Rename keyword argument "log" to "quiet",
2091
            use_dbus = False
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
2092
            server_settings["use_dbus"] = False
402 by Teddy Hogeborn
* mandos (Client.disable): Rename keyword argument "log" to "quiet",
2093
            tcp_server.use_dbus = False
337 by Teddy Hogeborn
Code cleanup. Move some global stuff into main.
2094
    protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
2095
    service = AvahiService(name = server_settings["servicename"],
2096
                           servicetype = "_mandos._tcp",
337 by Teddy Hogeborn
Code cleanup. Move some global stuff into main.
2097
                           protocol = protocol, bus = bus)
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
2098
    if server_settings["interface"]:
337 by Teddy Hogeborn
Code cleanup. Move some global stuff into main.
2099
        service.interface = (if_nametoindex
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
2100
                             (str(server_settings["interface"])))
458 by teddy at bsnet
* mandos (main): Bug fix: Fork before connecting to D-Bus.
2101
    
24.1.152 by Björn Påhlsson
bug fixes that prevent problems when runing server as root
2102
    global multiprocessing_manager
2103
    multiprocessing_manager = multiprocessing.Manager()
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
2104
    
328 by Teddy Hogeborn
* mandos (Client): Move all D-Bus code to new "ClientDBus" class.
2105
    client_class = Client
2106
    if use_dbus:
505.1.3 by Teddy Hogeborn
* mandos: Break long lines.
2107
        client_class = functools.partial(ClientDBusTransitional,
505.1.4 by Teddy Hogeborn
Removed superflous white space.
2108
                                         bus = bus)
518.1.1 by Björn Påhlsson
Persistent state: New feature. Client state is now stored when mandos
2109
    
2110
    special_settings = {
2111
        # Some settings need to be accessd by special methods;
2112
        # booleans need .getboolean(), etc.  Here is a list of them:
2113
        "approved_by_default":
2114
            lambda section:
2115
            client_config.getboolean(section, "approved_by_default"),
2116
        }
2117
    # Construct a new dict of client settings of this form:
2118
    # { client_name: {setting_name: value, ...}, ...}
2119
    # with exceptions for any special settings as defined above
2120
    client_settings = dict((clientname,
2121
                           dict((setting,
2122
                                 (value if setting not in special_settings
2123
                                  else special_settings[setting](clientname)))
2124
                                for setting, value in client_config.items(clientname)))
2125
                          for clientname in client_config.sections())
2126
    
2127
    old_client_settings = {}
2128
    clients_data = []
2129
2130
    if server_settings["restore"]:
2131
        try:
2132
            with open(stored_state_path, "rb") as stored_state:
2133
                clients_data, old_client_settings = pickle.load(stored_state)
2134
            os.remove(stored_state_path)
2135
        except IOError as e:
2136
            logger.warning("Could not load persistant state: {0}".format(e))
2137
            if e.errno != errno.ENOENT:
2138
                raise
2139
2140
    for client in clients_data:
2141
        client_name = client["name"]
2142
        
2143
        # Decide which value to use after restoring saved state.
2144
        # We have three different values: Old config file,
2145
        # new config file, and saved state.
2146
        # New config value takes precedence if it differs from old
2147
        # config value, otherwise use saved state.
2148
        for name, value in client_settings[client_name].items():
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
2149
            try:
518.1.1 by Björn Påhlsson
Persistent state: New feature. Client state is now stored when mandos
2150
                # For each value in new config, check if it differs
2151
                # from the old config value (Except for the "secret"
2152
                # attribute)
2153
                if name != "secret" and value != old_client_settings[client_name][name]:
2154
                    setattr(client, name, value)
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
2155
            except KeyError:
518.1.1 by Björn Påhlsson
Persistent state: New feature. Client state is now stored when mandos
2156
                pass
2157
2158
        # Clients who has passed its expire date, can still be enabled if its
2159
        # last checker was sucessful. Clients who checkers failed before we
2160
        # stored it state is asumed to had failed checker during downtime.
2161
        if client["enabled"] and client["last_checked_ok"]:
2162
            if ((datetime.datetime.utcnow() - client["last_checked_ok"])
2163
                > client["interval"]):
2164
                if client["last_checker_status"] != 0:
2165
                    client["enabled"] = False
2166
                else:
2167
                    client["expires"] = datetime.datetime.utcnow() + client["timeout"]
2168
2169
        client["changedstate"] = (multiprocessing_manager
2170
                                  .Condition(multiprocessing_manager
2171
                                             .Lock()))
2172
        if use_dbus:
2173
            new_client = ClientDBusTransitional.__new__(ClientDBusTransitional)
2174
            tcp_server.clients[client_name] = new_client
2175
            new_client.bus = bus
2176
            for name, value in client.iteritems():
2177
                setattr(new_client, name, value)
2178
            client_object_name = unicode(client_name).translate(
2179
                {ord("."): ord("_"),
2180
                 ord("-"): ord("_")})
2181
            new_client.dbus_object_path = (dbus.ObjectPath
2182
                                     ("/clients/" + client_object_name))
2183
            DBusObjectWithProperties.__init__(new_client,
2184
                                              new_client.bus,
2185
                                              new_client.dbus_object_path)
2186
        else:
2187
            tcp_server.clients[client_name] = Client.__new__(Client)
2188
            for name, value in client.iteritems():
2189
                setattr(tcp_server.clients[client_name], name, value)
2190
                
2191
        tcp_server.clients[client_name].decrypt_secret(
2192
            client_settings[client_name]["secret"])            
2193
        
2194
    # Create/remove clients based on new changes made to config
2195
    for clientname in set(old_client_settings) - set(client_settings):
2196
        del tcp_server.clients[clientname]
2197
    for clientname in set(client_settings) - set(old_client_settings):
2198
        tcp_server.clients[clientname] = (client_class(name = clientname,
2199
                                                       config =
2200
                                                       client_settings
2201
                                                       [clientname]))
24.1.149 by Björn Påhlsson
Changed ForkingMixIn in favor of multiprocessing
2202
    
518.1.1 by Björn Påhlsson
Persistent state: New feature. Client state is now stored when mandos
2203
341 by Teddy Hogeborn
Code cleanup and one bug fix.
2204
    if not tcp_server.clients:
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
2205
        logger.warning("No clients defined")
24.1.155 by Björn Påhlsson
mandos server: Added debuglevel that adjust at what level information
2206
        
15 by Teddy Hogeborn
* mandos-clients.conf ([foo]): Uncommented.
2207
    if not debug:
439 by Teddy Hogeborn
* mandos: Do not write pid file if --debug is passed.
2208
        try:
2209
            with pidfile:
2210
                pid = os.getpid()
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
2211
                pidfile.write(str(pid) + "\n".encode("utf-8"))
439 by Teddy Hogeborn
* mandos: Do not write pid file if --debug is passed.
2212
            del pidfile
2213
        except IOError:
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
2214
            logger.error("Could not write to file %r with PID %d",
439 by Teddy Hogeborn
* mandos: Do not write pid file if --debug is passed.
2215
                         pidfilename, pid)
2216
        except NameError:
2217
            # "pidfile" was never created
2218
            pass
2219
        del pidfilename
2220
        
15 by Teddy Hogeborn
* mandos-clients.conf ([foo]): Uncommented.
2221
        signal.signal(signal.SIGINT, signal.SIG_IGN)
24.1.185 by Björn Påhlsson
working transition code for going between se.bsnet.fukt to se.recompile
2222
    
28 by Teddy Hogeborn
* server.conf: New file.
2223
    signal.signal(signal.SIGHUP, lambda signum, frame: sys.exit())
2224
    signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit())
15 by Teddy Hogeborn
* mandos-clients.conf ([foo]): Uncommented.
2225
    
243 by Teddy Hogeborn
* mandos (Client.timeout, Client.interval): Changed from being a
2226
    if use_dbus:
327 by Teddy Hogeborn
Merge from pipe IPC branch.
2227
        class MandosDBusService(dbus.service.Object):
243 by Teddy Hogeborn
* mandos (Client.timeout, Client.interval): Changed from being a
2228
            """A D-Bus proxy object"""
2229
            def __init__(self):
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
2230
                dbus.service.Object.__init__(self, bus, "/")
505.1.1 by Teddy Hogeborn
* mandos (transitional_dbus_metaclass): Renamed to
2231
            _interface = "se.recompile.Mandos"
278 by Teddy Hogeborn
* mandos (Client.GetAllProperties): Also send Client.dbus_object_path
2232
            
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
2233
            @dbus.service.signal(_interface, signature="o")
411 by Teddy Hogeborn
More consistent terminology: Clients are no longer "invalid" - they
2234
            def ClientAdded(self, objpath):
243 by Teddy Hogeborn
* mandos (Client.timeout, Client.interval): Changed from being a
2235
                "D-Bus signal"
2236
                pass
278 by Teddy Hogeborn
* mandos (Client.GetAllProperties): Also send Client.dbus_object_path
2237
            
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
2238
            @dbus.service.signal(_interface, signature="ss")
409 by Teddy Hogeborn
* mandos (MandosServer.handle_ipc): Better log message.
2239
            def ClientNotFound(self, fingerprint, address):
327 by Teddy Hogeborn
Merge from pipe IPC branch.
2240
                "D-Bus signal"
2241
                pass
2242
            
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
2243
            @dbus.service.signal(_interface, signature="os")
278 by Teddy Hogeborn
* mandos (Client.GetAllProperties): Also send Client.dbus_object_path
2244
            def ClientRemoved(self, objpath, name):
243 by Teddy Hogeborn
* mandos (Client.timeout, Client.interval): Changed from being a
2245
                "D-Bus signal"
2246
                pass
278 by Teddy Hogeborn
* mandos (Client.GetAllProperties): Also send Client.dbus_object_path
2247
            
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
2248
            @dbus.service.method(_interface, out_signature="ao")
243 by Teddy Hogeborn
* mandos (Client.timeout, Client.interval): Changed from being a
2249
            def GetAllClients(self):
283 by Teddy Hogeborn
* mandos (peer_certificate): Handle NULL pointer from
2250
                "D-Bus method"
341 by Teddy Hogeborn
Code cleanup and one bug fix.
2251
                return dbus.Array(c.dbus_object_path
518.1.1 by Björn Påhlsson
Persistent state: New feature. Client state is now stored when mandos
2252
                                  for c in
2253
                                  tcp_server.clients.itervalues())
278 by Teddy Hogeborn
* mandos (Client.GetAllProperties): Also send Client.dbus_object_path
2254
            
333 by Teddy Hogeborn
Minor code cleanup; one minor bug fix.
2255
            @dbus.service.method(_interface,
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
2256
                                 out_signature="a{oa{sv}}")
243 by Teddy Hogeborn
* mandos (Client.timeout, Client.interval): Changed from being a
2257
            def GetAllClientsWithProperties(self):
283 by Teddy Hogeborn
* mandos (peer_certificate): Handle NULL pointer from
2258
                "D-Bus method"
243 by Teddy Hogeborn
* mandos (Client.timeout, Client.interval): Changed from being a
2259
                return dbus.Dictionary(
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
2260
                    ((c.dbus_object_path, c.GetAll(""))
518.1.1 by Björn Påhlsson
Persistent state: New feature. Client state is now stored when mandos
2261
                     for c in tcp_server.clients.itervalues()),
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
2262
                    signature="oa{sv}")
278 by Teddy Hogeborn
* mandos (Client.GetAllProperties): Also send Client.dbus_object_path
2263
            
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
2264
            @dbus.service.method(_interface, in_signature="o")
243 by Teddy Hogeborn
* mandos (Client.timeout, Client.interval): Changed from being a
2265
            def RemoveClient(self, object_path):
283 by Teddy Hogeborn
* mandos (peer_certificate): Handle NULL pointer from
2266
                "D-Bus method"
518.1.1 by Björn Påhlsson
Persistent state: New feature. Client state is now stored when mandos
2267
                for c in tcp_server.clients.itervalues():
243 by Teddy Hogeborn
* mandos (Client.timeout, Client.interval): Changed from being a
2268
                    if c.dbus_object_path == object_path:
518.1.1 by Björn Påhlsson
Persistent state: New feature. Client state is now stored when mandos
2269
                        del tcp_server.clients[c.name]
328 by Teddy Hogeborn
* mandos (Client): Move all D-Bus code to new "ClientDBus" class.
2270
                        c.remove_from_connection()
243 by Teddy Hogeborn
* mandos (Client.timeout, Client.interval): Changed from being a
2271
                        # Don't signal anything except ClientRemoved
402 by Teddy Hogeborn
* mandos (Client.disable): Rename keyword argument "log" to "quiet",
2272
                        c.disable(quiet=True)
243 by Teddy Hogeborn
* mandos (Client.timeout, Client.interval): Changed from being a
2273
                        # Emit D-Bus signal
278 by Teddy Hogeborn
* mandos (Client.GetAllProperties): Also send Client.dbus_object_path
2274
                        self.ClientRemoved(object_path, c.name)
2275
                        return
400 by Teddy Hogeborn
* mandos (Client.enable): Bug fix: Start new immediate checker last to
2276
                raise KeyError(object_path)
278 by Teddy Hogeborn
* mandos (Client.GetAllProperties): Also send Client.dbus_object_path
2277
            
243 by Teddy Hogeborn
* mandos (Client.timeout, Client.interval): Changed from being a
2278
            del _interface
278 by Teddy Hogeborn
* mandos (Client.GetAllProperties): Also send Client.dbus_object_path
2279
        
24.1.186 by Björn Påhlsson
transitional stuff actually working
2280
        class MandosDBusServiceTransitional(MandosDBusService):
505.1.1 by Teddy Hogeborn
* mandos (transitional_dbus_metaclass): Renamed to
2281
            __metaclass__ = AlternateDBusNamesMetaclass
24.1.186 by Björn Påhlsson
transitional stuff actually working
2282
        mandos_dbus_service = MandosDBusServiceTransitional()
238 by Teddy Hogeborn
First version of a somewhat complete D-Bus server interface. Also
2283
    
400 by Teddy Hogeborn
* mandos (Client.enable): Bug fix: Start new immediate checker last to
2284
    def cleanup():
2285
        "Cleanup function; run on exit"
2286
        service.cleanup()
2287
        
505.1.11 by Teddy Hogeborn
* mandos (Client.checked_ok): Set "expires" after setting timeout.
2288
        multiprocessing.active_children()
518.1.1 by Björn Påhlsson
Persistent state: New feature. Client state is now stored when mandos
2289
        if not (tcp_server.clients or client_settings):
2290
            return
2291
2292
        # Store client before exiting. Secrets are encrypted with key based
2293
        # on what config file has. If config file is removed/edited, old
2294
        # secret will thus be unrecovable.
2295
        clients = []
2296
        for client in tcp_server.clients.itervalues():
2297
            client.encrypt_secret(client_settings[client.name]["secret"])
2298
2299
            client_dict = {}
2300
2301
            # A list of attributes that will not be stored when shuting down.
2302
            exclude = set(("bus", "changedstate", "secret"))            
2303
            for name, typ in inspect.getmembers(dbus.service.Object):
2304
                exclude.add(name)
2305
                
2306
            client_dict["encrypted_secret"] = client.encrypted_secret
2307
            for attr in client.client_structure:
2308
                if attr not in exclude:
2309
                    client_dict[attr] = getattr(client, attr)
2310
2311
            clients.append(client_dict) 
2312
            del client_settings[client.name]["secret"]
2313
            
2314
        try:
2315
            with os.fdopen(os.open(stored_state_path, os.O_CREAT|os.O_WRONLY|os.O_TRUNC, 0600), "wb") as stored_state:
2316
                pickle.dump((clients, client_settings), stored_state)
2317
        except IOError as e:
2318
            logger.warning("Could not save persistant state: {0}".format(e))
2319
            if e.errno != errno.ENOENT:
2320
                raise
2321
2322
        # Delete all clients, and settings from config
400 by Teddy Hogeborn
* mandos (Client.enable): Bug fix: Start new immediate checker last to
2323
        while tcp_server.clients:
518.1.1 by Björn Påhlsson
Persistent state: New feature. Client state is now stored when mandos
2324
            name, client = tcp_server.clients.popitem()
402 by Teddy Hogeborn
* mandos (Client.disable): Rename keyword argument "log" to "quiet",
2325
            if use_dbus:
2326
                client.remove_from_connection()
400 by Teddy Hogeborn
* mandos (Client.enable): Bug fix: Start new immediate checker last to
2327
            # Don't signal anything except ClientRemoved
402 by Teddy Hogeborn
* mandos (Client.disable): Rename keyword argument "log" to "quiet",
2328
            client.disable(quiet=True)
400 by Teddy Hogeborn
* mandos (Client.enable): Bug fix: Start new immediate checker last to
2329
            if use_dbus:
2330
                # Emit D-Bus signal
505.1.3 by Teddy Hogeborn
* mandos: Break long lines.
2331
                mandos_dbus_service.ClientRemoved(client
518.1.1 by Björn Påhlsson
Persistent state: New feature. Client state is now stored when mandos
2332
                                              .dbus_object_path,
2333
                                              client.name)
2334
        client_settings.clear()
400 by Teddy Hogeborn
* mandos (Client.enable): Bug fix: Start new immediate checker last to
2335
    
2336
    atexit.register(cleanup)
2337
    
518.1.1 by Björn Påhlsson
Persistent state: New feature. Client state is now stored when mandos
2338
    for client in tcp_server.clients.itervalues():
243 by Teddy Hogeborn
* mandos (Client.timeout, Client.interval): Changed from being a
2339
        if use_dbus:
2340
            # Emit D-Bus signal
411 by Teddy Hogeborn
More consistent terminology: Clients are no longer "invalid" - they
2341
            mandos_dbus_service.ClientAdded(client.dbus_object_path)
518.1.1 by Björn Påhlsson
Persistent state: New feature. Client state is now stored when mandos
2342
        # Need to initiate checking of clients
2343
        if client.enabled:
2344
            client.init_checker()
2345
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
2346
    
163 by Teddy Hogeborn
* Makefile (PIDDIR, USER, GROUP): Removed.
2347
    tcp_server.enable()
2348
    tcp_server.server_activate()
2349
    
28 by Teddy Hogeborn
* server.conf: New file.
2350
    # Find out what port we got
2351
    service.port = tcp_server.socket.getsockname()[1]
314 by Teddy Hogeborn
Support not using IPv6 in server:
2352
    if use_ipv6:
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
2353
        logger.info("Now listening on address %r, port %d,"
2354
                    " flowinfo %d, scope_id %d"
314 by Teddy Hogeborn
Support not using IPv6 in server:
2355
                    % tcp_server.socket.getsockname())
2356
    else:                       # IPv4
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
2357
        logger.info("Now listening on address %r, port %d"
314 by Teddy Hogeborn
Support not using IPv6 in server:
2358
                    % tcp_server.socket.getsockname())
28 by Teddy Hogeborn
* server.conf: New file.
2359
    
29 by Teddy Hogeborn
* plugins.d/mandosclient.c (start_mandos_communication): Changed
2360
    #service.interface = tcp_server.socket.getsockname()[3]
28 by Teddy Hogeborn
* server.conf: New file.
2361
    
2362
    try:
2363
        # From the Avahi example code
2364
        try:
336 by Teddy Hogeborn
Code cleanup.
2365
            service.activate()
482 by Teddy Hogeborn
* mandos: Tolerate restarting Avahi servers. Also Changed to new
2366
        except dbus.exceptions.DBusException as error:
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
2367
            logger.critical("DBusException: %s", error)
401 by Teddy Hogeborn
* README (FAQ): Fix typo.
2368
            cleanup()
28 by Teddy Hogeborn
* server.conf: New file.
2369
            sys.exit(1)
2370
        # End of Avahi example code
2371
        
2372
        gobject.io_add_watch(tcp_server.fileno(), gobject.IO_IN,
2373
                             lambda *args, **kwargs:
237.1.2 by Teddy Hogeborn
Further steps towards a D-Bus server interface, plus minor syntax
2374
                             (tcp_server.handle_request
2375
                              (*args[2:], **kwargs) or True))
28 by Teddy Hogeborn
* server.conf: New file.
2376
        
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
2377
        logger.debug("Starting main loop")
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
2378
        main_loop.run()
482 by Teddy Hogeborn
* mandos: Tolerate restarting Avahi servers. Also Changed to new
2379
    except AvahiError as error:
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
2380
        logger.critical("AvahiError: %s", error)
401 by Teddy Hogeborn
* README (FAQ): Fix typo.
2381
        cleanup()
28 by Teddy Hogeborn
* server.conf: New file.
2382
        sys.exit(1)
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
2383
    except KeyboardInterrupt:
15 by Teddy Hogeborn
* mandos-clients.conf ([foo]): Uncommented.
2384
        if debug:
463.1.5 by teddy at bsnet
* mandos: Use unicode string literals.
2385
            print("", file=sys.stderr)
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
2386
        logger.debug("Server received KeyboardInterrupt")
2387
    logger.debug("Server exiting")
401 by Teddy Hogeborn
* README (FAQ): Fix typo.
2388
    # Must run before the D-Bus bus name gets deregistered
2389
    cleanup()
16 by Teddy Hogeborn
* Makefile: Include targets for all binaries.
2390
24.1.185 by Björn Påhlsson
working transition code for going between se.bsnet.fukt to se.recompile
2391
463.1.4 by teddy at bsnet
* mandos: Use unicode string literals.
2392
if __name__ == '__main__':
16 by Teddy Hogeborn
* Makefile: Include targets for all binaries.
2393
    main()