56
44
class Client(object):
57
45
"""A representation of a client host served by this server.
59
name: string; from the config file, used in log messages
60
fingerprint: string (40 or 32 hexadecimal digits); used to
61
uniquely identify the client
62
secret: bytestring; sent verbatim (over TLS) to client
63
fqdn: string (FQDN); available for use by the checker command
48
fqdn: string, FQDN (used by the checker)
64
49
created: datetime.datetime()
65
50
last_seen: datetime.datetime() or None if not yet seen
66
51
timeout: datetime.timedelta(); How long from last_seen until
67
52
this client is invalid
68
53
interval: datetime.timedelta(); How often to start a new checker
54
timeout_milliseconds: Used by gobject.timeout_add()
55
interval_milliseconds: - '' -
69
56
stop_hook: If set, called by stop() as stop_hook(self)
70
57
checker: subprocess.Popen(); a running checker process used
71
58
to see if the client lives.
73
60
checker_initiator_tag: a gobject event source tag, or None
74
61
stop_initiator_tag: - '' -
75
62
checker_callback_tag: - '' -
76
checker_command: string; External command which is run to check if
77
client lives. %()s expansions are done at
78
runtime with vars(self) as dict, so that for
79
instance %(name)s can be used in the command.
81
_timeout: Real variable for 'timeout'
82
_interval: Real variable for 'interval'
83
_timeout_milliseconds: Used by gobject.timeout_add()
84
_interval_milliseconds: - '' -
86
def _set_timeout(self, timeout):
87
"Setter function for 'timeout' attribute"
88
self._timeout = timeout
89
self._timeout_milliseconds = ((self.timeout.days
90
* 24 * 60 * 60 * 1000)
91
+ (self.timeout.seconds * 1000)
92
+ (self.timeout.microseconds
94
timeout = property(lambda self: self._timeout,
97
def _set_interval(self, interval):
98
"Setter function for 'interval' attribute"
99
self._interval = interval
100
self._interval_milliseconds = ((self.interval.days
101
* 24 * 60 * 60 * 1000)
102
+ (self.interval.seconds
104
+ (self.interval.microseconds
106
interval = property(lambda self: self._interval,
109
64
def __init__(self, name=None, options=None, stop_hook=None,
110
fingerprint=None, secret=None, secfile=None, fqdn=None,
111
timeout=None, interval=-1, checker=None):
65
dn=None, password=None, passfile=None, fqdn=None,
66
timeout=None, interval=-1):
113
# Uppercase and remove spaces from fingerprint
114
# for later comparison purposes with return value of
115
# the fingerprint() function
116
self.fingerprint = fingerprint.upper().replace(u" ", u"")
118
self.secret = secret.decode(u"base64")
121
self.secret = sf.read()
70
self.password = password
72
self.password = open(passfile).readall()
124
raise RuntimeError(u"No secret or secfile for client %s"
74
raise RuntimeError(u"No Password or Passfile for client %s"
126
76
self.fqdn = fqdn # string
127
77
self.created = datetime.datetime.now()
129
79
if timeout is None:
130
80
timeout = options.timeout
131
81
self.timeout = timeout
82
self.timeout_milliseconds = ((self.timeout.days
83
* 24 * 60 * 60 * 1000)
84
+ (self.timeout.seconds * 1000)
85
+ (self.timeout.microseconds
132
87
if interval == -1:
133
88
interval = options.interval
135
90
interval = string_to_delta(interval)
136
91
self.interval = interval
92
self.interval_milliseconds = ((self.interval.days
93
* 24 * 60 * 60 * 1000)
94
+ (self.interval.seconds * 1000)
95
+ (self.interval.microseconds
137
97
self.stop_hook = stop_hook
138
98
self.checker = None
139
99
self.checker_initiator_tag = None
140
100
self.stop_initiator_tag = None
141
101
self.checker_callback_tag = None
142
self.check_command = checker
144
103
"""Start this clients checker and timeout hooks"""
145
104
# Schedule a new checker to be started an 'interval' from now,
146
105
# and every interval from then on.
147
self.checker_initiator_tag = gobject.timeout_add\
148
(self._interval_milliseconds,
106
self.checker_initiator_tag = gobject.\
107
timeout_add(self.interval_milliseconds,
150
109
# Also start a new checker *right now*.
151
110
self.start_checker()
152
111
# Schedule a stop() when 'timeout' has passed
153
self.stop_initiator_tag = gobject.timeout_add\
154
(self._timeout_milliseconds,
112
self.stop_initiator_tag = gobject.\
113
timeout_add(self.timeout_milliseconds,
157
116
"""Stop this client.
158
117
The possibility that this client might be restarted is left
159
118
open, but not currently used."""
160
logger.debug(u"Stopping client %s", self.name)
119
# print "Stopping client", self.name
162
121
if self.stop_initiator_tag:
163
122
gobject.source_remove(self.stop_initiator_tag)
164
123
self.stop_initiator_tag = None
186
145
now = datetime.datetime.now()
187
146
if os.WIFEXITED(condition) \
188
147
and (os.WEXITSTATUS(condition) == 0):
189
logger.debug(u"Checker for %(name)s succeeded",
148
#print "Checker for %(name)s succeeded" % vars(self)
191
149
self.last_seen = now
192
150
gobject.source_remove(self.stop_initiator_tag)
193
self.stop_initiator_tag = gobject.timeout_add\
194
(self._timeout_milliseconds,
196
if not os.WIFEXITED(condition):
197
logger.warning(u"Checker for %(name)s crashed?",
200
logger.debug(u"Checker for %(name)s failed",
151
self.stop_initiator_tag = gobject.\
152
timeout_add(self.timeout_milliseconds,
155
# if not os.WIFEXITED(condition):
156
# print "Checker for %(name)s crashed?" % vars(self)
158
# print "Checker for %(name)s failed" % vars(self)
203
160
self.checker_callback_tag = None
204
161
def start_checker(self):
205
162
"""Start a new checker subprocess if one is not running.
206
163
If a checker already exists, leave it running and do
208
165
if self.checker is None:
209
logger.debug(u"Starting checker for %s",
212
command = self.check_command % self.fqdn
214
escaped_attrs = dict((key, re.escape(str(val)))
216
vars(self).iteritems())
218
command = self.check_command % escaped_attrs
219
except TypeError, error:
220
logger.critical(u'Could not format string "%s": %s',
221
self.check_command, error)
222
return True # Try again later
166
#print "Starting checker for", self.name
224
168
self.checker = subprocess.\
169
Popen("sleep 1; fping -q -- %s"
170
% re.escape(self.fqdn),
226
171
stdout=subprocess.PIPE,
227
172
close_fds=True, shell=True,
255
200
return now < (self.last_seen + self.timeout)
258
def peer_certificate(session):
259
# If not an OpenPGP certificate...
260
if gnutls.library.functions.gnutls_certificate_type_get\
261
(session._c_object) \
262
!= gnutls.library.constants.GNUTLS_CRT_OPENPGP:
263
# ...do the normal thing
264
return session.peer_certificate
265
list_size = ctypes.c_uint()
266
cert_list = gnutls.library.functions.gnutls_certificate_get_peers\
267
(session._c_object, ctypes.byref(list_size))
268
if list_size.value == 0:
271
return ctypes.string_at(cert.data, cert.size)
274
def fingerprint(openpgp):
275
# New empty GnuTLS certificate
276
crt = gnutls.library.types.gnutls_openpgp_crt_t()
277
gnutls.library.functions.gnutls_openpgp_crt_init\
279
# New GnuTLS "datum" with the OpenPGP public key
280
datum = gnutls.library.types.gnutls_datum_t\
281
(ctypes.cast(ctypes.c_char_p(openpgp),
282
ctypes.POINTER(ctypes.c_ubyte)),
283
ctypes.c_uint(len(openpgp)))
284
# Import the OpenPGP public key into the certificate
285
ret = gnutls.library.functions.gnutls_openpgp_crt_import\
288
gnutls.library.constants.GNUTLS_OPENPGP_FMT_RAW)
289
# New buffer for the fingerprint
290
buffer = ctypes.create_string_buffer(20)
291
buffer_length = ctypes.c_size_t()
292
# Get the fingerprint from the certificate into the buffer
293
gnutls.library.functions.gnutls_openpgp_crt_get_fingerprint\
294
(crt, ctypes.byref(buffer), ctypes.byref(buffer_length))
295
# Deinit the certificate
296
gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
297
# Convert the buffer to a Python bytestring
298
fpr = ctypes.string_at(buffer, buffer_length.value)
299
# Convert the bytestring to hexadecimal notation
300
hex_fpr = u''.join(u"%02X" % ord(char) for char in fpr)
304
203
class tcp_handler(SocketServer.BaseRequestHandler, object):
305
204
"""A TCP request handler class.
306
205
Instantiated by IPv6_TCPServer for each request to handle it.
307
206
Note: This will run in its own forked process."""
309
207
def handle(self):
310
logger.debug(u"TCP connection from: %s",
311
unicode(self.client_address))
312
session = gnutls.connection.ClientSession(self.request,
316
#priority = ':'.join(("NONE", "+VERS-TLS1.1", "+AES-256-CBC",
317
# "+SHA1", "+COMP-NULL", "+CTYPE-OPENPGP",
319
priority = "SECURE256"
321
gnutls.library.functions.gnutls_priority_set_direct\
322
(session._c_object, priority, None);
208
#print u"TCP request came"
209
#print u"Request:", self.request
210
#print u"Client Address:", self.client_address
211
#print u"Server:", self.server
212
session = gnutls.connection.ServerSession(self.request,
325
216
session.handshake()
326
217
except gnutls.errors.GNUTLSError, error:
327
logger.debug(u"Handshake failed: %s", error)
218
#sys.stderr.write(u"Handshake failed: %s\n" % error)
328
219
# Do not run session.bye() here: the session is not
329
220
# established. Just abandon the request.
222
#if session.peer_certificate:
223
# print "DN:", session.peer_certificate.subject
332
fpr = fingerprint(peer_certificate(session))
333
except (TypeError, gnutls.errors.GNUTLSError), error:
334
logger.debug(u"Bad certificate: %s", error)
225
session.verify_peer()
226
except gnutls.errors.CertificateError, error:
227
#sys.stderr.write(u"Verify failed: %s\n" % error)
337
logger.debug(u"Fingerprint: %s", fpr)
339
231
for c in clients:
340
if c.fingerprint == fpr:
232
if c.dn == session.peer_certificate.subject:
343
235
# Have to check if client.still_valid(), since it is possible
344
236
# that the client timed out while establishing the GnuTLS
346
if (not client) or (not client.still_valid()):
348
logger.debug(u"Client %(name)s is invalid",
351
logger.debug(u"Client not found for fingerprint: %s",
356
while sent_size < len(client.secret):
357
sent = session.send(client.secret[sent_size:])
358
logger.debug(u"Sent: %d, remaining: %d",
359
sent, len(client.secret)
360
- (sent_size + sent))
238
if client and client.still_valid():
239
session.send(client.password)
242
# sys.stderr.write(u"Client %(name)s is invalid\n"
245
# sys.stderr.write(u"Client not found for DN: %s\n"
246
# % session.peer_certificate.subject)
247
#session.send("gazonk")
488
379
"""From the Avahi server example code"""
489
380
global serviceName, server, rename_count
491
logger.debug(u"state change: %i", state)
382
# print "state change: %i" % state
493
384
if state == avahi.ENTRY_GROUP_ESTABLISHED:
494
logger.debug(u"Service established.")
386
# print "Service established."
495
387
elif state == avahi.ENTRY_GROUP_COLLISION:
497
389
rename_count = rename_count - 1
498
390
if rename_count > 0:
499
391
name = server.GetAlternativeServiceName(name)
500
logger.warning(u"Service name collision, "
501
u"changing name to '%s' ...", name)
392
print "WARNING: Service name collision, changing name to '%s' ..." % name
506
logger.error(u"No suitable service name found "
507
u"after %i retries, exiting.",
397
print "ERROR: No suitable service name found after %i retries, exiting." % n_rename
510
399
elif state == avahi.ENTRY_GROUP_FAILURE:
511
logger.error(u"Error in group state changed %s",
400
print "Error in group state changed", error