Debian Codegraph @

puresasl/mechanisms.py

raw symbols SCIP
1 import base64
2 import hashlib
3 import hmac
4 import random
5 import struct
6 import sys
7
8 from puresasl import SASLError, SASLProtocolException, QOP
9
10 try:
11 import kerberos
12 have_kerberos = True
13 except ImportError:
14 have_kerberos = False
15
16 PY3 = sys.version_info[0] == 3
17 if PY3:
18 def _b(s):
19 return s.encode("utf-8")
20 else:
21 def _b(s):
22 return s
23
24
25 class Mechanism(object):
26 """
27 The base class for all mechanisms.
28 """
29
30 name = None
31 """ The IANA registered name for the mechanism. """
32
33 score = 0
34 """ A relative security score where higher scores correspond
35 to more secure mechanisms. """
36
37 complete = False
38 """ Set to True when SASL negotiation has completed succesfully. """
39
40 has_initial_response = False
41
42 allows_anonymous = True
43 """ True if the mechanism allows for anonymous logins. """
44
45 uses_plaintext = True
46 """ True if the mechanism transmits sensitive information in plaintext. """
47
48 active_safe = False
49 """ True if the mechanism is safe against active attacks. """
50
51 dictionary_safe = False
52 """ True if the mechanism is safe against passive dictionary attacks. """
53
54 qops = [QOP.AUTH]
55 """ QOPs supported by the Mechanism """
56
57 qop = QOP.AUTH
58 """ Selected QOP """
59
60 def __init__(self, sasl, **props):
61 self.sasl = sasl
62
63 def process(self, challenge=None):
64 """
65 Process a challenge request and return the response.
66
67 :param challenge: A challenge issued by the server that
68 must be answered for authentication.
69 """
70 raise NotImplementedError()
71
72 def wrap(self, outgoing):
73 """
74 Wrap an outgoing message intended for the SASL server. Depending
75 on the negotiated quality of protection, this may result in the
76 message being signed, encrypted, or left unaltered.
77 """
78 raise NotImplementedError()
79
80 def unwrap(self, incoming):
81 """
82 Unwrap a message from the SASL server. Depending on the negotiated
83 quality of protection, this may check a signature, decrypt the message,
84 or leave the message unaltered.
85 """
86 raise NotImplementedError()
87
88 def dispose(self):
89 """
90 Clear all sensitive data, such as passwords.
91 """
92 pass
93
94 def _fetch_properties(self, *properties):
95 """
96 Ensure this mechanism has the needed properties. If they haven't
97 been set yet, the registered callback function will be called for
98 each property to retrieve a value.
99 """
100 needed = [p for p in properties if getattr(self, p, None) is None]
101 if needed and not self.sasl.callback:
102 raise SASLError('The following properties are required, but a '
103 'callback has not been set: %s' % ', '.join(needed))
104
105 for prop in needed:
106 setattr(self, prop, self.sasl.callback(prop))
107
108 def _pick_qop(self, server_qop_set):
109 """
110 Choose a quality of protection based on the user's requirements,
111 what the server supports, and what the mechanism supports.
112 """
113 user_qops = set(_b(qop) if isinstance(qop, str) else qop for qop in self.sasl.qops) # normalize user-defined config
114 supported_qops = set(self.qops)
115 available_qops = user_qops & supported_qops & server_qop_set
116 if not available_qops:
117 user = b', '.join(user_qops).decode('ascii')
118 supported = b', '.join(supported_qops).decode('ascii')
119 offered = b', '.join(server_qop_set).decode('ascii')
120 raise SASLProtocolException("Your requested quality of "
121 "protection is one of (%s), the server is "
122 "offering (%s), and %s supports (%s)" % (user, offered, self.name, supported))
123 else:
124 for qop in (QOP.AUTH_CONF, QOP.AUTH_INT, QOP.AUTH):
125 if qop in available_qops:
126 self.qop = qop
127 break
128
129
130 class AnonymousMechanism(Mechanism):
131 """
132 An anonymous user login mechanism.
133 """
134 name = 'ANONYMOUS'
135 score = 0
136
137 uses_plaintext = False
138
139 def process(self, challenge=None):
140 self.complete = True
141 return b'Anonymous, None'
142
143
144 class PlainMechanism(Mechanism):
145 """
146 A plaintext user/password based mechanism.
147 """
148 name = 'PLAIN'
149 score = 1
150
151 allows_anonymous = False
152
153 def wrap(self, outgoing):
154 return outgoing
155
156 def unwrap(self, incoming):
157 return incoming
158
159 def __init__(self, sasl, username=None, password=None, identity='', **props):
160 Mechanism.__init__(self, sasl)
161 self.identity = identity
162 self.username = username
163 self.password = password
164
165 def process(self, challenge=None):
166 self._fetch_properties('username', 'password')
167 self.complete = True
168 auth_id = self.sasl.authorization_id or self.identity
169 return b''.join((_b(auth_id), b'\x00', _b(self.username), b'\x00', _b(self.password)))
170
171 def dispose(self):
172 self.password = None
173
174
175 class ExternalMechanism(Mechanism):
176 """
177 The EXTERNAL mechanism allows a client to request the server to use
178 credentials established by means external to the mechanism to
179 authenticate the client.
180 """
181 name = 'EXTERNAL'
182 score = 10
183
184 def wrap(self, outgoing):
185 return outgoing
186
187 def unwrap(self, incoming):
188 return incoming
189
190 def process(self, challenge=None):
191 return b''
192
193
194 class CramMD5Mechanism(PlainMechanism):
195 name = "CRAM-MD5"
196 score = 20
197
198 allows_anonymous = False
199 uses_plaintext = False
200
201 def __init__(self, sasl, username=None, password=None, **props):
202 Mechanism.__init__(self, sasl)
203 self.username = username
204 self.password = password
205
206 def process(self, challenge=None):
207 if challenge is None:
208 return None
209
210 self._fetch_properties('username', 'password')
211 mac = hmac.HMAC(key=_b(self.password), digestmod=hashlib.md5)
212 mac.update(challenge)
213 self.complete = True
214 return b''.join((_b(self.username), b' ', _b(mac.hexdigest())))
215
216 def dispose(self):
217 self.password = None
218
219
220 # functions used in DigestMD5 which were originally defined in the now-removed
221 # util module
222
223 def bytes(text):
224 """
225 Convert Unicode text to UTF-8 encoded bytes.
226
227 Since Python 2.6+ and Python 3+ have similar but incompatible
228 signatures, this function unifies the two to keep code sane.
229
230 :param text: Unicode text to convert to bytes
231 :rtype: bytes (Python3), str (Python2.6+)
232 """
233 if sys.version_info < (3, 0):
234 import __builtin__
235 return __builtin__.bytes(text)
236 else:
237 import builtins
238 if isinstance(text, builtins.bytes):
239 # We already have bytes, so do nothing
240 return text
241 if isinstance(text, list):
242 # Convert a list of integers to bytes
243 return builtins.bytes(text)
244 else:
245 # Convert UTF-8 text to bytes
246 return builtins.bytes(str(text), encoding='utf-8')
247
248
249 def quote(text):
250 """
251 Enclose in quotes and escape internal slashes and double quotes.
252
253 :param text: A Unicode or byte string.
254 """
255 text = bytes(text)
256 return b'"' + text.replace(b'\\', b'\\\\').replace(b'"', b'\\"') + b'"'
257
258
259 class DigestMD5Mechanism(Mechanism):
260
261 name = "DIGEST-MD5"
262 score = 30
263
264 allows_anonymous = False
265 uses_plaintext = False
266
267 def __init__(self, sasl, username=None, password=None, **props):
268 Mechanism.__init__(self, sasl)
269 self.username = username
270 self.password = password
271
272 self._digest_uri = None
273 self._a1 = None
274
275 def dispose(self):
276 self._digest_uri = None
277 self._a1 = None
278
279 self.password = None
280 self.key_hash = None
281 self.realm = None
282 self.nonce = None
283 self.cnonce = None
284 self.nc = 0
285
286 def wrap(self, outgoing):
287 return outgoing
288
289 def unwrap(self, incoming):
290 return incoming
291
292 def response(self):
293 required_props = ['username']
294 if not getattr(self, 'key_hash', None):
295 required_props.append('password')
296 self._fetch_properties(*required_props)
297
298 resp = {}
299 resp['qop'] = self.qop
300
301 if getattr(self, 'realm', None) is not None:
302 resp['realm'] = quote(self.realm)
303
304 resp['username'] = quote(bytes(self.username))
305 resp['nonce'] = quote(self.nonce)
306 if self.nc == 0:
307 self.cnonce = bytes('%s' % random.random())[2:]
308 resp['cnonce'] = quote(self.cnonce)
309 self.nc += 1
310 resp['nc'] = bytes('%08x' % self.nc)
311
312 self._digest_uri = (
313 bytes(self.sasl.service) + b'/' + bytes(self.sasl.host))
314 resp['digest-uri'] = quote(self._digest_uri)
315
316 a2 = b'AUTHENTICATE:' + self._digest_uri
317 if self.qop != QOP.AUTH:
318 a2 += b':00000000000000000000000000000000'
319 resp['maxbuf'] = b'16777215' # 2**24-1
320 resp['response'] = self.gen_hash(a2)
321 return b','.join(
322 [
323 bytes(k) + b'=' + bytes(v)
324 for k, v in resp.items()
325 ]
326 )
327
328 @staticmethod
329 def parse_challenge(challenge):
330 """Parse a digest challenge message.
331
332 :param ``bytes`` challenge:
333 Challenge message from the server, in bytes.
334 :returns:
335 ``dict`` of ``str`` keyword to ``bytes`` values.
336 """
337 ret = {}
338 var = b''
339 val = b''
340 in_var = True
341 in_quotes = False
342 new = False
343 escaped = False
344 for c in challenge:
345 if sys.version_info[0] == 3:
346 c = bytes([c])
347 if in_var:
348 if c.isspace():
349 continue
350 if c == b'=':
351 in_var = False
352 new = True
353 else:
354 var += c
355 else:
356 if new:
357 if c == b'"':
358 in_quotes = True
359 else:
360 val += c
361 new = False
362 elif in_quotes:
363 if escaped:
364 escaped = False
365 val += c
366 else:
367 if c == b'\\':
368 escaped = True
369 elif c == b'"':
370 in_quotes = False
371 else:
372 val += c
373 else:
374 if c == b',':
375 if var:
376 ret[var.decode('ascii')] = val
377 var = b''
378 val = b''
379 in_var = True
380 else:
381 val += c
382 if var:
383 ret[var.decode('ascii')] = val
384 return ret
385
386 def gen_hash(self, a2):
387 if not getattr(self, 'key_hash', None):
388 key_hash = hashlib.md5()
389 user = bytes(self.username)
390 password = bytes(self.password)
391 realm = bytes(self.realm)
392 kh = user + b':' + realm + b':' + password
393 key_hash.update(kh)
394 self.key_hash = key_hash.digest()
395
396 a1 = hashlib.md5(self.key_hash)
397 a1h = b':' + self.nonce + b':' + self.cnonce
398 a1.update(a1h)
399 response = hashlib.md5()
400 self._a1 = a1.digest()
401 rv = bytes(a1.hexdigest().lower())
402 rv += b':' + self.nonce
403 rv += b':' + bytes('%08x' % self.nc)
404 rv += b':' + self.cnonce
405 rv += b':' + self.qop
406 rv += b':' + bytes(hashlib.md5(a2).hexdigest().lower())
407 response.update(rv)
408 return bytes(response.hexdigest().lower())
409
410 def authenticate_server(self, cmp_hash):
411 a2 = b':' + self._digest_uri
412 if self.qop != QOP.AUTH:
413 a2 += b':00000000000000000000000000000000'
414 if self.gen_hash(a2) != cmp_hash:
415 raise SASLProtocolException('Invalid server auth response')
416
417 def process(self, challenge=None):
418 if challenge is None:
419 needed = ['username', 'realm', 'nonce', 'key_hash',
420 'nc', 'cnonce', 'qops']
421 if all(getattr(self, p, None) is not None for p in needed):
422 return self.response()
423 else:
424 return None
425
426 challenge_dict = DigestMD5Mechanism.parse_challenge(challenge)
427 if 'rspauth' in challenge_dict:
428 self.authenticate_server(challenge_dict['rspauth'])
429 self.complete = True
430 return None
431
432 if 'realm' not in challenge_dict:
433 self._fetch_properties('realm')
434 challenge_dict['realm'] = self.realm
435
436 for key in ('nonce', 'realm'):
437 # TODO: rfc2831#section-2.1.1 realm: "Multiple realm directives are
438 # allowed, in which case the user or client must choose one as the
439 # realm for which to supply to username and password"
440 # TODO: rfc2831#section-2.1.1 nonce: "This directive is required
441 # and MUST appear exactly once; if not present, or if multiple
442 # instances are present, the client should abort the authentication
443 # exchange"
444 if key in challenge_dict:
445 setattr(self, key, challenge_dict[key])
446
447 self.nc = 0
448 if 'qop' in challenge_dict:
449 server_offered_qops = [
450 x.strip() for x in challenge_dict['qop'].split(b',')
451 ]
452 else:
453 server_offered_qops = [QOP.AUTH]
454 self._pick_qop(set(server_offered_qops))
455
456 if 'maxbuf' in challenge_dict:
457 self.max_buffer = min(
458 self.sasl.max_buffer, int(challenge_dict['maxbuf']))
459
460 # TODO: rfc2831#section-2.1.1 algorithm: This directive is required and
461 # MUST appear exactly once; if not present, or if multiple instances
462 # are present, the client should abort the authentication exchange.
463 return self.response()
464
465
466 class GSSAPIMechanism(Mechanism):
467 name = 'GSSAPI'
468 score = 100
469 qops = QOP.all
470
471 allows_anonymous = False
472 uses_plaintext = False
473 active_safe = True
474
475 def __init__(self, sasl, principal=None, **props):
476 Mechanism.__init__(self, sasl)
477 self.user = None
478 self._have_negotiated_details = False
479 self.host = self.sasl.host
480 self.service = self.sasl.service
481 self.principal = principal
482 self._fetch_properties('host', 'service')
483
484 krb_service = '@'.join((self.service, self.host))
485 try:
486 _, self.context = kerberos.authGSSClientInit(service=krb_service,
487 principal=self.principal)
488 except TypeError:
489 if self.principal is not None:
490 raise Exception("Error: kerberos library does not support principal.")
491 _, self.context = kerberos.authGSSClientInit(service=krb_service)
492
493 def process(self, challenge=None):
494 if not self._have_negotiated_details:
495 kerberos.authGSSClientStep(self.context, '')
496 _negotiated_details = kerberos.authGSSClientResponse(self.context)
497 self._have_negotiated_details = True
498 return base64.b64decode(_negotiated_details)
499
500 challenge = base64.b64encode(challenge).decode('ascii') # kerberos methods expect strings, not bytes
501 if self.user is None:
502 ret = kerberos.authGSSClientStep(self.context, challenge)
503 if ret == kerberos.AUTH_GSS_COMPLETE:
504 self.user = kerberos.authGSSClientUserName(self.context)
505 return b''
506 else:
507 response = kerberos.authGSSClientResponse(self.context)
508 if response:
509 response = base64.b64decode(response)
510 else:
511 response = b''
512 return response
513
514 kerberos.authGSSClientUnwrap(self.context, challenge)
515 data = kerberos.authGSSClientResponse(self.context)
516 plaintext_data = base64.b64decode(data)
517 if len(plaintext_data) != 4:
518 raise SASLProtocolException("Bad response from server") # todo: better message
519
520 word, = struct.unpack('!I', plaintext_data)
521 qop_bits = word >> 24
522 max_length = word & 0xffffff
523 server_offered_qops = QOP.names_from_bitmask(qop_bits)
524 self._pick_qop(server_offered_qops)
525
526 self.max_buffer = min(self.sasl.max_buffer, max_length)
527
528 """
529 byte 0: the selected qop. 1==auth, 2==auth-int, 4==auth-conf
530 byte 1-3: the max length for any buffer sent back and forth on
531 this connection. (big endian)
532 the rest of the buffer: the authorization user name in UTF-8 -
533 not null terminated.
534 """
535 auth_id = self.sasl.authorization_id or self.user
536 l = len(auth_id)
537 fmt = '!I' + str(l) + 's'
538 word = QOP.flag_from_name(self.qop) << 24 | self.max_buffer
539 out = struct.pack(fmt, word, _b(auth_id),)
540
541 encoded = base64.b64encode(out).decode('ascii')
542
543 kerberos.authGSSClientWrap(self.context, encoded)
544 response = kerberos.authGSSClientResponse(self.context)
545 self.complete = True
546 return base64.b64decode(response)
547
548 def wrap(self, outgoing):
549 if self.qop != QOP.AUTH:
550 outgoing = base64.b64encode(outgoing)
551 if self.qop == QOP.AUTH_CONF:
552 protect = 1
553 else:
554 protect = 0
555 kerberos.authGSSClientWrap(self.context, outgoing, None, protect)
556 return base64.b64decode(kerberos.authGSSClientResponse(self.context))
557 else:
558 return outgoing
559
560 def unwrap(self, incoming):
561 if self.qop != QOP.AUTH:
562 incoming = base64.b64encode(incoming).decode('ascii')
563 kerberos.authGSSClientUnwrap(self.context, incoming)
564 conf = kerberos.authGSSClientResponseConf(self.context)
565 if 0 == conf and self.qop == QOP.AUTH_CONF:
566 raise Exception("Error: confidentiality requested, but not honored by the server.")
567 return base64.b64decode(kerberos.authGSSClientResponse(self.context))
568 else:
569 return incoming
570
571 def dispose(self):
572 kerberos.authGSSClientClean(self.context)
573
574
575 #: Global registry mapping mechanism names to implementation classes.
576 mechanisms = dict((m.name, m) for m in (
577 AnonymousMechanism,
578 PlainMechanism,
579 ExternalMechanism,
580 CramMD5Mechanism,
581 DigestMD5Mechanism))
582
583 if have_kerberos:
584 mechanisms[GSSAPIMechanism.name] = GSSAPIMechanism