client.py 5.36 KB
Newer Older
1 2 3 4 5 6 7
# slixmpp.util.sasl.client
# ~~~~~~~~~~~~~~~~~~~~~~~~~~
# 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
mathieui's avatar
mathieui committed
8
from __future__ import annotations
Lance Stout's avatar
Lance Stout committed
9
import logging
Lance Stout's avatar
Lance Stout committed
10 11
import stringprep

mathieui's avatar
mathieui committed
12
from typing import Iterable, Set, Callable, Dict, Any, Optional, Type
louiz’'s avatar
louiz’ committed
13
from slixmpp.util import hashes, bytes, stringprep_profiles
Lance Stout's avatar
Lance Stout committed
14 15


Lance Stout's avatar
Lance Stout committed
16 17 18
log = logging.getLogger(__name__)


Lance Stout's avatar
Lance Stout committed
19
#: Global registry mapping mechanism names to implementation classes.
mathieui's avatar
mathieui committed
20
MECHANISMS: Dict[str, Type[Mech]] = {}
Lance Stout's avatar
Lance Stout committed
21 22 23


#: Global registry mapping mechanism names to security scores.
mathieui's avatar
mathieui committed
24
MECH_SEC_SCORES: Dict[str, int] = {}
Lance Stout's avatar
Lance Stout committed
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48


#: The SASLprep profile of stringprep used to validate simple username
#: and password credentials.
saslprep = stringprep_profiles.create(
    nfkc=True,
    bidi=True,
    mappings=[
        stringprep_profiles.b1_mapping,
        stringprep_profiles.c12_mapping],
    prohibited=[
        stringprep.in_table_c12,
        stringprep.in_table_c21,
        stringprep.in_table_c22,
        stringprep.in_table_c3,
        stringprep.in_table_c4,
        stringprep.in_table_c5,
        stringprep.in_table_c6,
        stringprep.in_table_c7,
        stringprep.in_table_c8,
        stringprep.in_table_c9],
    unassigned=[stringprep.in_table_a1])


mathieui's avatar
mathieui committed
49
def sasl_mech(score: int):
Lance Stout's avatar
Lance Stout committed
50
    sec_score = score
mathieui's avatar
mathieui committed
51 52

    def register(mech: Type[Mech]):
Lance Stout's avatar
Lance Stout committed
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
        n = 0
        mech.score = sec_score
        if mech.use_hashes:
            for hashing_alg in hashes():
                n += 1
                score = mech.score + n
                name = '%s-%s' % (mech.name, hashing_alg)
                MECHANISMS[name] = mech
                MECH_SEC_SCORES[name] = score

                if mech.channel_binding:
                    name += '-PLUS'
                    score += 10
                    MECHANISMS[name] = mech
                    MECH_SEC_SCORES[name] = score
        else:
            MECHANISMS[mech.name] = mech
            MECH_SEC_SCORES[mech.name] = mech.score
            if mech.channel_binding:
                MECHANISMS[mech.name + '-PLUS'] = mech
73
                MECH_SEC_SCORES[mech.name] = mech.score + 10
Lance Stout's avatar
Lance Stout committed
74 75 76 77 78
        return mech
    return register


class SASLNoAppropriateMechanism(Exception):
Lance Stout's avatar
Lance Stout committed
79 80
    def __init__(self, value=''):
        self.message = value
Lance Stout's avatar
Lance Stout committed
81 82 83


class SASLCancelled(Exception):
Lance Stout's avatar
Lance Stout committed
84 85
    def __init__(self, value=''):
        self.message = value
Lance Stout's avatar
Lance Stout committed
86 87 88


class SASLFailed(Exception):
Lance Stout's avatar
Lance Stout committed
89 90
    def __init__(self, value=''):
        self.message = value
Lance Stout's avatar
Lance Stout committed
91 92 93


class SASLMutualAuthFailed(SASLFailed):
Lance Stout's avatar
Lance Stout committed
94 95
    def __init__(self, value=''):
        self.message = value
Lance Stout's avatar
Lance Stout committed
96 97 98 99 100 101 102 103


class Mech(object):

    name = 'GENERIC'
    score = -1
    use_hashes = False
    channel_binding = False
mathieui's avatar
mathieui committed
104 105 106
    required_credentials: Set[str] = set()
    optional_credentials: Set[str] = set()
    security: Set[str] = set()
Lance Stout's avatar
Lance Stout committed
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122

    def __init__(self, name, credentials, security_settings):
        self.credentials = credentials
        self.security_settings = security_settings
        self.values = {}
        self.base_name = self.name
        self.name = name
        self.setup(name)

    def setup(self, name):
        pass

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


mathieui's avatar
mathieui committed
123 124 125 126 127 128 129 130
CredentialsCallback = Callable[[Iterable[str], Iterable[str]], Dict[str, Any]]
SecurityCallback = Callable[[Iterable[str]], Dict[str, Any]]


def choose(mech_list: Iterable[Type[Mech]], credentials: CredentialsCallback,
           security_settings: SecurityCallback,
           limit: Optional[Iterable[Type[Mech]]] = None,
           min_mech: Optional[str] = None) -> Mech:
Lance Stout's avatar
Lance Stout committed
131 132 133 134 135 136 137 138 139 140 141
    available_mechs = set(MECHANISMS.keys())
    if limit is None:
        limit = set(mech_list)
    if not isinstance(limit, set):
        limit = set(limit)
    if not isinstance(mech_list, set):
        mech_list = set(mech_list)

    mech_list = mech_list.intersection(limit)
    available_mechs = available_mechs.intersection(mech_list)

mathieui's avatar
mathieui committed
142 143 144 145
    if min_mech is None:
        best_score = -1
    else:
        best_score = MECH_SEC_SCORES.get(min_mech, -1)
Lance Stout's avatar
Lance Stout committed
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
    best_mech = None
    for name in available_mechs:
        if name in MECH_SEC_SCORES:
            if MECH_SEC_SCORES[name] > best_score:
                best_score = MECH_SEC_SCORES[name]
                best_mech = name
    if best_mech is None:
        raise SASLNoAppropriateMechanism()

    mech_class = MECHANISMS[best_mech]

    try:
        creds = credentials(mech_class.required_credentials,
                            mech_class.optional_credentials)
        for req in mech_class.required_credentials:
            if req not in creds:
                raise SASLCancelled('Missing credential: %s' % req)
        for opt in mech_class.optional_credentials:
            if opt not in creds:
                creds[opt] = b''
        for cred in creds:
            if cred in ('username', 'password', 'authzid'):
                creds[cred] = bytes(saslprep(creds[cred]))
            else:
                creds[cred] = bytes(creds[cred])
        security_opts = security_settings(mech_class.security)

        return mech_class(best_mech, creds, security_opts)
    except SASLCancelled as e:
Lance Stout's avatar
Lance Stout committed
175
        log.info('SASL: %s: %s', best_mech, e.message)
Lance Stout's avatar
Lance Stout committed
176 177 178 179
        mech_list.remove(best_mech)
        return choose(mech_list, credentials, security_settings,
                limit=limit,
                min_mech=min_mech)