mechanisms.py 16.9 KB
Newer Older
Lance Stout's avatar
Lance Stout committed
1

2 3 4 5 6 7 8 9
# slixmpp.util.sasl.mechanisms
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# A collection of supported SASL mechanisms.
# This module was originally based on Dave Cridland's Suelta library.
# Part of Slixmpp: The Slick XMPP Library
# :copryight: (c) 2004-2013 David Alan Cridland
# :copyright: (c) 2013 Nathanael C. Fritz, Lance J.T. Stout
# :license: MIT, see LICENSE for more details
Lance Stout's avatar
Lance Stout committed
10 11 12 13
import hmac
import random

from base64 import b64encode, b64decode
mathieui's avatar
mathieui committed
14 15 16
from typing import List, Dict, Optional

bytes_ = bytes
Lance Stout's avatar
Lance Stout committed
17

louiz’'s avatar
louiz’ committed
18 19
from slixmpp.util import bytes, hash, XOR, quote, num_to_bytes
from slixmpp.util.sasl.client import sasl_mech, Mech, \
20 21
                                       SASLCancelled, SASLFailed, \
                                       SASLMutualAuthFailed
Lance Stout's avatar
Lance Stout committed
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36


@sasl_mech(0)
class ANONYMOUS(Mech):

    name = 'ANONYMOUS'

    def process(self, challenge=b''):
        return b'Anonymous, Suelta'


@sasl_mech(1)
class LOGIN(Mech):

    name = 'LOGIN'
37
    required_credentials = {'username', 'password'}
Lance Stout's avatar
Lance Stout committed
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56

    def setup(self, name):
        self.step = 0

    def process(self, challenge=b''):
        if not challenge:
            return b''

        if self.step == 0:
            self.step = 1
            return self.credentials['username']
        else:
            return self.credentials['password']


@sasl_mech(2)
class PLAIN(Mech):

    name = 'PLAIN'
57 58 59
    required_credentials = {'username', 'password'}
    optional_credentials = {'authzid'}
    security = {'encrypted', 'encrypted_plain', 'unencrypted_plain'}
Lance Stout's avatar
Lance Stout committed
60 61 62 63 64 65 66 67 68

    def setup(self, name):
        if not self.security_settings['encrypted']:
            if not self.security_settings['unencrypted_plain']:
                raise SASLCancelled('PLAIN without encryption')
        else:
            if not self.security_settings['encrypted_plain']:
                raise SASLCancelled('PLAIN with encryption')

mathieui's avatar
mathieui committed
69
    def process(self, challenge: bytes_ = b'') -> bytes_:
Lance Stout's avatar
Lance Stout committed
70 71 72 73 74 75 76 77 78 79
        authzid = self.credentials['authzid']
        authcid = self.credentials['username']
        password = self.credentials['password']
        return authzid + b'\x00' + authcid + b'\x00' + password


@sasl_mech(100)
class EXTERNAL(Mech):

    name = 'EXTERNAL'
80
    optional_credentials = {'authzid'}
Lance Stout's avatar
Lance Stout committed
81 82 83 84 85

    def process(self, challenge=b''):
        return self.credentials['authzid']


86
@sasl_mech(31)
Lance Stout's avatar
Lance Stout committed
87 88 89
class X_FACEBOOK_PLATFORM(Mech):

    name = 'X-FACEBOOK-PLATFORM'
90
    required_credentials = {'api_key', 'access_token'}
Lance Stout's avatar
Lance Stout committed
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107

    def process(self, challenge=b''):
        if challenge:
            values = {}
            for kv in challenge.split(b'&'):
                key, value = kv.split(b'=')
                values[key] = value

            resp_data = {
                b'method': values[b'method'],
                b'v': b'1.0',
                b'call_id': b'1.0',
                b'nonce': values[b'nonce'],
                b'access_token': self.credentials['access_token'],
                b'api_key': self.credentials['api_key']
            }

108
            resp = '&'.join(['%s=%s' % (k.decode("utf-8"), v.decode("utf-8")) for k, v in resp_data.items()])
Lance Stout's avatar
Lance Stout committed
109 110 111 112 113 114 115 116
            return bytes(resp)
        return b''


@sasl_mech(10)
class X_MESSENGER_OAUTH2(Mech):

    name = 'X-MESSENGER-OAUTH2'
117
    required_credentials = {'access_token'}
