mod_privacy: Fix selecting the top resource (fixes #694)
[prosody.git] / util / sasl / digest-md5.lua
1 -- sasl.lua v0.4
2 -- Copyright (C) 2008-2010 Tobias Markmann
3 --
4 --    All rights reserved.
5 --
6 --    Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
7 --
8 --        * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
9 --        * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
10 --        * Neither the name of Tobias Markmann nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
11 --
12 --    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
13
14 local tostring = tostring;
15 local type = type;
16
17 local s_gmatch = string.gmatch;
18 local s_match = string.match;
19 local t_concat = table.concat;
20 local t_insert = table.insert;
21 local to_byte, to_char = string.byte, string.char;
22
23 local md5 = require "util.hashes".md5;
24 local log = require "util.logger".init("sasl");
25 local generate_uuid = require "util.uuid".generate;
26 local nodeprep = require "util.encodings".stringprep.nodeprep;
27
28 module "sasl.digest-md5"
29
30 --=========================
31 --SASL DIGEST-MD5 according to RFC 2831
32
33 --[[
34 Supported Authentication Backends
35
36 digest_md5:
37         function(username, domain, realm, encoding) -- domain and realm are usually the same; for some broken
38                                                                                                 -- implementations it's not
39                 return digesthash, state;
40         end
41
42 digest_md5_test:
43         function(username, domain, realm, encoding, digesthash)
44                 return true or false, state;
45         end
46 ]]
47
48 local function digest(self, message)
49         --TODO complete support for authzid
50
51         local function serialize(message)
52                 local data = ""
53
54                 -- testing all possible values
55                 if message["realm"] then data = data..[[realm="]]..message.realm..[[",]] end
56                 if message["nonce"] then data = data..[[nonce="]]..message.nonce..[[",]] end
57                 if message["qop"] then data = data..[[qop="]]..message.qop..[[",]] end
58                 if message["charset"] then data = data..[[charset=]]..message.charset.."," end
59                 if message["algorithm"] then data = data..[[algorithm=]]..message.algorithm.."," end
60                 if message["rspauth"] then data = data..[[rspauth=]]..message.rspauth.."," end
61                 data = data:gsub(",$", "")
62                 return data
63         end
64
65         local function utf8tolatin1ifpossible(passwd)
66                 local i = 1;
67                 while i <= #passwd do
68                         local passwd_i = to_byte(passwd:sub(i, i));
69                         if passwd_i > 0x7F then
70                                 if passwd_i < 0xC0 or passwd_i > 0xC3 then
71                                         return passwd;
72                                 end
73                                 i = i + 1;
74                                 passwd_i = to_byte(passwd:sub(i, i));
75                                 if passwd_i < 0x80 or passwd_i > 0xBF then
76                                         return passwd;
77                                 end
78                         end
79                         i = i + 1;
80                 end
81
82                 local p = {};
83                 local j = 0;
84                 i = 1;
85                 while (i <= #passwd) do
86                         local passwd_i = to_byte(passwd:sub(i, i));
87                         if passwd_i > 0x7F then
88                                 i = i + 1;
89                                 local passwd_i_1 = to_byte(passwd:sub(i, i));
90                                 t_insert(p, to_char(passwd_i%4*64 + passwd_i_1%64)); -- I'm so clever
91                         else
92                                 t_insert(p, to_char(passwd_i));
93                         end
94                         i = i + 1;
95                 end
96                 return t_concat(p);
97         end
98         local function latin1toutf8(str)
99                 local p = {};
100                 for ch in s_gmatch(str, ".") do
101                         ch = to_byte(ch);
102                         if (ch < 0x80) then
103                                 t_insert(p, to_char(ch));
104                         elseif (ch < 0xC0) then
105                                 t_insert(p, to_char(0xC2, ch));
106                         else
107                                 t_insert(p, to_char(0xC3, ch - 64));
108                         end
109                 end
110                 return t_concat(p);
111         end
112         local function parse(data)
113                 local message = {}
114                 -- COMPAT: %z in the pattern to work around jwchat bug (sends "charset=utf-8\0")
115                 for k, v in s_gmatch(data, [[([%w%-]+)="?([^",%z]*)"?,?]]) do -- FIXME The hacky regex makes me shudder
116                         message[k] = v;
117                 end
118                 return message;
119         end
120
121         if not self.nonce then
122                 self.nonce = generate_uuid();
123                 self.step = 0;
124                 self.nonce_count = {};
125         end
126
127         self.step = self.step + 1;
128         if (self.step == 1) then
129                 local challenge = serialize({   nonce = self.nonce,
130                                                                                 qop = "auth",
131                                                                                 charset = "utf-8",
132                                                                                 algorithm = "md5-sess",
133                                                                                 realm = self.realm});
134                 return "challenge", challenge;
135         elseif (self.step == 2) then
136                 local response = parse(message);
137                 -- check for replay attack
138                 if response["nc"] then
139                         if self.nonce_count[response["nc"]] then return "failure", "not-authorized" end
140                 end
141
142                 -- check for username, it's REQUIRED by RFC 2831
143                 local username = response["username"];
144                 local _nodeprep = self.profile.nodeprep;
145                 if username and _nodeprep ~= false then
146                         username = (_nodeprep or nodeprep)(username); -- FIXME charset
147                 end
148                 if not username or username == "" then
149                         return "failure", "malformed-request";
150                 end
151                 self.username = username;
152
153                 -- check for nonce, ...
154                 if not response["nonce"] then
155                         return "failure", "malformed-request";
156                 else
157                         -- check if it's the right nonce
158                         if response["nonce"] ~= tostring(self.nonce) then return "failure", "malformed-request" end
159                 end
160
161                 if not response["cnonce"] then return "failure", "malformed-request", "Missing entry for cnonce in SASL message." end
162                 if not response["qop"] then response["qop"] = "auth" end
163
164                 if response["realm"] == nil or response["realm"] == "" then
165                         response["realm"] = "";
166                 elseif response["realm"] ~= self.realm then
167                         return "failure", "not-authorized", "Incorrect realm value";
168                 end
169
170                 local decoder;
171                 if response["charset"] == nil then
172                         decoder = utf8tolatin1ifpossible;
173                 elseif response["charset"] ~= "utf-8" then
174                         return "failure", "incorrect-encoding", "The client's response uses "..response["charset"].." for encoding with isn't supported by sasl.lua. Supported encodings are latin or utf-8.";
175                 end
176
177                 local domain = "";
178                 local protocol = "";
179                 if response["digest-uri"] then
180                         protocol, domain = response["digest-uri"]:match("(%w+)/(.*)$");
181                         if protocol == nil or domain == nil then return "failure", "malformed-request" end
182                 else
183                         return "failure", "malformed-request", "Missing entry for digest-uri in SASL message."
184                 end
185
186                 --TODO maybe realm support
187                 local Y, state;
188                 if self.profile.plain then
189                         local password, state = self.profile.plain(self, response["username"], self.realm)
190                         if state == nil then return "failure", "not-authorized"
191                         elseif state == false then return "failure", "account-disabled" end
192                         Y = md5(response["username"]..":"..response["realm"]..":"..password);
193                 elseif self.profile["digest-md5"] then
194                         Y, state = self.profile["digest-md5"](self, response["username"], self.realm, response["realm"], response["charset"])
195                         if state == nil then return "failure", "not-authorized"
196                         elseif state == false then return "failure", "account-disabled" end
197                 elseif self.profile["digest-md5-test"] then
198                         -- TODO
199                 end
200                 --local password_encoding, Y = self.credentials_handler("DIGEST-MD5", response["username"], self.realm, response["realm"], decoder);
201                 --if Y == nil then return "failure", "not-authorized"
202                 --elseif Y == false then return "failure", "account-disabled" end
203                 local A1 = "";
204                 if response.authzid then
205                         if response.authzid == self.username or response.authzid == self.username.."@"..self.realm then
206                                 -- COMPAT
207                                 log("warn", "Client is violating RFC 3920 (section 6.1, point 7).");
208                                 A1 = Y..":"..response["nonce"]..":"..response["cnonce"]..":"..response.authzid;
209                         else
210                                 return "failure", "invalid-authzid";
211                         end
212                 else
213                         A1 = Y..":"..response["nonce"]..":"..response["cnonce"];
214                 end
215                 local A2 = "AUTHENTICATE:"..protocol.."/"..domain;
216
217                 local HA1 = md5(A1, true);
218                 local HA2 = md5(A2, true);
219
220                 local KD = HA1..":"..response["nonce"]..":"..response["nc"]..":"..response["cnonce"]..":"..response["qop"]..":"..HA2;
221                 local response_value = md5(KD, true);
222
223                 if response_value == response["response"] then
224                         -- calculate rspauth
225                         A2 = ":"..protocol.."/"..domain;
226
227                         HA1 = md5(A1, true);
228                         HA2 = md5(A2, true);
229
230                         KD = HA1..":"..response["nonce"]..":"..response["nc"]..":"..response["cnonce"]..":"..response["qop"]..":"..HA2
231                         local rspauth = md5(KD, true);
232                         self.authenticated = true;
233                         --TODO: considering sending the rspauth in a success node for saving one roundtrip; allowed according to http://tools.ietf.org/html/draft-saintandre-rfc3920bis-09#section-7.3.6
234                         return "challenge", serialize({rspauth = rspauth});
235                 else
236                         return "failure", "not-authorized", "The response provided by the client doesn't match the one we calculated."
237                 end
238         elseif self.step == 3 then
239                 if self.authenticated ~= nil then return "success"
240                 else return "failure", "malformed-request" end
241         end
242 end
243
244 function init(registerMechanism)
245         registerMechanism("DIGEST-MD5", {"plain"}, digest);
246 end
247
248 return _M;