/mandos/release

To get this branch, use:
bzr branch http://bzr.recompile.se/loggerhead/mandos/release
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
46 by Teddy Hogeborn
* network-protocol.txt: New.
9
# methods "add" and "remove" in the "AvahiService" class, the
10
# "server_state_changed" and "entry_group_state_changed" functions,
11
# 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
24.1.102 by Björn Påhlsson
changed 2007-2008 copyright notice to 2008
14
# Copyright © 2008 Teddy Hogeborn & Björn Påhlsson
16 by Teddy Hogeborn
* Makefile: Include targets for all binaries.
15
# 
16
# This program is free software: you can redistribute it and/or modify
17
# it under the terms of the GNU General Public License as published by
18
# the Free Software Foundation, either version 3 of the License, or
19
# (at your option) any later version.
20
#
21
#     This program is distributed in the hope that it will be useful,
22
#     but WITHOUT ANY WARRANTY; without even the implied warranty of
23
#     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
24
#     GNU General Public License for more details.
25
# 
26
# You should have received a copy of the GNU General Public License
109 by Teddy Hogeborn
* .bzrignore: New.
27
# along with this program.  If not, see
28
# <http://www.gnu.org/licenses/>.
16 by Teddy Hogeborn
* Makefile: Include targets for all binaries.
29
# 
28 by Teddy Hogeborn
* server.conf: New file.
30
# Contact the authors at <mandos@fukt.bsnet.se>.
16 by Teddy Hogeborn
* Makefile: Include targets for all binaries.
31
# 
3 by Björn Påhlsson
Python based server
32
10 by Teddy Hogeborn
* server.py: Bug fix: Do "from __future__ import division".
33
from __future__ import division
34
3 by Björn Påhlsson
Python based server
35
import SocketServer
36
import socket
37
from optparse import OptionParser
38
import datetime
39
import errno
40
import gnutls.crypto
41
import gnutls.connection
42
import gnutls.errors
12 by Teddy Hogeborn
* mandos-clients.conf ([foo]/dn, [foo]/password, [braxen_client]/dn,
43
import gnutls.library.functions
44
import gnutls.library.constants
45
import gnutls.library.types
3 by Björn Påhlsson
Python based server
46
import ConfigParser
4 by Teddy Hogeborn
* server.py (Client.created, Client.next_check): New.
47
import sys
9 by Teddy Hogeborn
* client.cpp (main): Get t_old early since it is used on error exits.
48
import re
49
import os
50
import signal
10 by Teddy Hogeborn
* server.py: Bug fix: Do "from __future__ import division".
51
from sets import Set
52
import subprocess
15 by Teddy Hogeborn
* mandos-clients.conf ([foo]): Uncommented.
53
import atexit
54
import stat
16 by Teddy Hogeborn
* Makefile: Include targets for all binaries.
55
import logging
56
import logging.handlers
163 by Teddy Hogeborn
* Makefile (PIDDIR, USER, GROUP): Removed.
57
import pwd
5 by Teddy Hogeborn
* server.py (server_metaclass): New.
58
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
59
import dbus
60
import gobject
61
import avahi
62
from dbus.mainloop.glib import DBusGMainLoop
12 by Teddy Hogeborn
* mandos-clients.conf ([foo]/dn, [foo]/password, [braxen_client]/dn,
63
import ctypes
215 by Teddy Hogeborn
* mandos: Remove unused "select" module. Import "ctypes.util".
64
import ctypes.util
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
65
57 by Teddy Hogeborn
* mandos (version): New variable.
66
version = "1.0"
13 by Björn Påhlsson
Added following support:
67
68
logger = logging.Logger('mandos')
15 by Teddy Hogeborn
* mandos-clients.conf ([foo]): Uncommented.
69
syslogger = logging.handlers.SysLogHandler\
52 by Teddy Hogeborn
* mandos: Make syslog use "/dev/log" instead of UDP to localhost.
70
            (facility = logging.handlers.SysLogHandler.LOG_DAEMON,
71
             address = "/dev/log")
15 by Teddy Hogeborn
* mandos-clients.conf ([foo]): Uncommented.
72
syslogger.setFormatter(logging.Formatter\
52 by Teddy Hogeborn
* mandos: Make syslog use "/dev/log" instead of UDP to localhost.
73
                        ('Mandos: %(levelname)s: %(message)s'))
15 by Teddy Hogeborn
* mandos-clients.conf ([foo]): Uncommented.
74
logger.addHandler(syslogger)
13 by Björn Påhlsson
Added following support:
75
61 by Teddy Hogeborn
* mandos (console): Define handler globally.
76
console = logging.StreamHandler()
77
console.setFormatter(logging.Formatter('%(name)s: %(levelname)s:'
78
                                       ' %(message)s'))
79
logger.addHandler(console)
28 by Teddy Hogeborn
* server.conf: New file.
80
81
class AvahiError(Exception):
82
    def __init__(self, value):
83
        self.value = value
215 by Teddy Hogeborn
* mandos: Remove unused "select" module. Import "ctypes.util".
84
        super(AvahiError, self).__init__()
28 by Teddy Hogeborn
* server.conf: New file.
85
    def __str__(self):
86
        return repr(self.value)
87
88
class AvahiServiceError(AvahiError):
89
    pass
90
91
class AvahiGroupError(AvahiError):
92
    pass
93
94
95
class AvahiService(object):
45 by Teddy Hogeborn
* server.py: Cosmetic changes.
96
    """An Avahi (Zeroconf) service.
97
    Attributes:
28 by Teddy Hogeborn
* server.conf: New file.
98
    interface: integer; avahi.IF_UNSPEC or an interface index.
99
               Used to optionally bind to the specified interface.
45 by Teddy Hogeborn
* server.py: Cosmetic changes.
100
    name: string; Example: 'Mandos'
101
    type: string; Example: '_mandos._tcp'.
102
                  See <http://www.dns-sd.org/ServiceTypes.html>
103
    port: integer; what port to announce
104
    TXT: list of strings; TXT record for the service
105
    domain: string; Domain to publish on, default to .local if empty.
106
    host: string; Host to publish records for, default is localhost
107
    max_renames: integer; maximum number of renames
108
    rename_count: integer; counter so we only rename after collisions
109
                  a sensible number of times
28 by Teddy Hogeborn
* server.conf: New file.
110
    """
111
    def __init__(self, interface = avahi.IF_UNSPEC, name = None,
215 by Teddy Hogeborn
* mandos: Remove unused "select" module. Import "ctypes.util".
112
                 servicetype = None, port = None, TXT = None, domain = "",
52 by Teddy Hogeborn
* mandos: Make syslog use "/dev/log" instead of UDP to localhost.
113
                 host = "", max_renames = 32768):
28 by Teddy Hogeborn
* server.conf: New file.
114
        self.interface = interface
115
        self.name = name
215 by Teddy Hogeborn
* mandos: Remove unused "select" module. Import "ctypes.util".
116
        self.type = servicetype
28 by Teddy Hogeborn
* server.conf: New file.
117
        self.port = port
118
        if TXT is None:
119
            self.TXT = []
120
        else:
121
            self.TXT = TXT
122
        self.domain = domain
123
        self.host = host
124
        self.rename_count = 0
76 by Teddy Hogeborn
* plugins.d/password-request.c (init_gnutls_global): Renamed
125
        self.max_renames = max_renames
28 by Teddy Hogeborn
* server.conf: New file.
126
    def rename(self):
127
        """Derived from the Avahi example code"""
128
        if self.rename_count >= self.max_renames:
109 by Teddy Hogeborn
* .bzrignore: New.
129
            logger.critical(u"No suitable Zeroconf service name found"
130
                            u" after %i retries, exiting.",
215 by Teddy Hogeborn
* mandos: Remove unused "select" module. Import "ctypes.util".
131
                            self.rename_count)
28 by Teddy Hogeborn
* server.conf: New file.
132
            raise AvahiServiceError("Too many renames")
76 by Teddy Hogeborn
* plugins.d/password-request.c (init_gnutls_global): Renamed
133
        self.name = server.GetAlternativeServiceName(self.name)
109 by Teddy Hogeborn
* .bzrignore: New.
134
        logger.info(u"Changing Zeroconf service name to %r ...",
135
                    str(self.name))
52 by Teddy Hogeborn
* mandos: Make syslog use "/dev/log" instead of UDP to localhost.
136
        syslogger.setFormatter(logging.Formatter\
137
                               ('Mandos (%s): %%(levelname)s:'
76 by Teddy Hogeborn
* plugins.d/password-request.c (init_gnutls_global): Renamed
138
                               ' %%(message)s' % self.name))
28 by Teddy Hogeborn
* server.conf: New file.
139
        self.remove()
140
        self.add()
141
        self.rename_count += 1
142
    def remove(self):
143
        """Derived from the Avahi example code"""
144
        if group is not None:
145
            group.Reset()
146
    def add(self):
147
        """Derived from the Avahi example code"""
148
        global group
149
        if group is None:
150
            group = dbus.Interface\
151
                    (bus.get_object(avahi.DBUS_NAME,
152
                                    server.EntryGroupNew()),
153
                     avahi.DBUS_INTERFACE_ENTRY_GROUP)
154
            group.connect_to_signal('StateChanged',
155
                                    entry_group_state_changed)
109 by Teddy Hogeborn
* .bzrignore: New.
156
        logger.debug(u"Adding Zeroconf service '%s' of type '%s' ...",
28 by Teddy Hogeborn
* server.conf: New file.
157
                     service.name, service.type)
158
        group.AddService(
159
                self.interface,         # interface
160
                avahi.PROTO_INET6,      # protocol
161
                dbus.UInt32(0),         # flags
162
                self.name, self.type,
163
                self.domain, self.host,
164
                dbus.UInt16(self.port),
165
                avahi.string_array_to_txt_array(self.TXT))
166
        group.Commit()
167
16 by Teddy Hogeborn
* Makefile: Include targets for all binaries.
168
# From the Avahi example code:
28 by Teddy Hogeborn
* server.conf: New file.
169
group = None                            # our entry group
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
170
# End of Avahi example code
171
172
3 by Björn Påhlsson
Python based server
173
class Client(object):
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
174
    """A representation of a client host served by this server.
175
    Attributes:
12 by Teddy Hogeborn
* mandos-clients.conf ([foo]/dn, [foo]/password, [braxen_client]/dn,
176
    name:      string; from the config file, used in log messages
177
    fingerprint: string (40 or 32 hexadecimal digits); used to
178
                 uniquely identify the client
179
    secret:    bytestring; sent verbatim (over TLS) to client
51 by Teddy Hogeborn
* clients.conf: Better comments.
180
    host:      string; available for use by the checker command
28 by Teddy Hogeborn
* server.conf: New file.
181
    created:   datetime.datetime(); object creation, not client host
182
    last_checked_ok: datetime.datetime() or None if not yet checked OK
183
    timeout:   datetime.timedelta(); How long from last_checked_ok
184
                                     until this client is invalid
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
185
    interval:  datetime.timedelta(); How often to start a new checker
186
    stop_hook: If set, called by stop() as stop_hook(self)
187
    checker:   subprocess.Popen(); a running checker process used
188
                                   to see if the client lives.
28 by Teddy Hogeborn
* server.conf: New file.
189
                                   'None' if no process is running.
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
190
    checker_initiator_tag: a gobject event source tag, or None
191
    stop_initiator_tag:    - '' -
192
    checker_callback_tag:  - '' -
12 by Teddy Hogeborn
* mandos-clients.conf ([foo]/dn, [foo]/password, [braxen_client]/dn,
193
    checker_command: string; External command which is run to check if
28 by Teddy Hogeborn
* server.conf: New file.
194
                     client lives.  %() expansions are done at
12 by Teddy Hogeborn
* mandos-clients.conf ([foo]/dn, [foo]/password, [braxen_client]/dn,
195
                     runtime with vars(self) as dict, so that for
196
                     instance %(name)s can be used in the command.
197
    Private attibutes:
198
    _timeout: Real variable for 'timeout'
199
    _interval: Real variable for 'interval'
28 by Teddy Hogeborn
* server.conf: New file.
200
    _timeout_milliseconds: Used when calling gobject.timeout_add()
12 by Teddy Hogeborn
* mandos-clients.conf ([foo]/dn, [foo]/password, [braxen_client]/dn,
201
    _interval_milliseconds: - '' -
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
202
    """
12 by Teddy Hogeborn
* mandos-clients.conf ([foo]/dn, [foo]/password, [braxen_client]/dn,
203
    def _set_timeout(self, timeout):
204
        "Setter function for 'timeout' attribute"
205
        self._timeout = timeout
206
        self._timeout_milliseconds = ((self.timeout.days
207
                                       * 24 * 60 * 60 * 1000)
208
                                      + (self.timeout.seconds * 1000)
209
                                      + (self.timeout.microseconds
210
                                         // 1000))
211
    timeout = property(lambda self: self._timeout,
212
                       _set_timeout)
213
    del _set_timeout
214
    def _set_interval(self, interval):
215
        "Setter function for 'interval' attribute"
216
        self._interval = interval
217
        self._interval_milliseconds = ((self.interval.days
218
                                        * 24 * 60 * 60 * 1000)
219
                                       + (self.interval.seconds
220
                                          * 1000)
221
                                       + (self.interval.microseconds
222
                                          // 1000))
223
    interval = property(lambda self: self._interval,
224
                        _set_interval)
225
    del _set_interval
215 by Teddy Hogeborn
* mandos: Remove unused "select" module. Import "ctypes.util".
226
    def __init__(self, name = None, stop_hook=None, config=None):
45 by Teddy Hogeborn
* server.py: Cosmetic changes.
227
        """Note: the 'checker' key in 'config' sets the
228
        'checker_command' attribute and *not* the 'checker'
229
        attribute."""
215 by Teddy Hogeborn
* mandos: Remove unused "select" module. Import "ctypes.util".
230
        if config is None:
231
            config = {}
3 by Björn Påhlsson
Python based server
232
        self.name = name
25 by Teddy Hogeborn
* mandos-clients.conf ([DEFAULT]): New section.
233
        logger.debug(u"Creating client %r", self.name)
45 by Teddy Hogeborn
* server.py: Cosmetic changes.
234
        # Uppercase and remove spaces from fingerprint for later
235
        # comparison purposes with return value from the fingerprint()
236
        # function
44 by Teddy Hogeborn
* ca.pem: Removed.
237
        self.fingerprint = config["fingerprint"].upper()\
238
                           .replace(u" ", u"")
25 by Teddy Hogeborn
* mandos-clients.conf ([DEFAULT]): New section.
239
        logger.debug(u"  Fingerprint: %s", self.fingerprint)
44 by Teddy Hogeborn
* ca.pem: Removed.
240
        if "secret" in config:
241
            self.secret = config["secret"].decode(u"base64")
242
        elif "secfile" in config:
223 by Teddy Hogeborn
* .bzrignore (plugins.d/askpass-fifo): Added.
243
            secfile = open(os.path.expanduser(os.path.expandvars
244
                                              (config["secfile"])))
215 by Teddy Hogeborn
* mandos: Remove unused "select" module. Import "ctypes.util".
245
            self.secret = secfile.read()
246
            secfile.close()
3 by Björn Påhlsson
Python based server
247
        else:
28 by Teddy Hogeborn
* server.conf: New file.
248
            raise TypeError(u"No secret or secfile for client %s"
249
                            % self.name)
51 by Teddy Hogeborn
* clients.conf: Better comments.
250
        self.host = config.get("host", "")
4 by Teddy Hogeborn
* server.py (Client.created, Client.next_check): New.
251
        self.created = datetime.datetime.now()
28 by Teddy Hogeborn
* server.conf: New file.
252
        self.last_checked_ok = None
44 by Teddy Hogeborn
* ca.pem: Removed.
253
        self.timeout = string_to_delta(config["timeout"])
254
        self.interval = string_to_delta(config["interval"])
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
255
        self.stop_hook = stop_hook
256
        self.checker = None
257
        self.checker_initiator_tag = None
258
        self.stop_initiator_tag = None
259
        self.checker_callback_tag = None
44 by Teddy Hogeborn
* ca.pem: Removed.
260
        self.check_command = config["checker"]
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
261
    def start(self):
16 by Teddy Hogeborn
* Makefile: Include targets for all binaries.
262
        """Start this client's checker and timeout hooks"""
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
263
        # Schedule a new checker to be started an 'interval' from now,
264
        # and every interval from then on.
12 by Teddy Hogeborn
* mandos-clients.conf ([foo]/dn, [foo]/password, [braxen_client]/dn,
265
        self.checker_initiator_tag = gobject.timeout_add\
266
                                     (self._interval_milliseconds,
267
                                      self.start_checker)
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
268
        # Also start a new checker *right now*.
269
        self.start_checker()
270
        # Schedule a stop() when 'timeout' has passed
12 by Teddy Hogeborn
* mandos-clients.conf ([foo]/dn, [foo]/password, [braxen_client]/dn,
271
        self.stop_initiator_tag = gobject.timeout_add\
272
                                  (self._timeout_milliseconds,
273
                                   self.stop)
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
274
    def stop(self):
275
        """Stop this client.
28 by Teddy Hogeborn
* server.conf: New file.
276
        The possibility that a client might be restarted is left open,
277
        but not currently used."""
16 by Teddy Hogeborn
* Makefile: Include targets for all binaries.
278
        # If this client doesn't have a secret, it is already stopped.
51 by Teddy Hogeborn
* clients.conf: Better comments.
279
        if hasattr(self, "secret") and self.secret:
44 by Teddy Hogeborn
* ca.pem: Removed.
280
            logger.info(u"Stopping client %s", self.name)
16 by Teddy Hogeborn
* Makefile: Include targets for all binaries.
281
            self.secret = None
282
        else:
283
            return False
28 by Teddy Hogeborn
* server.conf: New file.
284
        if getattr(self, "stop_initiator_tag", False):
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
285
            gobject.source_remove(self.stop_initiator_tag)
286
            self.stop_initiator_tag = None
28 by Teddy Hogeborn
* server.conf: New file.
287
        if getattr(self, "checker_initiator_tag", False):
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
288
            gobject.source_remove(self.checker_initiator_tag)
289
            self.checker_initiator_tag = None
290
        self.stop_checker()
291
        if self.stop_hook:
292
            self.stop_hook(self)
293
        # Do not run this again if called by a gobject.timeout_add
294
        return False
295
    def __del__(self):
16 by Teddy Hogeborn
* Makefile: Include targets for all binaries.
296
        self.stop_hook = None
297
        self.stop()
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
298
    def checker_callback(self, pid, condition):
299
        """The checker has completed, so take appropriate actions."""
10 by Teddy Hogeborn
* server.py: Bug fix: Do "from __future__ import division".
300
        now = datetime.datetime.now()
16 by Teddy Hogeborn
* Makefile: Include targets for all binaries.
301
        self.checker_callback_tag = None
302
        self.checker = None
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
303
        if os.WIFEXITED(condition) \
304
               and (os.WEXITSTATUS(condition) == 0):
44 by Teddy Hogeborn
* ca.pem: Removed.
305
            logger.info(u"Checker for %(name)s succeeded",
306
                        vars(self))
28 by Teddy Hogeborn
* server.conf: New file.
307
            self.last_checked_ok = now
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
308
            gobject.source_remove(self.stop_initiator_tag)
12 by Teddy Hogeborn
* mandos-clients.conf ([foo]/dn, [foo]/password, [braxen_client]/dn,
309
            self.stop_initiator_tag = gobject.timeout_add\
310
                                      (self._timeout_milliseconds,
311
                                       self.stop)
15 by Teddy Hogeborn
* mandos-clients.conf ([foo]): Uncommented.
312
        elif not os.WIFEXITED(condition):
13 by Björn Påhlsson
Added following support:
313
            logger.warning(u"Checker for %(name)s crashed?",
314
                           vars(self))
315
        else:
44 by Teddy Hogeborn
* ca.pem: Removed.
316
            logger.info(u"Checker for %(name)s failed",
317
                        vars(self))
9 by Teddy Hogeborn
* client.cpp (main): Get t_old early since it is used on error exits.
318
    def start_checker(self):
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
319
        """Start a new checker subprocess if one is not running.
320
        If a checker already exists, leave it running and do
321
        nothing."""
16 by Teddy Hogeborn
* Makefile: Include targets for all binaries.
322
        # The reason for not killing a running checker is that if we
323
        # did that, then if a checker (for some reason) started
324
        # running slowly and taking more than 'interval' time, the
325
        # client would inevitably timeout, since no checker would get
326
        # a chance to run to completion.  If we instead leave running
327
        # checkers alone, the checker would have to take more time
328
        # than 'timeout' for the client to be declared invalid, which
329
        # is as it should be.
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
330
        if self.checker is None:
12 by Teddy Hogeborn
* mandos-clients.conf ([foo]/dn, [foo]/password, [braxen_client]/dn,
331
            try:
28 by Teddy Hogeborn
* server.conf: New file.
332
                # In case check_command has exactly one % operator
51 by Teddy Hogeborn
* clients.conf: Better comments.
333
                command = self.check_command % self.host
12 by Teddy Hogeborn
* mandos-clients.conf ([foo]/dn, [foo]/password, [braxen_client]/dn,
334
            except TypeError:
28 by Teddy Hogeborn
* server.conf: New file.
335
                # Escape attributes for the shell
12 by Teddy Hogeborn
* mandos-clients.conf ([foo]/dn, [foo]/password, [braxen_client]/dn,
336
                escaped_attrs = dict((key, re.escape(str(val)))
337
                                     for key, val in
338
                                     vars(self).iteritems())
13 by Björn Påhlsson
Added following support:
339
                try:
340
                    command = self.check_command % escaped_attrs
341
                except TypeError, error:
28 by Teddy Hogeborn
* server.conf: New file.
342
                    logger.error(u'Could not format string "%s":'
343
                                 u' %s', self.check_command, error)
13 by Björn Påhlsson
Added following support:
344
                    return True # Try again later
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
345
            try:
44 by Teddy Hogeborn
* ca.pem: Removed.
346
                logger.info(u"Starting checker %r for %s",
347
                            command, self.name)
94 by Teddy Hogeborn
* clients.conf ([DEFAULT]/checker): Update to new default value.
348
                # We don't need to redirect stdout and stderr, since
349
                # in normal mode, that is already done by daemon(),
350
                # and in debug mode we don't want to.  (Stdin is
351
                # always replaced by /dev/null.)
28 by Teddy Hogeborn
* server.conf: New file.
352
                self.checker = subprocess.Popen(command,
353
                                                close_fds=True,
354
                                                shell=True, cwd="/")
15 by Teddy Hogeborn
* mandos-clients.conf ([foo]): Uncommented.
355
                self.checker_callback_tag = gobject.child_watch_add\
356
                                            (self.checker.pid,
357
                                             self.checker_callback)
94 by Teddy Hogeborn
* clients.conf ([DEFAULT]/checker): Update to new default value.
358
            except OSError, error:
13 by Björn Påhlsson
Added following support:
359
                logger.error(u"Failed to start subprocess: %s",
360
                             error)
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
361
        # Re-run this periodically if run by gobject.timeout_add
362
        return True
9 by Teddy Hogeborn
* client.cpp (main): Get t_old early since it is used on error exits.
363
    def stop_checker(self):
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
364
        """Force the checker process, if any, to stop."""
16 by Teddy Hogeborn
* Makefile: Include targets for all binaries.
365
        if self.checker_callback_tag:
366
            gobject.source_remove(self.checker_callback_tag)
367
            self.checker_callback_tag = None
28 by Teddy Hogeborn
* server.conf: New file.
368
        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.
369
            return
51 by Teddy Hogeborn
* clients.conf: Better comments.
370
        logger.debug(u"Stopping checker for %(name)s", vars(self))
16 by Teddy Hogeborn
* Makefile: Include targets for all binaries.
371
        try:
372
            os.kill(self.checker.pid, signal.SIGTERM)
373
            #os.sleep(0.5)
374
            #if self.checker.poll() is None:
375
            #    os.kill(self.checker.pid, signal.SIGKILL)
376
        except OSError, error:
28 by Teddy Hogeborn
* server.conf: New file.
377
            if error.errno != errno.ESRCH: # No such process
16 by Teddy Hogeborn
* Makefile: Include targets for all binaries.
378
                raise
9 by Teddy Hogeborn
* client.cpp (main): Get t_old early since it is used on error exits.
379
        self.checker = None
28 by Teddy Hogeborn
* server.conf: New file.
380
    def still_valid(self):
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
381
        """Has the timeout not yet passed for this client?"""
28 by Teddy Hogeborn
* server.conf: New file.
382
        now = datetime.datetime.now()
383
        if self.last_checked_ok is None:
10 by Teddy Hogeborn
* server.py: Bug fix: Do "from __future__ import division".
384
            return now < (self.created + self.timeout)
385
        else:
28 by Teddy Hogeborn
* server.conf: New file.
386
            return now < (self.last_checked_ok + self.timeout)
3 by Björn Påhlsson
Python based server
387
388
12 by Teddy Hogeborn
* mandos-clients.conf ([foo]/dn, [foo]/password, [braxen_client]/dn,
389
def peer_certificate(session):
16 by Teddy Hogeborn
* Makefile: Include targets for all binaries.
390
    "Return the peer's OpenPGP certificate as a bytestring"
12 by Teddy Hogeborn
* mandos-clients.conf ([foo]/dn, [foo]/password, [braxen_client]/dn,
391
    # If not an OpenPGP certificate...
392
    if gnutls.library.functions.gnutls_certificate_type_get\
393
            (session._c_object) \
394
           != gnutls.library.constants.GNUTLS_CRT_OPENPGP:
395
        # ...do the normal thing
396
        return session.peer_certificate
397
    list_size = ctypes.c_uint()
398
    cert_list = gnutls.library.functions.gnutls_certificate_get_peers\
399
        (session._c_object, ctypes.byref(list_size))
400
    if list_size.value == 0:
401
        return None
402
    cert = cert_list[0]
403
    return ctypes.string_at(cert.data, cert.size)
404
405
406
def fingerprint(openpgp):
16 by Teddy Hogeborn
* Makefile: Include targets for all binaries.
407
    "Convert an OpenPGP bytestring to a hexdigit fingerprint string"
12 by Teddy Hogeborn
* mandos-clients.conf ([foo]/dn, [foo]/password, [braxen_client]/dn,
408
    # New GnuTLS "datum" with the OpenPGP public key
409
    datum = gnutls.library.types.gnutls_datum_t\
410
        (ctypes.cast(ctypes.c_char_p(openpgp),
411
                     ctypes.POINTER(ctypes.c_ubyte)),
412
         ctypes.c_uint(len(openpgp)))
45 by Teddy Hogeborn
* server.py: Cosmetic changes.
413
    # New empty GnuTLS certificate
414
    crt = gnutls.library.types.gnutls_openpgp_crt_t()
415
    gnutls.library.functions.gnutls_openpgp_crt_init\
416
        (ctypes.byref(crt))
12 by Teddy Hogeborn
* mandos-clients.conf ([foo]/dn, [foo]/password, [braxen_client]/dn,
417
    # Import the OpenPGP public key into the certificate
45 by Teddy Hogeborn
* server.py: Cosmetic changes.
418
    gnutls.library.functions.gnutls_openpgp_crt_import\
419
                    (crt, ctypes.byref(datum),
420
                     gnutls.library.constants.GNUTLS_OPENPGP_FMT_RAW)
24.1.62 by Björn Påhlsson
merge + small bugfix
421
    # Verify the self signature in the key
215 by Teddy Hogeborn
* mandos: Remove unused "select" module. Import "ctypes.util".
422
    crtverify = ctypes.c_uint()
24.1.62 by Björn Påhlsson
merge + small bugfix
423
    gnutls.library.functions.gnutls_openpgp_crt_verify_self\
109 by Teddy Hogeborn
* .bzrignore: New.
424
        (crt, 0, ctypes.byref(crtverify))
99 by Teddy Hogeborn
* mandos (fingerprint): Bug fix: Check crtverify.value, not crtverify.
425
    if crtverify.value != 0:
24.1.62 by Björn Påhlsson
merge + small bugfix
426
        gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
427
        raise gnutls.errors.CertificateSecurityError("Verify failed")
12 by Teddy Hogeborn
* mandos-clients.conf ([foo]/dn, [foo]/password, [braxen_client]/dn,
428
    # New buffer for the fingerprint
215 by Teddy Hogeborn
* mandos: Remove unused "select" module. Import "ctypes.util".
429
    buf = ctypes.create_string_buffer(20)
430
    buf_len = ctypes.c_size_t()
12 by Teddy Hogeborn
* mandos-clients.conf ([foo]/dn, [foo]/password, [braxen_client]/dn,
431
    # Get the fingerprint from the certificate into the buffer
432
    gnutls.library.functions.gnutls_openpgp_crt_get_fingerprint\
215 by Teddy Hogeborn
* mandos: Remove unused "select" module. Import "ctypes.util".
433
        (crt, ctypes.byref(buf), ctypes.byref(buf_len))
12 by Teddy Hogeborn
* mandos-clients.conf ([foo]/dn, [foo]/password, [braxen_client]/dn,
434
    # Deinit the certificate
435
    gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
436
    # Convert the buffer to a Python bytestring
215 by Teddy Hogeborn
* mandos: Remove unused "select" module. Import "ctypes.util".
437
    fpr = ctypes.string_at(buf, buf_len.value)
12 by Teddy Hogeborn
* mandos-clients.conf ([foo]/dn, [foo]/password, [braxen_client]/dn,
438
    # Convert the bytestring to hexadecimal notation
439
    hex_fpr = u''.join(u"%02X" % ord(char) for char in fpr)
440
    return hex_fpr
441
442
215 by Teddy Hogeborn
* mandos: Remove unused "select" module. Import "ctypes.util".
443
class TCP_handler(SocketServer.BaseRequestHandler, object):
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
444
    """A TCP request handler class.
445
    Instantiated by IPv6_TCPServer for each request to handle it.
446
    Note: This will run in its own forked process."""
12 by Teddy Hogeborn
* mandos-clients.conf ([foo]/dn, [foo]/password, [braxen_client]/dn,
447
    
3 by Björn Påhlsson
Python based server
448
    def handle(self):
44 by Teddy Hogeborn
* ca.pem: Removed.
449
        logger.info(u"TCP connection from: %s",
13 by Björn Påhlsson
Added following support:
450
                     unicode(self.client_address))
41 by Teddy Hogeborn
Merge.
451
        session = gnutls.connection.ClientSession\
452
                  (self.request, gnutls.connection.X509Credentials())
453
        
24.1.12 by Björn Påhlsson
merge +
454
        line = self.request.makefile().readline()
455
        logger.debug(u"Protocol version: %r", line)
24.1.11 by Björn Påhlsson
Added support for protocol version handling
456
        try:
457
            if int(line.strip().split()[0]) > 1:
458
                raise RuntimeError
459
        except (ValueError, IndexError, RuntimeError), error:
460
            logger.error(u"Unknown protocol version: %s", error)
461
            return
462
        
28 by Teddy Hogeborn
* server.conf: New file.
463
        # Note: gnutls.connection.X509Credentials is really a generic
464
        # GnuTLS certificate credentials object so long as no X.509
465
        # keys are added to it.  Therefore, we can use it here despite
466
        # using OpenPGP certificates.
12 by Teddy Hogeborn
* mandos-clients.conf ([foo]/dn, [foo]/password, [braxen_client]/dn,
467
        
468
        #priority = ':'.join(("NONE", "+VERS-TLS1.1", "+AES-256-CBC",
469
        #                "+SHA1", "+COMP-NULL", "+CTYPE-OPENPGP",
470
        #                "+DHE-DSS"))
28 by Teddy Hogeborn
* server.conf: New file.
471
        priority = "NORMAL"             # Fallback default, since this
472
                                        # MUST be set.
473
        if self.server.settings["priority"]:
474
            priority = self.server.settings["priority"]
12 by Teddy Hogeborn
* mandos-clients.conf ([foo]/dn, [foo]/password, [braxen_client]/dn,
475
        gnutls.library.functions.gnutls_priority_set_direct\
215 by Teddy Hogeborn
* mandos: Remove unused "select" module. Import "ctypes.util".
476
            (session._c_object, priority, None)
12 by Teddy Hogeborn
* mandos-clients.conf ([foo]/dn, [foo]/password, [braxen_client]/dn,
477
        
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
478
        try:
479
            session.handshake()
480
        except gnutls.errors.GNUTLSError, error:
44 by Teddy Hogeborn
* ca.pem: Removed.
481
            logger.warning(u"Handshake failed: %s", error)
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
482
            # Do not run session.bye() here: the session is not
483
            # established.  Just abandon the request.
484
            return
3 by Björn Påhlsson
Python based server
485
        try:
12 by Teddy Hogeborn
* mandos-clients.conf ([foo]/dn, [foo]/password, [braxen_client]/dn,
486
            fpr = fingerprint(peer_certificate(session))
487
        except (TypeError, gnutls.errors.GNUTLSError), error:
44 by Teddy Hogeborn
* ca.pem: Removed.
488
            logger.warning(u"Bad certificate: %s", error)
3 by Björn Påhlsson
Python based server
489
            session.bye()
490
            return
13 by Björn Påhlsson
Added following support:
491
        logger.debug(u"Fingerprint: %s", fpr)
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
492
        client = None
16 by Teddy Hogeborn
* Makefile: Include targets for all binaries.
493
        for c in self.server.clients:
12 by Teddy Hogeborn
* mandos-clients.conf ([foo]/dn, [foo]/password, [braxen_client]/dn,
494
            if c.fingerprint == fpr:
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
495
                client = c
496
                break
28 by Teddy Hogeborn
* server.conf: New file.
497
        if not client:
44 by Teddy Hogeborn
* ca.pem: Removed.
498
            logger.warning(u"Client not found for fingerprint: %s",
499
                           fpr)
28 by Teddy Hogeborn
* server.conf: New file.
500
            session.bye()
501
            return
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
502
        # Have to check if client.still_valid(), since it is possible
503
        # that the client timed out while establishing the GnuTLS
504
        # session.
28 by Teddy Hogeborn
* server.conf: New file.
505
        if not client.still_valid():
44 by Teddy Hogeborn
* ca.pem: Removed.
506
            logger.warning(u"Client %(name)s is invalid",
507
                           vars(client))
12 by Teddy Hogeborn
* mandos-clients.conf ([foo]/dn, [foo]/password, [braxen_client]/dn,
508
            session.bye()
509
            return
510
        sent_size = 0
511
        while sent_size < len(client.secret):
512
            sent = session.send(client.secret[sent_size:])
13 by Björn Påhlsson
Added following support:
513
            logger.debug(u"Sent: %d, remaining: %d",
514
                         sent, len(client.secret)
515
                         - (sent_size + sent))
12 by Teddy Hogeborn
* mandos-clients.conf ([foo]/dn, [foo]/password, [braxen_client]/dn,
516
            sent_size += sent
3 by Björn Påhlsson
Python based server
517
        session.bye()
518
5 by Teddy Hogeborn
* server.py (server_metaclass): New.
519
3 by Björn Påhlsson
Python based server
520
class IPv6_TCPServer(SocketServer.ForkingTCPServer, object):
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
521
    """IPv6 TCP server.  Accepts 'None' as address and/or port.
522
    Attributes:
28 by Teddy Hogeborn
* server.conf: New file.
523
        settings:       Server settings
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
524
        clients:        Set() of Client objects
163 by Teddy Hogeborn
* Makefile (PIDDIR, USER, GROUP): Removed.
525
        enabled:        Boolean; whether this server is activated yet
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
526
    """
527
    address_family = socket.AF_INET6
528
    def __init__(self, *args, **kwargs):
28 by Teddy Hogeborn
* server.conf: New file.
529
        if "settings" in kwargs:
530
            self.settings = kwargs["settings"]
531
            del kwargs["settings"]
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
532
        if "clients" in kwargs:
533
            self.clients = kwargs["clients"]
534
            del kwargs["clients"]
163 by Teddy Hogeborn
* Makefile (PIDDIR, USER, GROUP): Removed.
535
        self.enabled = False
215 by Teddy Hogeborn
* mandos: Remove unused "select" module. Import "ctypes.util".
536
        super(IPv6_TCPServer, self).__init__(*args, **kwargs)
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
537
    def server_bind(self):
538
        """This overrides the normal server_bind() function
539
        to bind to an interface if one was specified, and also NOT to
540
        bind to an address or port if they were not specified."""
29 by Teddy Hogeborn
* plugins.d/mandosclient.c (start_mandos_communication): Changed
541
        if self.settings["interface"]:
28 by Teddy Hogeborn
* server.conf: New file.
542
            # 25 is from /usr/include/asm-i486/socket.h
543
            SO_BINDTODEVICE = getattr(socket, "SO_BINDTODEVICE", 25)
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
544
            try:
545
                self.socket.setsockopt(socket.SOL_SOCKET,
28 by Teddy Hogeborn
* server.conf: New file.
546
                                       SO_BINDTODEVICE,
547
                                       self.settings["interface"])
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
548
            except socket.error, error:
549
                if error[0] == errno.EPERM:
44 by Teddy Hogeborn
* ca.pem: Removed.
550
                    logger.error(u"No permission to"
551
                                 u" bind to interface %s",
552
                                 self.settings["interface"])
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
553
                else:
554
                    raise error
555
        # Only bind(2) the socket if we really need to.
556
        if self.server_address[0] or self.server_address[1]:
557
            if not self.server_address[0]:
558
                in6addr_any = "::"
559
                self.server_address = (in6addr_any,
560
                                       self.server_address[1])
49 by Teddy Hogeborn
* mandos (IPv6_TCPServer.server_bind): Bug fix: allow port to be empty
561
            elif not self.server_address[1]:
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
562
                self.server_address = (self.server_address[0],
563
                                       0)
49 by Teddy Hogeborn
* mandos (IPv6_TCPServer.server_bind): Bug fix: allow port to be empty
564
#                 if self.settings["interface"]:
565
#                     self.server_address = (self.server_address[0],
566
#                                            0, # port
567
#                                            0, # flowinfo
568
#                                            if_nametoindex
569
#                                            (self.settings
570
#                                             ["interface"]))
215 by Teddy Hogeborn
* mandos: Remove unused "select" module. Import "ctypes.util".
571
            return super(IPv6_TCPServer, self).server_bind()
163 by Teddy Hogeborn
* Makefile (PIDDIR, USER, GROUP): Removed.
572
    def server_activate(self):
573
        if self.enabled:
215 by Teddy Hogeborn
* mandos: Remove unused "select" module. Import "ctypes.util".
574
            return super(IPv6_TCPServer, self).server_activate()
163 by Teddy Hogeborn
* Makefile (PIDDIR, USER, GROUP): Removed.
575
    def enable(self):
576
        self.enabled = True
10 by Teddy Hogeborn
* server.py: Bug fix: Do "from __future__ import division".
577
3 by Björn Påhlsson
Python based server
578
4 by Teddy Hogeborn
* server.py (Client.created, Client.next_check): New.
579
def string_to_delta(interval):
580
    """Parse a string and return a datetime.timedelta
581
582
    >>> string_to_delta('7d')
583
    datetime.timedelta(7)
584
    >>> string_to_delta('60s')
585
    datetime.timedelta(0, 60)
586
    >>> string_to_delta('60m')
587
    datetime.timedelta(0, 3600)
588
    >>> string_to_delta('24h')
589
    datetime.timedelta(1)
590
    >>> string_to_delta(u'1w')
591
    datetime.timedelta(7)
93 by Teddy Hogeborn
* mandos (string_to_delta): Accept a whitespace-separated sequence of
592
    >>> string_to_delta('5m 30s')
593
    datetime.timedelta(0, 330)
4 by Teddy Hogeborn
* server.py (Client.created, Client.next_check): New.
594
    """
93 by Teddy Hogeborn
* mandos (string_to_delta): Accept a whitespace-separated sequence of
595
    timevalue = datetime.timedelta(0)
596
    for s in interval.split():
597
        try:
215 by Teddy Hogeborn
* mandos: Remove unused "select" module. Import "ctypes.util".
598
            suffix = unicode(s[-1])
599
            value = int(s[:-1])
93 by Teddy Hogeborn
* mandos (string_to_delta): Accept a whitespace-separated sequence of
600
            if suffix == u"d":
601
                delta = datetime.timedelta(value)
602
            elif suffix == u"s":
603
                delta = datetime.timedelta(0, value)
604
            elif suffix == u"m":
605
                delta = datetime.timedelta(0, 0, 0, 0, value)
606
            elif suffix == u"h":
607
                delta = datetime.timedelta(0, 0, 0, 0, 0, value)
608
            elif suffix == u"w":
609
                delta = datetime.timedelta(0, 0, 0, 0, 0, 0, value)
610
            else:
611
                raise ValueError
612
        except (ValueError, IndexError):
4 by Teddy Hogeborn
* server.py (Client.created, Client.next_check): New.
613
            raise ValueError
93 by Teddy Hogeborn
* mandos (string_to_delta): Accept a whitespace-separated sequence of
614
        timevalue += delta
615
    return timevalue
4 by Teddy Hogeborn
* server.py (Client.created, Client.next_check): New.
616
8 by Teddy Hogeborn
* Makefile (client_debug): Bug fix; add quotes and / to CERT_ROOT.
617
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
618
def server_state_changed(state):
16 by Teddy Hogeborn
* Makefile: Include targets for all binaries.
619
    """Derived from the Avahi example code"""
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
620
    if state == avahi.SERVER_COLLISION:
109 by Teddy Hogeborn
* .bzrignore: New.
621
        logger.error(u"Zeroconf server name collision")
28 by Teddy Hogeborn
* server.conf: New file.
622
        service.remove()
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
623
    elif state == avahi.SERVER_RUNNING:
28 by Teddy Hogeborn
* server.conf: New file.
624
        service.add()
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
625
626
627
def entry_group_state_changed(state, error):
16 by Teddy Hogeborn
* Makefile: Include targets for all binaries.
628
    """Derived from the Avahi example code"""
109 by Teddy Hogeborn
* .bzrignore: New.
629
    logger.debug(u"Avahi state change: %i", state)
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
630
    
631
    if state == avahi.ENTRY_GROUP_ESTABLISHED:
109 by Teddy Hogeborn
* .bzrignore: New.
632
        logger.debug(u"Zeroconf service established.")
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
633
    elif state == avahi.ENTRY_GROUP_COLLISION:
109 by Teddy Hogeborn
* .bzrignore: New.
634
        logger.warning(u"Zeroconf service name collision.")
28 by Teddy Hogeborn
* server.conf: New file.
635
        service.rename()
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
636
    elif state == avahi.ENTRY_GROUP_FAILURE:
109 by Teddy Hogeborn
* .bzrignore: New.
637
        logger.critical(u"Avahi: Error in group state changed %s",
28 by Teddy Hogeborn
* server.conf: New file.
638
                        unicode(error))
639
        raise AvahiGroupError("State changed: %s", str(error))
640
24.1.13 by Björn Påhlsson
mandosclient
641
def if_nametoindex(interface):
28 by Teddy Hogeborn
* server.conf: New file.
642
    """Call the C function if_nametoindex(), or equivalent"""
24.1.13 by Björn Påhlsson
mandosclient
643
    global if_nametoindex
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
644
    try:
24.1.13 by Björn Påhlsson
mandosclient
645
        if_nametoindex = ctypes.cdll.LoadLibrary\
646
            (ctypes.util.find_library("c")).if_nametoindex
12 by Teddy Hogeborn
* mandos-clients.conf ([foo]/dn, [foo]/password, [braxen_client]/dn,
647
    except (OSError, AttributeError):
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
648
        if "struct" not in sys.modules:
649
            import struct
650
        if "fcntl" not in sys.modules:
651
            import fcntl
24.1.13 by Björn Påhlsson
mandosclient
652
        def if_nametoindex(interface):
28 by Teddy Hogeborn
* server.conf: New file.
653
            "Get an interface index the hard way, i.e. using fcntl()"
654
            SIOCGIFINDEX = 0x8933  # From /usr/include/linux/sockios.h
655
            s = socket.socket()
656
            ifreq = fcntl.ioctl(s, SIOCGIFINDEX,
657
                                struct.pack("16s16x", interface))
658
            s.close()
659
            interface_index = struct.unpack("I", ifreq[16:20])[0]
660
            return interface_index
24.1.13 by Björn Påhlsson
mandosclient
661
    return if_nametoindex(interface)
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
662
663
47 by Teddy Hogeborn
* plugbasedclient.c: Renamed to "mandos-client.c". All users changed.
664
def daemon(nochdir = False, noclose = False):
15 by Teddy Hogeborn
* mandos-clients.conf ([foo]): Uncommented.
665
    """See daemon(3).  Standard BSD Unix function.
666
    This should really exist as os.daemon, but it doesn't (yet)."""
667
    if os.fork():
668
        sys.exit()
669
    os.setsid()
670
    if not nochdir:
671
        os.chdir("/")
46 by Teddy Hogeborn
* network-protocol.txt: New.
672
    if os.fork():
673
        sys.exit()
15 by Teddy Hogeborn
* mandos-clients.conf ([foo]): Uncommented.
674
    if not noclose:
675
        # Close all standard open file descriptors
28 by Teddy Hogeborn
* server.conf: New file.
676
        null = os.open(os.path.devnull, os.O_NOCTTY | os.O_RDWR)
15 by Teddy Hogeborn
* mandos-clients.conf ([foo]): Uncommented.
677
        if not stat.S_ISCHR(os.fstat(null).st_mode):
678
            raise OSError(errno.ENODEV,
679
                          "/dev/null not a character device")
680
        os.dup2(null, sys.stdin.fileno())
681
        os.dup2(null, sys.stdout.fileno())
682
        os.dup2(null, sys.stderr.fileno())
683
        if null > 2:
684
            os.close(null)
685
686
16 by Teddy Hogeborn
* Makefile: Include targets for all binaries.
687
def main():
59 by Teddy Hogeborn
* mandos (main): Use program name in --version output.
688
    parser = OptionParser(version = "%%prog %s" % version)
3 by Björn Påhlsson
Python based server
689
    parser.add_option("-i", "--interface", type="string",
28 by Teddy Hogeborn
* server.conf: New file.
690
                      metavar="IF", help="Bind to interface IF")
691
    parser.add_option("-a", "--address", type="string",
16 by Teddy Hogeborn
* Makefile: Include targets for all binaries.
692
                      help="Address to listen for requests on")
28 by Teddy Hogeborn
* server.conf: New file.
693
    parser.add_option("-p", "--port", type="int",
3 by Björn Påhlsson
Python based server
694
                      help="Port number to receive requests on")
4 by Teddy Hogeborn
* server.py (Client.created, Client.next_check): New.
695
    parser.add_option("--check", action="store_true", default=False,
696
                      help="Run self-test")
49 by Teddy Hogeborn
* mandos (IPv6_TCPServer.server_bind): Bug fix: allow port to be empty
697
    parser.add_option("--debug", action="store_true",
28 by Teddy Hogeborn
* server.conf: New file.
698
                      help="Debug mode; run in foreground and log to"
699
                      " terminal")
700
    parser.add_option("--priority", type="string", help="GnuTLS"
701
                      " priority string (see GnuTLS documentation)")
702
    parser.add_option("--servicename", type="string", metavar="NAME",
703
                      help="Zeroconf service name")
704
    parser.add_option("--configdir", type="string",
705
                      default="/etc/mandos", metavar="DIR",
706
                      help="Directory to search for configuration"
707
                      " files")
215 by Teddy Hogeborn
* mandos: Remove unused "select" module. Import "ctypes.util".
708
    options = parser.parse_args()[0]
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
709
    
4 by Teddy Hogeborn
* server.py (Client.created, Client.next_check): New.
710
    if options.check:
711
        import doctest
712
        doctest.testmod()
713
        sys.exit()
3 by Björn Påhlsson
Python based server
714
    
28 by Teddy Hogeborn
* server.conf: New file.
715
    # Default values for config file for server-global settings
716
    server_defaults = { "interface": "",
717
                        "address": "",
718
                        "port": "",
719
                        "debug": "False",
720
                        "priority":
721
                        "SECURE256:!CTYPE-X.509:+CTYPE-OPENPGP",
722
                        "servicename": "Mandos",
723
                        }
724
    
725
    # Parse config file for server-global settings
726
    server_config = ConfigParser.SafeConfigParser(server_defaults)
727
    del server_defaults
47 by Teddy Hogeborn
* plugbasedclient.c: Renamed to "mandos-client.c". All users changed.
728
    server_config.read(os.path.join(options.configdir, "mandos.conf"))
28 by Teddy Hogeborn
* server.conf: New file.
729
    # Convert the SafeConfigParser object to a dict
89 by Teddy Hogeborn
* Makefile: Bug fix: fixed creation of man pages for section 5 pages.
730
    server_settings = server_config.defaults()
28 by Teddy Hogeborn
* server.conf: New file.
731
    # Use getboolean on the boolean config option
732
    server_settings["debug"] = server_config.getboolean\
89 by Teddy Hogeborn
* Makefile: Bug fix: fixed creation of man pages for section 5 pages.
733
                               ("DEFAULT", "debug")
28 by Teddy Hogeborn
* server.conf: New file.
734
    del server_config
735
    
736
    # Override the settings from the config file with command line
737
    # options, if set.
738
    for option in ("interface", "address", "port", "debug",
739
                   "priority", "servicename", "configdir"):
740
        value = getattr(options, option)
741
        if value is not None:
742
            server_settings[option] = value
743
    del options
744
    # Now we have our good server settings in "server_settings"
745
    
52 by Teddy Hogeborn
* mandos: Make syslog use "/dev/log" instead of UDP to localhost.
746
    debug = server_settings["debug"]
747
    
748
    if not debug:
749
        syslogger.setLevel(logging.WARNING)
61 by Teddy Hogeborn
* mandos (console): Define handler globally.
750
        console.setLevel(logging.WARNING)
52 by Teddy Hogeborn
* mandos: Make syslog use "/dev/log" instead of UDP to localhost.
751
    
752
    if server_settings["servicename"] != "Mandos":
753
        syslogger.setFormatter(logging.Formatter\
754
                               ('Mandos (%s): %%(levelname)s:'
755
                                ' %%(message)s'
756
                                % server_settings["servicename"]))
757
    
28 by Teddy Hogeborn
* server.conf: New file.
758
    # Parse config file with clients
759
    client_defaults = { "timeout": "1h",
760
                        "interval": "5m",
94 by Teddy Hogeborn
* clients.conf ([DEFAULT]/checker): Update to new default value.
761
                        "checker": "fping -q -- %(host)s",
93 by Teddy Hogeborn
* mandos (string_to_delta): Accept a whitespace-separated sequence of
762
                        "host": "",
28 by Teddy Hogeborn
* server.conf: New file.
763
                        }
764
    client_config = ConfigParser.SafeConfigParser(client_defaults)
765
    client_config.read(os.path.join(server_settings["configdir"],
766
                                    "clients.conf"))
767
    
163 by Teddy Hogeborn
* Makefile (PIDDIR, USER, GROUP): Removed.
768
    clients = Set()
769
    tcp_server = IPv6_TCPServer((server_settings["address"],
770
                                 server_settings["port"]),
215 by Teddy Hogeborn
* mandos: Remove unused "select" module. Import "ctypes.util".
771
                                TCP_handler,
163 by Teddy Hogeborn
* Makefile (PIDDIR, USER, GROUP): Removed.
772
                                settings=server_settings,
773
                                clients=clients)
164 by Teddy Hogeborn
* mandos: Open the PID file before daemonizing, but write to it
774
    pidfilename = "/var/run/mandos.pid"
775
    try:
776
        pidfile = open(pidfilename, "w")
777
    except IOError, error:
778
        logger.error("Could not open file %r", pidfilename)
779
    
163 by Teddy Hogeborn
* Makefile (PIDDIR, USER, GROUP): Removed.
780
    uid = 65534
781
    gid = 65534
782
    try:
783
        uid = pwd.getpwnam("mandos").pw_uid
784
    except KeyError:
785
        try:
786
            uid = pwd.getpwnam("nobody").pw_uid
787
        except KeyError:
788
            pass
789
    try:
790
        gid = pwd.getpwnam("mandos").pw_gid
791
    except KeyError:
792
        try:
793
            gid = pwd.getpwnam("nogroup").pw_gid
794
        except KeyError:
795
            pass
796
    try:
797
        os.setuid(uid)
798
        os.setgid(gid)
799
    except OSError, error:
800
        if error[0] != errno.EPERM:
801
            raise error
164 by Teddy Hogeborn
* mandos: Open the PID file before daemonizing, but write to it
802
    
28 by Teddy Hogeborn
* server.conf: New file.
803
    global service
804
    service = AvahiService(name = server_settings["servicename"],
215 by Teddy Hogeborn
* mandos: Remove unused "select" module. Import "ctypes.util".
805
                           servicetype = "_mandos._tcp", )
29 by Teddy Hogeborn
* plugins.d/mandosclient.c (start_mandos_communication): Changed
806
    if server_settings["interface"]:
109 by Teddy Hogeborn
* .bzrignore: New.
807
        service.interface = if_nametoindex\
808
                            (server_settings["interface"])
25 by Teddy Hogeborn
* mandos-clients.conf ([DEFAULT]): New section.
809
    
16 by Teddy Hogeborn
* Makefile: Include targets for all binaries.
810
    global main_loop
811
    global bus
812
    global server
813
    # From the Avahi example code
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
814
    DBusGMainLoop(set_as_default=True )
815
    main_loop = gobject.MainLoop()
816
    bus = dbus.SystemBus()
109 by Teddy Hogeborn
* .bzrignore: New.
817
    server = dbus.Interface(bus.get_object(avahi.DBUS_NAME,
818
                                           avahi.DBUS_PATH_SERVER),
819
                            avahi.DBUS_INTERFACE_SERVER)
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
820
    # End of Avahi example code
821
    
822
    def remove_from_clients(client):
823
        clients.remove(client)
824
        if not clients:
44 by Teddy Hogeborn
* ca.pem: Removed.
825
            logger.critical(u"No clients left, exiting")
28 by Teddy Hogeborn
* server.conf: New file.
826
            sys.exit()
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
827
    
44 by Teddy Hogeborn
* ca.pem: Removed.
828
    clients.update(Set(Client(name = section,
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
829
                              stop_hook = remove_from_clients,
44 by Teddy Hogeborn
* ca.pem: Removed.
830
                              config
831
                              = dict(client_config.items(section)))
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
832
                       for section in client_config.sections()))
51 by Teddy Hogeborn
* clients.conf: Better comments.
833
    if not clients:
834
        logger.critical(u"No clients defined")
835
        sys.exit(1)
15 by Teddy Hogeborn
* mandos-clients.conf ([foo]): Uncommented.
836
    
94 by Teddy Hogeborn
* clients.conf ([DEFAULT]/checker): Update to new default value.
837
    if debug:
838
        # Redirect stdin so all checkers get /dev/null
839
        null = os.open(os.path.devnull, os.O_NOCTTY | os.O_RDWR)
840
        os.dup2(null, sys.stdin.fileno())
841
        if null > 2:
842
            os.close(null)
843
    else:
844
        # No console logging
61 by Teddy Hogeborn
* mandos (console): Define handler globally.
845
        logger.removeHandler(console)
94 by Teddy Hogeborn
* clients.conf ([DEFAULT]/checker): Update to new default value.
846
        # Close all input and output, do double fork, etc.
47 by Teddy Hogeborn
* plugbasedclient.c: Renamed to "mandos-client.c". All users changed.
847
        daemon()
51 by Teddy Hogeborn
* clients.conf: Better comments.
848
    
165 by Teddy Hogeborn
* mandos (main): Use EAFP with pidfile.
849
    try:
164 by Teddy Hogeborn
* mandos: Open the PID file before daemonizing, but write to it
850
        pid = os.getpid()
165 by Teddy Hogeborn
* mandos (main): Use EAFP with pidfile.
851
        pidfile.write(str(pid) + "\n")
852
        pidfile.close()
853
        del pidfile
215 by Teddy Hogeborn
* mandos: Remove unused "select" module. Import "ctypes.util".
854
    except IOError:
165 by Teddy Hogeborn
* mandos (main): Use EAFP with pidfile.
855
        logger.error(u"Could not write to file %r with PID %d",
856
                     pidfilename, pid)
857
    except NameError:
858
        # "pidfile" was never created
859
        pass
164 by Teddy Hogeborn
* mandos: Open the PID file before daemonizing, but write to it
860
    del pidfilename
15 by Teddy Hogeborn
* mandos-clients.conf ([foo]): Uncommented.
861
    
862
    def cleanup():
863
        "Cleanup function; run on exit"
864
        global group
16 by Teddy Hogeborn
* Makefile: Include targets for all binaries.
865
        # From the Avahi example code
15 by Teddy Hogeborn
* mandos-clients.conf ([foo]): Uncommented.
866
        if not group is None:
867
            group.Free()
868
            group = None
869
        # End of Avahi example code
870
        
16 by Teddy Hogeborn
* Makefile: Include targets for all binaries.
871
        while clients:
872
            client = clients.pop()
15 by Teddy Hogeborn
* mandos-clients.conf ([foo]): Uncommented.
873
            client.stop_hook = None
874
            client.stop()
875
    
876
    atexit.register(cleanup)
877
    
878
    if not debug:
879
        signal.signal(signal.SIGINT, signal.SIG_IGN)
28 by Teddy Hogeborn
* server.conf: New file.
880
    signal.signal(signal.SIGHUP, lambda signum, frame: sys.exit())
881
    signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit())
15 by Teddy Hogeborn
* mandos-clients.conf ([foo]): Uncommented.
882
    
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
883
    for client in clients:
884
        client.start()
885
    
163 by Teddy Hogeborn
* Makefile (PIDDIR, USER, GROUP): Removed.
886
    tcp_server.enable()
887
    tcp_server.server_activate()
888
    
28 by Teddy Hogeborn
* server.conf: New file.
889
    # Find out what port we got
890
    service.port = tcp_server.socket.getsockname()[1]
44 by Teddy Hogeborn
* ca.pem: Removed.
891
    logger.info(u"Now listening on address %r, port %d, flowinfo %d,"
892
                u" scope_id %d" % tcp_server.socket.getsockname())
28 by Teddy Hogeborn
* server.conf: New file.
893
    
29 by Teddy Hogeborn
* plugins.d/mandosclient.c (start_mandos_communication): Changed
894
    #service.interface = tcp_server.socket.getsockname()[3]
28 by Teddy Hogeborn
* server.conf: New file.
895
    
896
    try:
897
        # From the Avahi example code
898
        server.connect_to_signal("StateChanged", server_state_changed)
899
        try:
900
            server_state_changed(server.GetState())
901
        except dbus.exceptions.DBusException, error:
902
            logger.critical(u"DBusException: %s", error)
903
            sys.exit(1)
904
        # End of Avahi example code
905
        
906
        gobject.io_add_watch(tcp_server.fileno(), gobject.IO_IN,
907
                             lambda *args, **kwargs:
908
                             tcp_server.handle_request\
909
                             (*args[2:], **kwargs) or True)
910
        
51 by Teddy Hogeborn
* clients.conf: Better comments.
911
        logger.debug(u"Starting main loop")
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
912
        main_loop.run()
28 by Teddy Hogeborn
* server.conf: New file.
913
    except AvahiError, error:
914
        logger.critical(u"AvahiError: %s" + unicode(error))
915
        sys.exit(1)
11 by Teddy Hogeborn
* server.py: Rewritten to use Zeroconf (mDNS/DNS-SD) in place of the
916
    except KeyboardInterrupt:
15 by Teddy Hogeborn
* mandos-clients.conf ([foo]): Uncommented.
917
        if debug:
918
            print
16 by Teddy Hogeborn
* Makefile: Include targets for all binaries.
919
920
if __name__ == '__main__':
921
    main()