Lance Stout's avatar
Lance Stout committed
118 119 120 121 122

    def process(self, challenge=b''):
        return self.credentials['access_token']


123 124 125 126
@sasl_mech(10)
class X_OAUTH2(Mech):

    name = 'X-OAUTH2'
127
    required_credentials = {'username', 'access_token'}
128 129 130 131 132 133

    def process(self, challenge=b''):
        return b'\x00' + self.credentials['username'] + \
               b'\x00' + self.credentials['access_token']


Lance Stout's avatar
Lance Stout committed
134 135 136 137
@sasl_mech(3)
class X_GOOGLE_TOKEN(Mech):

    name = 'X-GOOGLE-TOKEN'
138
    required_credentials = {'email', 'access_token'}
Lance Stout's avatar
Lance Stout committed
139 140 141 142 143 144 145 146 147 148 149 150

    def process(self, challenge=b''):
        email = self.credentials['email']
        token = self.credentials['access_token']
        return b'\x00' + email + b'\x00' + token


@sasl_mech(20)
class CRAM(Mech):

    name = 'CRAM'
    use_hashes = True
151 152
    required_credentials = {'username', 'password'}
    security = {'encrypted', 'unencrypted_cram'}
Lance Stout's avatar
Lance Stout committed
153

mathieui's avatar
mathieui committed
154
    def setup(self, name: str):
Lance Stout's avatar
Lance Stout committed
155 156 157 158 159 160 161 162
        self.hash_name = name[5:]
        self.hash = hash(self.hash_name)
        if self.hash is None:
            raise SASLCancelled('Unknown hash: %s' % self.hash_name)
        if not self.security_settings['encrypted']:
            if not self.security_settings['unencrypted_cram']:
                raise SASLCancelled('Unecrypted CRAM-%s' % self.hash_name)

mathieui's avatar
mathieui committed
163
    def process(self, challenge: bytes_ = b'') -> Optional[bytes_]:
Lance Stout's avatar
Lance Stout committed
164 165 166 167 168 169
        if not challenge:
            return None

        username = self.credentials['username']
        password = self.credentials['password']

mathieui's avatar
mathieui committed
170
        mac = hmac.HMAC(key=password, digestmod=self.hash)  # type: ignore
Lance Stout's avatar
Lance Stout committed
171 172 173 174 175 176 177 178 179 180 181
        mac.update(challenge)

        return username + b' ' + bytes(mac.hexdigest())


@sasl_mech(60)
class SCRAM(Mech):

    name = 'SCRAM'
    use_hashes = True
    channel_binding = True
182 183 184
    required_credentials = {'username', 'password'}
    optional_credentials = {'authzid', 'channel_binding'}
    security = {'encrypted', 'unencrypted_scram'}
Lance Stout's avatar
Lance Stout committed
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206

    def setup(self, name):
        self.use_channel_binding = False
        if name[-5:] == '-PLUS':
            name = name[:-5]
            self.use_channel_binding = True

        self.hash_name = name[6:]
        self.hash = hash(self.hash_name)

        if self.hash is None:
            raise SASLCancelled('Unknown hash: %s' % self.hash_name)
        if not self.security_settings['encrypted']:
            if not self.security_settings['unencrypted_scram']:
                raise SASLCancelled('Unencrypted SCRAM')

        self.step = 0
        self._mutual_auth = False

    def HMAC(self, key, msg):
        return hmac.HMAC(key=key, msg=msg, digestmod=self.hash).digest()

mathieui's avatar
mathieui committed
207 208 209
    def Hi(self, text: str, salt: bytes_, iterations: int):
        text_enc = bytes(text)
        ui1 = self.HMAC(text_enc, salt + b'\0\0\0\01')
Lance Stout's avatar
Lance Stout committed
210 211
        ui = ui1
        for i in range(iterations - 1):
mathieui's avatar
mathieui committed
212
            ui1 = self.HMAC(text_enc, ui1)
Lance Stout's avatar
Lance Stout committed
213 214 215
            ui = XOR(ui, ui1)
        return ui

mathieui's avatar
mathieui committed
216
    def H(self, text: str) -> bytes_:
Lance Stout's avatar
Lance Stout committed
217 218
        return self.hash(text).digest()

mathieui's avatar
mathieui committed
219 220 221
    def saslname(self, value_b: bytes_) -> bytes_:
        value = value_b.decode("utf-8")
        escaped: List[str] = []
