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