fa818b9aaf198f46045a18fb8ae0d1a240895c7d
[prosody.git] / util / sasl.lua
1
2 local md5 = require "util.hashes".md5;
3 local log = require "util.logger".init("sasl");
4 local tostring = tostring;
5 local st = require "util.stanza";
6 local generate_uuid = require "util.uuid".generate;
7 local s_match = string.match;
8 local gmatch = string.gmatch
9 local string = string
10 local math = require "math"
11 local type = type
12 local error = error
13 local print = print
14 local idna_ascii = require "util.encodings".idna.to_ascii
15 local idna_unicode = require "util.encodings".idna.to_unicode
16
17 module "sasl"
18
19 local function new_plain(realm, password_handler)
20         local object = { mechanism = "PLAIN", realm = realm, password_handler = password_handler}
21         function object.feed(self, message)
22         
23                 if message == "" or message == nil then return "failure", "malformed-request" end
24                 local response = message
25                 local authorization = s_match(response, "([^&%z]+)")
26                 local authentication = s_match(response, "%z([^&%z]+)%z")
27                 local password = s_match(response, "%z[^&%z]+%z([^&%z]+)")
28                 
29                 if authentication == nil or password == nil then return "failure", "malformed-request" end
30                 
31                 local password_encoding, correct_password = self.password_handler(authentication, self.realm, "PLAIN")
32                 
33                 if correct_password == nil then return "failure", "not-authorized"
34                 elseif correct_password == false then return "failure", "account-disabled" end
35                 
36                 local claimed_password = ""
37                 if password_encoding == nil then claimed_password = password
38                 else claimed_password = password_encoding(password) end
39                 
40                 self.username = authentication
41                 if claimed_password == correct_password then
42                         return "success"
43                 else
44                         return "failure", "not-authorized"
45                 end
46         end
47         return object
48 end
49
50 local function new_digest_md5(realm, password_handler)
51         --TODO maybe support for authzid
52
53         local function serialize(message)
54                 local data = ""
55                 
56                 if type(message) ~= "table" then error("serialize needs an argument of type table.") end
57                 
58                 -- testing all possible values
59                 if message["nonce"] then data = data..[[nonce="]]..message.nonce..[[",]] end
60                 if message["qop"] then data = data..[[qop="]]..message.qop..[[",]] end
61                 if message["charset"] then data = data..[[charset=]]..message.charset.."," end
62                 if message["algorithm"] then data = data..[[algorithm=]]..message.algorithm.."," end
63                 if message["realm"] then data = data..[[realm="]]..message.realm..[[",]] end
64                 if message["rspauth"] then data = data..[[rspauth=]]..message.rspauth.."," end
65                 data = data:gsub(",$", "")
66                 return data
67         end
68         
69         local function parse(data)
70                 message = {}
71                 for k, v in gmatch(data, [[([%w%-]+)="?([^",]*)"?,?]]) do -- FIXME The hacky regex makes me shudder
72                         message[k] = v
73                 end
74                 return message
75         end
76
77         local object = { mechanism = "DIGEST-MD5", realm = realm, password_handler = password_handler}
78         
79         --TODO: something better than math.random would be nice, maybe OpenSSL's random number generator
80         object.nonce = generate_uuid()
81         object.step = 0
82         object.nonce_count = {}
83                                                                                                 
84         function object.feed(self, message)
85                 self.step = self.step + 1
86                 if (self.step == 1) then
87                         local challenge = serialize({   nonce = object.nonce, 
88                                                                                         qop = "auth",
89                                                                                         charset = "utf-8",
90                                                                                         algorithm = "md5-sess",
91                                                                                         realm = idna_ascii(self.realm)});
92                         return "challenge", challenge
93                 elseif (self.step == 2) then
94                         local response = parse(message)
95                         -- check for replay attack
96                         if response["nc"] then
97                                 if self.nonce_count[response["nc"]] then return "failure", "not-authorized" end
98                         end
99                         
100                         -- check for username, it's REQUIRED by RFC 2831
101                         if not response["username"] then
102                                 return "failure", "malformed-request"
103                         end
104                         self["username"] = response["username"] 
105                         
106                         -- check for nonce, ...
107                         if not response["nonce"] then
108                                 return "failure", "malformed-request"
109                         else
110                                 -- check if it's the right nonce
111                                 if response["nonce"] ~= tostring(self.nonce) then return "failure", "malformed-request" end
112                         end
113                         
114                         if not response["cnonce"] then return "failure", "malformed-request", "Missing entry for cnonce in SASL message." end
115                         if not response["qop"] then response["qop"] = "auth" end
116                         
117                         if response["realm"] == nil then response["realm"] = "" end
118                         
119                         local domain = ""
120                         local protocol = ""
121                         if response["digest-uri"] then
122                                 protocol, domain = response["digest-uri"]:match("(%w+)/(.*)$")
123                                 if protocol == nil or domain == nil then return "failure", "malformed-request" end
124                         else
125                                 return "failure", "malformed-request", "Missing entry for digest-uri in SASL message."
126                         end
127                         
128                         --TODO maybe realm support
129                         self.username = response["username"]
130                         local password_encoding, Y = self.password_handler(response["username"], idna_unicode(response["realm"]), "DIGEST-MD5")
131                         if Y == nil then return "failure", "not-authorized"
132                         elseif Y == false then return "failure", "account-disabled" end
133                         
134                         local A1 = Y..":"..response["nonce"]..":"..response["cnonce"]--:authzid
135                         local A2 = "AUTHENTICATE:"..protocol.."/"..idna_ascii(domain)
136                         
137                         local HA1 = md5(A1, true)
138                         local HA2 = md5(A2, true)
139                         
140                         local KD = HA1..":"..response["nonce"]..":"..response["nc"]..":"..response["cnonce"]..":"..response["qop"]..":"..HA2
141                         local response_value = md5(KD, true)
142                         
143                         if response_value == response["response"] then
144                                 -- calculate rspauth
145                                 A2 = ":"..protocol.."/"..idna_ascii(domain)
146                                 
147                                 HA1 = md5(A1, true)
148                                 HA2 = md5(A2, true)
149         
150                                 KD = HA1..":"..response["nonce"]..":"..response["nc"]..":"..response["cnonce"]..":"..response["qop"]..":"..HA2
151                                 local rspauth = md5(KD, true)
152                                 self.authenticated = true
153                                 return "challenge", serialize({rspauth = rspauth})
154                         else
155                                 return "failure", "not-authorized", "The response provided by the client doesn't match the one we calculated."
156                         end                                                     
157                 elseif self.step == 3 then
158                         if self.authenticated ~= nil then return "success"
159                         else return "failure", "malformed-request" end
160                 end
161         end
162         return object
163 end
164
165 function new(mechanism, realm, password_handler)
166         local object
167         if mechanism == "PLAIN" then object = new_plain(realm, password_handler)
168         elseif mechanism == "DIGEST-MD5" then object = new_digest_md5(realm, password_handler)
169         else
170                 log("debug", "Unsupported SASL mechanism: "..tostring(mechanism));
171                 return nil
172         end
173         return object
174 end
175
176 return _M;