222 223
        for char in value:
            if char == ',':
mathieui's avatar
mathieui committed
224
                escaped.append('=2C')
225
            elif char == '=':
mathieui's avatar
mathieui committed
226
                escaped.append('=3D')
Lance Stout's avatar
Lance Stout committed
227
            else:
mathieui's avatar
mathieui committed
228
                escaped.append(char)
229
        return "".join(escaped).encode("utf-8")
Lance Stout's avatar
Lance Stout committed
230

mathieui's avatar
mathieui committed
231
    def parse(self, challenge: bytes_) -> Dict[bytes_, bytes_]:
Lance Stout's avatar
Lance Stout committed
232 233 234 235 236
        items = {}
        for key, value in [item.split(b'=', 1) for item in challenge.split(b',')]:
            items[key] = value
        return items

mathieui's avatar
mathieui committed
237
    def process(self, challenge: bytes_ = b''):
Lance Stout's avatar
Lance Stout committed
238 239 240
        steps = [self.process_1, self.process_2, self.process_3]
        return steps[self.step](challenge)

mathieui's avatar
mathieui committed
241
    def process_1(self, challenge: bytes_) -> bytes_:
Lance Stout's avatar
Lance Stout committed
242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267
        self.step = 1

        self.cnonce = bytes(('%s' % random.random())[2:])

        gs2_cbind_flag = b'n'
        if self.credentials['channel_binding']:
            if self.use_channel_binding:
                gs2_cbind_flag = b'p=tls-unique'
            else:
                gs2_cbind_flag = b'y'

        authzid = b''
        if self.credentials['authzid']:
            authzid = b'a=' + self.saslname(self.credentials['authzid'])

        self.gs2_header = gs2_cbind_flag + b',' + authzid + b','

        nonce = b'r=' + self.cnonce
        username = b'n=' + self.saslname(self.credentials['username'])

        self.client_first_message_bare = username + b',' + nonce
        self.client_first_message = self.gs2_header + \
                                    self.client_first_message_bare

        return self.client_first_message

mathieui's avatar
mathieui committed
268
    def process_2(self, challenge: bytes_) -> bytes_:
Lance Stout's avatar
Lance Stout committed
269 270 271 272 273 274 275 276 277 278 279 280 281
        self.step = 2

        data = self.parse(challenge)
        if b'm' in data:
            raise SASLCancelled('Received reserved attribute.')

        salt = b64decode(data[b's'])
        iteration_count = int(data[b'i'])
        nonce = data[b'r']

        if nonce[:len(self.cnonce)] != self.cnonce:
            raise SASLCancelled('Invalid nonce')

Lance Stout's avatar
Lance Stout committed
282 283 284
        cbind_data = b''
        if self.use_channel_binding:
            cbind_data = self.credentials['channel_binding']
Lance Stout's avatar
Lance Stout committed
285 286 287
        cbind_input = self.gs2_header + cbind_data
        channel_binding = b'c=' + b64encode(cbind_input).replace(b'\n', b'')

288
        client_final_message_without_proof = channel_binding + b',r=' + nonce
Lance Stout's avatar
Lance Stout committed
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308

        salted_password = self.Hi(self.credentials['password'],
                                       salt,
                                       iteration_count)
        client_key = self.HMAC(salted_password, b'Client Key')
        stored_key = self.H(client_key)
        auth_message = self.client_first_message_bare + b',' + \
                       challenge + b',' + \
                       client_final_message_without_proof
        client_signature = self.HMAC(stored_key, auth_message)
        client_proof = XOR(client_key, client_signature)
        server_key = self.HMAC(salted_password, b'Server Key')

        self.server_signature = self.HMAC(server_key, auth_message)

        client_final_message = client_final_message_without_proof + \
                               b',p=' + b64encode(client_proof)

        return client_final_message

mathieui's avatar
mathieui committed
309
    def process_3(self, challenge: bytes_) -> bytes_:
Lance Stout's avatar
Lance Stout committed
310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329
        data = self.parse(challenge)
        verifier = data.get(b'v', None)
        error = data.get(b'e', 'Unknown error')

        if not verifier:
            raise SASLFailed(error)

        if b64decode(verifier) != self.server_signature:
            raise SASLMutualAuthFailed()

        self._mutual_auth = True

        return b''


@sasl_mech(30)
class DIGEST(Mech):

    name = 'DIGEST'
    use_hashes = True
