44
48
class Client(object):
45
49
"""A representation of a client host served by this server.
48
fqdn: string, FQDN (used by the checker)
51
name: string; from the config file, used in log messages
52
fingerprint: string (40 or 32 hexadecimal digits); used to
53
uniquely identify the client
54
secret: bytestring; sent verbatim (over TLS) to client
55
fqdn: string (FQDN); available for use by the checker command
49
56
created: datetime.datetime()
50
57
last_seen: datetime.datetime() or None if not yet seen
51
58
timeout: datetime.timedelta(); How long from last_seen until
52
59
this client is invalid
53
60
interval: datetime.timedelta(); How often to start a new checker
54
timeout_milliseconds: Used by gobject.timeout_add()
55
interval_milliseconds: - '' -
56
61
stop_hook: If set, called by stop() as stop_hook(self)
57
62
checker: subprocess.Popen(); a running checker process used
58
63
to see if the client lives.
60
65
checker_initiator_tag: a gobject event source tag, or None
61
66
stop_initiator_tag: - '' -
62
67
checker_callback_tag: - '' -
68
checker_command: string; External command which is run to check if
69
client lives. %()s expansions are done at
70
runtime with vars(self) as dict, so that for
71
instance %(name)s can be used in the command.
73
_timeout: Real variable for 'timeout'
74
_interval: Real variable for 'interval'
75
_timeout_milliseconds: Used by gobject.timeout_add()
76
_interval_milliseconds: - '' -
78
def _set_timeout(self, timeout):
79
"Setter function for 'timeout' attribute"
80
self._timeout = timeout
81
self._timeout_milliseconds = ((self.timeout.days
82
* 24 * 60 * 60 * 1000)
83
+ (self.timeout.seconds * 1000)
84
+ (self.timeout.microseconds
86
timeout = property(lambda self: self._timeout,
89
def _set_interval(self, interval):
90
"Setter function for 'interval' attribute"
91
self._interval = interval
92
self._interval_milliseconds = ((self.interval.days
93
* 24 * 60 * 60 * 1000)
94
+ (self.interval.seconds
96
+ (self.interval.microseconds
98
interval = property(lambda self: self._interval,
64
101
def __init__(self, name=None, options=None, stop_hook=None,
65
dn=None, password=None, passfile=None, fqdn=None,
66
timeout=None, interval=-1):
102
fingerprint=None, secret=None, secfile=None, fqdn=None,
103
timeout=None, interval=-1, checker=None):
70
self.password = password
72
self.password = open(passfile).readall()
105
# Uppercase and remove spaces from fingerprint
106
# for later comparison purposes with return value of
107
# the fingerprint() function
108
self.fingerprint = fingerprint.upper().replace(u" ", u"")
110
self.secret = secret.decode(u"base64")
113
self.secret = sf.read()
74
raise RuntimeError(u"No Password or Passfile for client %s"
116
raise RuntimeError(u"No secret or secfile for client %s"
76
118
self.fqdn = fqdn # string
77
119
self.created = datetime.datetime.now()
79
121
if timeout is None:
80
122
timeout = options.timeout
81
123
self.timeout = timeout
82
self.timeout_milliseconds = ((self.timeout.days
83
* 24 * 60 * 60 * 1000)
84
+ (self.timeout.seconds * 1000)
85
+ (self.timeout.microseconds
87
124
if interval == -1:
88
125
interval = options.interval
90
127
interval = string_to_delta(interval)
91
128
self.interval = interval
92
self.interval_milliseconds = ((self.interval.days
93
* 24 * 60 * 60 * 1000)
94
+ (self.interval.seconds * 1000)
95
+ (self.interval.microseconds
97
129
self.stop_hook = stop_hook
98
130
self.checker = None
99
131
self.checker_initiator_tag = None
100
132
self.stop_initiator_tag = None
101
133
self.checker_callback_tag = None
134
self.check_command = checker
103
136
"""Start this clients checker and timeout hooks"""
104
137
# Schedule a new checker to be started an 'interval' from now,
105
138
# and every interval from then on.
106
self.checker_initiator_tag = gobject.\
107
timeout_add(self.interval_milliseconds,
139
self.checker_initiator_tag = gobject.timeout_add\
140
(self._interval_milliseconds,
109
142
# Also start a new checker *right now*.
110
143
self.start_checker()
111
144
# Schedule a stop() when 'timeout' has passed
112
self.stop_initiator_tag = gobject.\
113
timeout_add(self.timeout_milliseconds,
145
self.stop_initiator_tag = gobject.timeout_add\
146
(self._timeout_milliseconds,
116
149
"""Stop this client.
117
150
The possibility that this client might be restarted is left
118
151
open, but not currently used."""
119
# print "Stopping client", self.name
153
sys.stderr.write(u"Stopping client %s\n" % self.name)
121
155
if self.stop_initiator_tag:
122
156
gobject.source_remove(self.stop_initiator_tag)
123
157
self.stop_initiator_tag = None
145
179
now = datetime.datetime.now()
146
180
if os.WIFEXITED(condition) \
147
181
and (os.WEXITSTATUS(condition) == 0):
148
#print "Checker for %(name)s succeeded" % vars(self)
183
sys.stderr.write(u"Checker for %(name)s succeeded\n"
149
185
self.last_seen = now
150
186
gobject.source_remove(self.stop_initiator_tag)
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)
187
self.stop_initiator_tag = gobject.timeout_add\
188
(self._timeout_milliseconds,
191
if not os.WIFEXITED(condition):
192
sys.stderr.write(u"Checker for %(name)s crashed?\n"
195
sys.stderr.write(u"Checker for %(name)s failed\n"
159
197
self.checker = None
160
198
self.checker_callback_tag = None
161
199
def start_checker(self):
200
246
return now < (self.last_seen + self.timeout)
249
def peer_certificate(session):
250
# If not an OpenPGP certificate...
251
if gnutls.library.functions.gnutls_certificate_type_get\
252
(session._c_object) \
253
!= gnutls.library.constants.GNUTLS_CRT_OPENPGP:
254
# ...do the normal thing
255
return session.peer_certificate
256
list_size = ctypes.c_uint()
257
cert_list = gnutls.library.functions.gnutls_certificate_get_peers\
258
(session._c_object, ctypes.byref(list_size))
259
if list_size.value == 0:
262
return ctypes.string_at(cert.data, cert.size)
265
def fingerprint(openpgp):
266
# New empty GnuTLS certificate
267
crt = gnutls.library.types.gnutls_openpgp_crt_t()
268
gnutls.library.functions.gnutls_openpgp_crt_init\
270
# New GnuTLS "datum" with the OpenPGP public key
271
datum = gnutls.library.types.gnutls_datum_t\
272
(ctypes.cast(ctypes.c_char_p(openpgp),
273
ctypes.POINTER(ctypes.c_ubyte)),
274
ctypes.c_uint(len(openpgp)))
275
# Import the OpenPGP public key into the certificate
276
ret = gnutls.library.functions.gnutls_openpgp_crt_import\
279
gnutls.library.constants.GNUTLS_OPENPGP_FMT_RAW)
280
# New buffer for the fingerprint
281
buffer = ctypes.create_string_buffer(20)
282
buffer_length = ctypes.c_size_t()
283
# Get the fingerprint from the certificate into the buffer
284
gnutls.library.functions.gnutls_openpgp_crt_get_fingerprint\
285
(crt, ctypes.byref(buffer), ctypes.byref(buffer_length))
286
# Deinit the certificate
287
gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
288
# Convert the buffer to a Python bytestring
289
fpr = ctypes.string_at(buffer, buffer_length.value)
290
# Convert the bytestring to hexadecimal notation
291
hex_fpr = u''.join(u"%02X" % ord(char) for char in fpr)
203
295
class tcp_handler(SocketServer.BaseRequestHandler, object):
204
296
"""A TCP request handler class.
205
297
Instantiated by IPv6_TCPServer for each request to handle it.
206
298
Note: This will run in its own forked process."""
207
300
def handle(self):
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,
302
sys.stderr.write(u"TCP request came\n")
303
sys.stderr.write(u"Request: %s\n" % self.request)
304
sys.stderr.write(u"Client Address: %s\n"
305
% unicode(self.client_address))
306
sys.stderr.write(u"Server: %s\n" % self.server)
307
session = gnutls.connection.ClientSession(self.request,
311
#priority = ':'.join(("NONE", "+VERS-TLS1.1", "+AES-256-CBC",
312
# "+SHA1", "+COMP-NULL", "+CTYPE-OPENPGP",
314
priority = "SECURE256"
316
gnutls.library.functions.gnutls_priority_set_direct\
317
(session._c_object, priority, None);
216
320
session.handshake()
217
321
except gnutls.errors.GNUTLSError, error:
218
#sys.stderr.write(u"Handshake failed: %s\n" % error)
323
sys.stderr.write(u"Handshake failed: %s\n" % error)
219
324
# Do not run session.bye() here: the session is not
220
325
# established. Just abandon the request.
222
#if session.peer_certificate:
223
# print "DN:", session.peer_certificate.subject
225
session.verify_peer()
226
except gnutls.errors.CertificateError, error:
227
#sys.stderr.write(u"Verify failed: %s\n" % error)
328
fpr = fingerprint(peer_certificate(session))
329
except (TypeError, gnutls.errors.GNUTLSError), error:
331
sys.stderr.write(u"Bad certificate: %s\n" % error)
335
sys.stderr.write(u"Fingerprint: %s\n" % fpr)
231
337
for c in clients:
232
if c.dn == session.peer_certificate.subject:
338
if c.fingerprint == fpr:
235
341
# Have to check if client.still_valid(), since it is possible
236
342
# that the client timed out while establishing the GnuTLS
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")
344
if (not client) or (not client.still_valid()):
347
sys.stderr.write(u"Client %(name)s is invalid\n"
350
sys.stderr.write(u"Client not found for "
351
u"fingerprint: %s\n" % fpr)
355
while sent_size < len(client.secret):
356
sent = session.send(client.secret[sent_size:])
358
sys.stderr.write(u"Sent: %d, remaining: %d\n"
359
% (sent, len(client.secret)
360
- (sent_size + sent)))
379
489
"""From the Avahi server example code"""
380
490
global serviceName, server, rename_count
382
# print "state change: %i" % state
493
sys.stderr.write(u"state change: %i\n" % state)
384
495
if state == avahi.ENTRY_GROUP_ESTABLISHED:
386
# print "Service established."
497
sys.stderr.write(u"Service established.\n")
387
498
elif state == avahi.ENTRY_GROUP_COLLISION:
389
500
rename_count = rename_count - 1
390
501
if rename_count > 0:
391
502
name = server.GetAlternativeServiceName(name)
392
print "WARNING: Service name collision, changing name to '%s' ..." % name
503
sys.stderr.write(u"WARNING: Service name collision, "
504
u"changing name to '%s' ...\n" % name)
397
print "ERROR: No suitable service name found after %i retries, exiting." % n_rename
509
sys.stderr.write(u"ERROR: No suitable service name found "
510
u"after %i retries, exiting.\n"
399
513
elif state == avahi.ENTRY_GROUP_FAILURE:
400
print "Error in group state changed", error
514
sys.stderr.write(u"Error in group state changed %s\n"