summaryrefslogtreecommitdiff
path: root/sleekxmpp/thirdparty/suelta/mechanisms/scram_hmac.py
blob: b70ac9a4778e9f87a8703b350cf45e13419866c7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
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
175
176
import sys
import hmac
import random
from base64 import b64encode, b64decode

from sleekxmpp.thirdparty.suelta.util import hash, bytes, num_to_bytes, bytes_to_num, XOR
from sleekxmpp.thirdparty.suelta.sasl import Mechanism, register_mechanism
from sleekxmpp.thirdparty.suelta.exceptions import SASLError, SASLCancelled


def parse_challenge(challenge):
    """
    """
    items = {}
    for key, value in [item.split(b'=', 1) for item in challenge.split(b',')]:
        items[key] = value
    return items


class SCRAM_HMAC(Mechanism):

    """
    """

    def __init__(self, sasl, name):
        """
        """
        super(SCRAM_HMAC, self).__init__(sasl, name, 0)

        self._cb = False
        if name[-5:] == '-PLUS':
            name = name[:-5]
            self._cb = True

        self.hash = hash(name[6:])
        if self.hash is None:
            raise SASLCancelled(self.sasl, self)
        if not self.sasl.tls_active():
            if not self.sasl.sec_query(self, '-ENCRYPTION, SCRAM'):
                raise SASLCancelled(self.sasl, self)

        self._step = 0
        self._rspauth = False

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

    def Hi(self, text, salt, iterations):
        """
        """
        text = bytes(text)
        ui_1 = self.HMAC(text, salt + b'\0\0\0\01')
        ui = ui_1
        for i in range(iterations - 1):
            ui_1 = self.HMAC(text, ui_1)
            ui = XOR(ui, ui_1)
        return ui

    def H(self, text):
        """
        """
        return self.hash(text).digest()

    def prep(self):
        if 'password' in self.values:
            del self.values['password']

    def process(self, challenge=None):
        """
        """
        steps = {
            0: self.process_one,
            1: self.process_two,
            2: self.process_three
        }
        return steps[self._step](challenge)

    def process_one(self, challenge):
        """
        """
        vitals = ['username']
        if 'SaltedPassword' not in self.values:
            vitals.append('password')
        if 'Iterations' not in self.values:
            vitals.append('password')

        self.check_values(vitals)

        username = bytes(self.values['username'])

        self._step = 1
        self._cnonce = bytes(('%s' % random.random())[2:])
        self._soup = b'n=' + username + b',r=' + self._cnonce
        self._gs2header = b''

        if not self.sasl.tls_active():
            if self._cb:
                self._gs2header = b'p=tls-unique,,'
            else:
                self._gs2header = b'y,,'
        else:
            self._gs2header = b'n,,'

        return self._gs2header + self._soup

    def process_two(self, challenge):
        """
        """
        data = parse_challenge(challenge)

        self._step = 2
        self._soup += b',' + challenge + b','
        self._nonce = data[b'r']
        self._salt = b64decode(data[b's'])
        self._iter = int(data[b'i'])

        if self._nonce[:len(self._cnonce)] != self._cnonce:
            raise SASLCancelled(self.sasl, self)

        cbdata = self.sasl.tls_active()
        c = self._gs2header
        if not cbdata and self._cb:
            c += None

        r = b'c=' + b64encode(c).replace(b'\n', b'')
        r += b',r=' + self._nonce
        self._soup += r

        if 'Iterations' in self.values:
            if self.values['Iterations'] != self._iter:
                if 'SaltedPassword' in self.values:
                    del self.values['SaltedPassword']
        if 'Salt' in self.values:
            if self.values['Salt'] != self._salt:
                if 'SaltedPassword' in self.values:
                    del self.values['SaltedPassword']

        self.values['Iterations'] = self._iter
        self.values['Salt'] = self._salt

        if 'SaltedPassword' not in self.values:
            self.check_values(['password'])
            password = bytes(self.values['password'])
            salted_pass = self.Hi(password, self._salt, self._iter)
            self.values['SaltedPassword'] = salted_pass

        salted_pass = self.values['SaltedPassword']
        client_key = self.HMAC(salted_pass, b'Client Key')
        stored_key = self.H(client_key)
        client_sig = self.HMAC(stored_key, self._soup)
        client_proof = XOR(client_key, client_sig)
        r += b',p=' + b64encode(client_proof).replace(b'\n', b'')
        server_key = self.HMAC(self.values['SaltedPassword'], b'Server Key')
        self.server_sig = self.HMAC(server_key, self._soup)
        return r

    def process_three(self, challenge=None):
        """
        """
        data = parse_challenge(challenge)
        if b64decode(data[b'v']) == self.server_sig:
            self._rspauth = True

    def okay(self):
        """
        """
        return self._rspauth

    def get_user(self):
        return self.values['username']


register_mechanism('SCRAM-', 60, SCRAM_HMAC)
register_mechanism('SCRAM-', 70, SCRAM_HMAC, extra='-PLUS')