330 331 332
    required_credentials = {'username', 'password', 'realm', 'service', 'host'}
    optional_credentials = {'authzid', 'service-name'}
    security = {'encrypted', 'unencrypted_digest'}
Lance Stout's avatar
Lance Stout committed
333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349

    def setup(self, name):
        self.hash_name = name[7:]
        self.hash = hash(self.hash_name)
        if self.hash is None:
            raise SASLCancelled('Unknown hash: %s' % self.hash_name)
        if not self.security_settings['encrypted']:
            if not self.security_settings['unencrypted_digest']:
                raise SASLCancelled('Unencrypted DIGEST')

        self.qops = [b'auth']
        self.qop = b'auth'
        self.maxbuf = b'65536'
        self.nonce = b''
        self.cnonce = b''
        self.nonce_count = 1

mathieui's avatar
mathieui committed
350 351
    def parse(self, challenge:  bytes_ = b''):
        data: Dict[str, bytes_] = {}
Lance Stout's avatar
Lance Stout committed
352 353 354 355 356 357
        var_name = b''
        var_value = b''

        # States: var, new_var, end, quote, escaped_quote
        state = 'var'

mathieui's avatar
mathieui committed
358 359
        for char_int in challenge:
            char = bytes_([char_int])
Lance Stout's avatar
Lance Stout committed
360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404

            if state == 'var':
                if char.isspace():
                    continue
                if char == b'=':
                    state = 'value'
                else:
                    var_name += char
            elif state == 'value':
                if char == b'"':
                    state = 'quote'
                elif char == b',':
                    if var_name:
                        data[var_name.decode('utf-8')] = var_value
                    var_name = b''
                    var_value = b''
                    state = 'var'
                else:
                    var_value += char
            elif state == 'escaped':
                var_value += char
            elif state == 'quote':
                if char == b'\\':
                    state = 'escaped'
                elif char == b'"':
                    state = 'end'
                else:
                    var_value += char
            else:
                if char == b',':
                    if var_name:
                        data[var_name.decode('utf-8')] = var_value
                    var_name = b''
                    var_value = b''
                    state = 'var'
                else:
                    var_value += char

        if var_name:
            data[var_name.decode('utf-8')] = var_value
        var_name = b''
        var_value = b''
        state = 'var'
        return data

mathieui's avatar
mathieui committed
405
    def MAC(self, key: bytes_, seq: int, msg: bytes_) -> bytes_:
Lance Stout's avatar
Lance Stout committed
406 407 408 409 410 411
        mac = hmac.HMAC(key=key, digestmod=self.hash)
        seqnum = num_to_bytes(seq)
        mac.update(seqnum)
        mac.update(msg)
        return mac.digest()[:10] + b'\x00\x01' + seqnum

mathieui's avatar
mathieui committed
412
    def A1(self) -> bytes_:
Lance Stout's avatar
Lance Stout committed
413 414 415 416 417 418 419 420 421 422 423 424 425 426
        username = self.credentials['username']
        password = self.credentials['password']
        authzid = self.credentials['authzid']
        realm = self.credentials['realm']

        a1 = self.hash()
        a1.update(username + b':' + realm + b':' + password)
        a1 = a1.digest()
        a1 += b':' + self.nonce + b':' + self.cnonce
        if authzid:
            a1 += b':' + authzid

        return bytes(a1)

mathieui's avatar
mathieui committed
427
    def A2(self, prefix: bytes_ = b'') -> bytes_:
Lance Stout's avatar
Lance Stout committed
428 429 430 431 432
        a2 = prefix + b':' + self.digest_uri()
        if self.qop in (b'auth-int', b'auth-conf'):
            a2 += b':00000000000000000000000000000000'
        return bytes(a2)

mathieui's avatar
mathieui committed
433
    def response(self, prefix: bytes_ = b'') -> bytes_:
Lance Stout's avatar
Lance Stout committed
434 435 436 437 438 439 440 441 442
        nc = bytes('%08x' % self.nonce_count)

        a1 = bytes(self.hash(self.A1()).hexdigest().lower())
        a2 = bytes(self.hash(self.A2(prefix)).hexdigest().lower())
        s = self.nonce + b':' + nc + b':' + self.cnonce + \
                         b':' + self.qop + b':' + a2

        return bytes(self.hash(a1 + b':' + s).hexdigest().lower())

mathieui's avatar
mathieui committed
443
    def digest_uri(self) -> bytes_:
Lance Stout's avatar
Lance Stout committed
444 445 446 447 448 449 450 451 452
        serv_type = self.credentials['service']
        serv_name = self.credentials['service-name']
        host = self.credentials['host']

        uri = serv_type + b'/' + host
        if serv_name and host != serv_name:
            uri += b'/' + serv_name
        return uri

mathieui's avatar
mathieui committed
453
    def respond(self) -> bytes_:
Lance Stout's avatar
Lance Stout committed
454 455 456 457 458 459 460 461 462 463
        data = {
            'username': quote(self.credentials['username']),
            'authzid': quote(self.credentials['authzid']),
            'realm': quote(self.credentials['realm']),
            'nonce': quote(self.nonce),
            'cnonce': quote(self.cnonce),
            'nc': bytes('%08x' % self.nonce_count),
            'qop': self.qop,
            'digest-uri': quote(self.digest_uri()),
            'response': self.response(b'AUTHENTICATE'),
464 465
            'maxbuf': self.maxbuf,
            'charset': 'utf-8'
Lance Stout's avatar
Lance Stout committed
466 467 468 469 470 471 472
        }
        resp = b''
        for key, value in data.items():
            if value and value != b'""':
                resp += b',' + bytes(key) + b'=' + bytes(value)
        return resp[1:]

mathieui's avatar
mathieui committed
473
    def process(self, challenge: bytes_ = b'') -> Optional[bytes_]:
Lance Stout's avatar
Lance Stout committed
474 475 476 477
        if not challenge:
            if self.cnonce and self.nonce and self.nonce_count and self.qop:
                self.nonce_count += 1
                return self.respond()
478
            return None
Lance Stout's avatar
Lance Stout committed
479 480 481 482 483

        data = self.parse(challenge)
        if 'rspauth' in data:
            if data['rspauth'] != self.response():
                raise SASLMutualAuthFailed()
mathieui's avatar
mathieui committed
484
            return None
Lance Stout's avatar
Lance Stout committed
485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506
        else:
            self.nonce_count = 1
            self.cnonce = bytes('%s' % random.random())[2:]
            self.qops = data.get('qop', [b'auth'])
            self.qop = b'auth'
            if 'nonce' in data:
                self.nonce = data['nonce']
            if 'realm' in data and not self.credentials['realm']:
                self.credentials['realm'] = data['realm']

            return self.respond()


try:
    import kerberos
except ImportError:
    pass
else:
    @sasl_mech(75)
    class GSSAPI(Mech):

        name = 'GSSAPI'
507 508
        required_credentials = {'username', 'service-name'}
        optional_credentials = {'authzid'}
Lance Stout's avatar
Lance Stout committed
509 510 511 512

        def setup(self, name):
            authzid = self.credentials['authzid']
            if not authzid:
513
                authzid = 'xmpp@' + self.credentials['service-name'].decode()
Lance Stout's avatar
Lance Stout committed
514 515 516 517 518

            _, self.gss = kerberos.authGSSClientInit(authzid)
            self.step = 0

        def process(self, challenge=b''):
519
            b64_challenge = b64encode(challenge).decode('ascii')
Lance Stout's avatar
Lance Stout committed
520 521 522 523 524
            try:
                if self.step == 0:
                    result = kerberos.authGSSClientStep(self.gss, b64_challenge)
                    if result != kerberos.AUTH_GSS_CONTINUE:
                        self.step = 1
Graham's avatar
Graham committed
525 526 527
                elif not challenge:
                    kerberos.authGSSClientClean(self.gss)
                    return b''
Lance Stout's avatar
Lance Stout committed
528 529 530 531 532
                elif self.step == 1:
                    username = self.credentials['username']

                    kerberos.authGSSClientUnwrap(self.gss, b64_challenge)
                    resp = kerberos.authGSSClientResponse(self.gss)
533
                    kerberos.authGSSClientWrap(self.gss, resp, username.decode())
Lance Stout's avatar
Lance Stout committed
534 535 536

                resp = kerberos.authGSSClientResponse(self.gss)
            except kerberos.GSSError as e:
537
                raise SASLCancelled('Kerberos error: %s' % e)
Lance Stout's avatar
Lance Stout committed
538 539 540 541
            if not resp:
                return b''
            else:
                return b64decode(resp)