From 07e0d852f589325e95245f0bf6e65de7208afbb0 Mon Sep 17 00:00:00 2001
From: Tobias Markmann <tm@ayena.de>
Date: Sun, 9 Nov 2008 21:16:57 +0100
Subject: Some early attempts on DIGEST-MD5.

---
 util/sasl.lua | 146 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
 1 file changed, 144 insertions(+), 2 deletions(-)

diff --git a/util/sasl.lua b/util/sasl.lua
index dbd6326a..ef1009c2 100644
--- a/util/sasl.lua
+++ b/util/sasl.lua
@@ -1,16 +1,23 @@
 
 local base64 = require "base64"
+local md5 = require "md5"
+local crypto = require "crypto"
 local log = require "util.logger".init("sasl");
 local tostring = tostring;
 local st = require "util.stanza";
+local generate_uuid = require "util.uuid".generate;
 local s_match = string.match;
-module "sasl"
+local math = require "math"
+local type = type
+local error = error
+local print = print
 
+module "sasl"
 
 local function new_plain(onAuth, onSuccess, onFail, onWrite)
 	local object = { mechanism = "PLAIN", onAuth = onAuth, onSuccess = onSuccess, onFail = onFail,
 	 				onWrite = onWrite}
-	--local challenge = base64.encode("");
+	local challenge = base64.encode("");
 	--onWrite(st.stanza("challenge", {xmlns = "urn:ietf:params:xml:ns:xmpp-sasl"}):text(challenge))
 	object.feed = 	function(self, stanza)
 						if stanza.name ~= "response" and stanza.name ~= "auth" then self.onFail("invalid-stanza-tag") end
@@ -30,9 +37,144 @@ local function new_plain(onAuth, onSuccess, onFail, onWrite)
 end
 
 
+--[[
+SERVER:
+nonce="3145176401",qop="auth",charset=utf-8,algorithm=md5-sess
+
+CLIENT: username="tobiasfar",nonce="3145176401",cnonce="pJiW7hzeZLvOSAf7gBzwTzLWe4obYOVDlnNESzQCzGg=",nc=00000001,digest-uri="xmpp/jabber.org",qop=auth,response=99a93ba75235136e6403c3a2ba37089d,charset=utf-8	
+
+username="tobias",nonce="4406697386",cnonce="wUnT7vYrOB0V8D/lKd5bhpaNCk+hLJwc8T4CBCqp7WM=",nc=00000001,digest-uri="xmpp/luaetta.ath.cx",qop=auth,response=d202b8a1bdf8204816fb23c5f87b6b63,charset=utf-8
+
+SERVER:
+rspauth=ab66d28c260e97da577ce3aac46a8991
+]]--
+local function new_digest_md5(onAuth, onSuccess, onFail, onWrite)
+	local function H(s)
+		return md5.sum(s)
+	end
+	
+	local function KD(k, s)
+		return H(k..":"..s)
+	end
+	
+	local function HEX(n)
+		return md5.sumhexa(n)
+	end
+
+	local function HMAC(k, s)
+		return crypto.hmac.digest("md5", s, k, true)
+	end
+
+	local function serialize(message)
+		local data = ""
+		
+		if type(message) ~= "table" then error("serialize needs an argument of type table.") end
+		
+		-- testing all possible values
+		if message["nonce"] then data = data..[[nonce="]]..message.nonce..[[",]] end
+		if message["qop"] then data = data..[[qop="]]..message.qop..[[",]] end
+		if message["charset"] then data = data..[[charset=]]..message.charset.."," end
+		if message["algorithm"] then data = data..[[algorithm=]]..message.algorithm.."," end
+		if message["rspauth"] then data = data..[[rspauth=]]..message.algorith.."," end
+		data = data:gsub(",$", "")
+		return data
+	end
+	
+	local function parse(data)
+		message = {}
+		for k, v in string.gmatch(data, [[([%w%-])="?[%w%-]"?,?]]) do
+			message[k] = v
+		end
+		return message
+	end
+
+	local object = { mechanism = "DIGEST-MD5", onAuth = onAuth, onSuccess = onSuccess, onFail = onFail,
+	 				onWrite = onWrite }
+	
+	--TODO: something better than math.random would be nice, maybe OpenSSL's random number generator
+	object.nonce = math.random(0, 9)
+	for i = 1, 9 do object.nonce = object.nonce..math.random(0, 9) end
+	object.step = 1
+	object.nonce_count = {}
+	local challenge = base64.encode(serialize({	nonce = object.nonce, 
+												qop = "auth",
+												charset = "utf-8",
+												algorithm = "md5-sess"} ));
+	object.onWrite(st.stanza("challenge", {xmlns = "urn:ietf:params:xml:ns:xmpp-sasl"}):text(challenge))
+	object.feed = 	function(self, stanza)
+						print(tostring(stanza))
+						if stanza.name ~= "response" and stanza.name ~= "auth" then self.onFail("invalid-stanza-tag") end
+						if stanza.attr.xmlns ~= "urn:ietf:params:xml:ns:xmpp-sasl" then self.onFail("invalid-stanza-namespace") end
+						if stanza.name == "auth" then return end
+						self.step = self.step + 1
+						if (self.step == 2) then
+							
+							log("debug", tostring(stanza[1]))
+							local response = parse(base64.decode(stanza[1]))
+							-- check for replay attack
+							if response["nonce-count"] then
+								if self.nonce_count[response["nonce-count"]] then self.onFail("not-authorized") end
+							end
+							
+							-- check for username, it's REQUIRED by RFC 2831
+							if not response["username"] then
+								self.onFail("malformed-request")
+							end
+							
+							-- check for nonce, ...
+							if not response["nonce"] then
+								self.onFail("malformed-request")
+							else
+								-- check if it's the right nonce
+								if response["nonce"] ~= self.nonce then self.onFail("malformed-request") end
+							end
+							
+							if not response["cnonce"] then self.onFail("malformed-request") end
+							if not response["qop"] then response["qop"] = "auth" end
+							
+							local hostname = ""
+							if response["digest-uri"] then
+								local uri = response["digest-uri"]:gmatch("^(%w)/(%w)")
+								local protocol = uri[1]
+								log(protocol)
+								local hostname = uri[2]
+								log(hostname)
+							end
+														
+							-- compare response_value with own calculation
+							local A1-- = H(response["username"]..":"..realm-value, ":", passwd } ),
+							        --   ":", nonce-value, ":", cnonce-value)
+							local A2
+							
+							local response_value = HEX(KD(HEX(H(A1)), response["nonce"]..":"..response["nonce-count"]..":"..response["cnonce-value"]..":"..response["qop"]..":"..HEX(H(A2))))
+							
+							if response["qop"] == "auth" then
+							
+							else
+							
+							end
+							
+							local response_value = HEX(KD(HEX(H(A1)), response["nonce"]..":"..response["nonce-count"]..":"..response["cnonce-value"]..":"..response["qop"]..":"..HEX(H(A2))))
+							
+						end
+						--[[
+						local authorization = s_match(response, "([^&%z]+)")
+						local authentication = s_match(response, "%z([^&%z]+)%z")
+						local password = s_match(response, "%z[^&%z]+%z([^&%z]+)")
+						if self.onAuth(authentication, password) == true then
+							self.onWrite(st.stanza("success", {xmlns = "urn:ietf:params:xml:ns:xmpp-sasl"}))
+							self.onSuccess(authentication)
+						else
+							self.onWrite(st.stanza("failure", {xmlns = "urn:ietf:params:xml:ns:xmpp-sasl"}):tag("temporary-auth-failure"));
+						end]]--
+					end
+	return object
+end
+
 function new(mechanism, onAuth, onSuccess, onFail, onWrite)
 	local object
 	if mechanism == "PLAIN" then object = new_plain(onAuth, onSuccess, onFail, onWrite)
+	elseif mechanism == "DIGEST-MD5" then object = new_digest_md5(onAuth, onSuccess, onFail, onWrite)
 	else
 		log("debug", "Unsupported SASL mechanism: "..tostring(mechanism));
 		onFail("unsupported-mechanism")
-- 
cgit v1.2.3


From 346b695b798ac36147be7d47f3dfb7a946776358 Mon Sep 17 00:00:00 2001
From: Tobias Markmann <tm@ayena.de>
Date: Sun, 9 Nov 2008 22:45:17 +0100
Subject: Fixing some parsing and some other stuff.

---
 util/sasl.lua | 19 ++++++++-----------
 1 file changed, 8 insertions(+), 11 deletions(-)

diff --git a/util/sasl.lua b/util/sasl.lua
index ef1009c2..7a0e47b8 100644
--- a/util/sasl.lua
+++ b/util/sasl.lua
@@ -7,6 +7,7 @@ local tostring = tostring;
 local st = require "util.stanza";
 local generate_uuid = require "util.uuid".generate;
 local s_match = string.match;
+local gmatch = string.gmatch
 local math = require "math"
 local type = type
 local error = error
@@ -82,7 +83,7 @@ local function new_digest_md5(onAuth, onSuccess, onFail, onWrite)
 	
 	local function parse(data)
 		message = {}
-		for k, v in string.gmatch(data, [[([%w%-])="?[%w%-]"?,?]]) do
+		for k, v in gmatch(data, [[([%w%-]+)="?([%w%-%/%.]+)"?,?]]) do
 			message[k] = v
 		end
 		return message
@@ -102,14 +103,11 @@ local function new_digest_md5(onAuth, onSuccess, onFail, onWrite)
 												algorithm = "md5-sess"} ));
 	object.onWrite(st.stanza("challenge", {xmlns = "urn:ietf:params:xml:ns:xmpp-sasl"}):text(challenge))
 	object.feed = 	function(self, stanza)
-						print(tostring(stanza))
 						if stanza.name ~= "response" and stanza.name ~= "auth" then self.onFail("invalid-stanza-tag") end
 						if stanza.attr.xmlns ~= "urn:ietf:params:xml:ns:xmpp-sasl" then self.onFail("invalid-stanza-namespace") end
 						if stanza.name == "auth" then return end
 						self.step = self.step + 1
 						if (self.step == 2) then
-							
-							log("debug", tostring(stanza[1]))
 							local response = parse(base64.decode(stanza[1]))
 							-- check for replay attack
 							if response["nonce-count"] then
@@ -133,12 +131,11 @@ local function new_digest_md5(onAuth, onSuccess, onFail, onWrite)
 							if not response["qop"] then response["qop"] = "auth" end
 							
 							local hostname = ""
+							local protocol = ""
 							if response["digest-uri"] then
-								local uri = response["digest-uri"]:gmatch("^(%w)/(%w)")
-								local protocol = uri[1]
-								log(protocol)
-								local hostname = uri[2]
-								log(hostname)
+								protocol, hostname = response["digest-uri"]:match("(%w+)/(.*)$")
+							else
+								error("No digest-uri")
 							end
 														
 							-- compare response_value with own calculation
@@ -146,7 +143,7 @@ local function new_digest_md5(onAuth, onSuccess, onFail, onWrite)
 							        --   ":", nonce-value, ":", cnonce-value)
 							local A2
 							
-							local response_value = HEX(KD(HEX(H(A1)), response["nonce"]..":"..response["nonce-count"]..":"..response["cnonce-value"]..":"..response["qop"]..":"..HEX(H(A2))))
+							--local response_value = HEX(KD(HEX(H(A1)), response["nonce"]..":"..response["nonce-count"]..":"..response["cnonce-value"]..":"..response["qop"]..":"..HEX(H(A2))))
 							
 							if response["qop"] == "auth" then
 							
@@ -154,7 +151,7 @@ local function new_digest_md5(onAuth, onSuccess, onFail, onWrite)
 							
 							end
 							
-							local response_value = HEX(KD(HEX(H(A1)), response["nonce"]..":"..response["nonce-count"]..":"..response["cnonce-value"]..":"..response["qop"]..":"..HEX(H(A2))))
+							--local response_value = HEX(KD(HEX(H(A1)), response["nonce"]..":"..response["nonce-count"]..":"..response["cnonce-value"]..":"..response["qop"]..":"..HEX(H(A2))))
 							
 						end
 						--[[
-- 
cgit v1.2.3


From c4d2deffc64a4d955e52d7e8b2dce3af444872c7 Mon Sep 17 00:00:00 2001
From: Tobias Markmann <tm@ayena.de>
Date: Mon, 10 Nov 2008 16:28:15 +0100
Subject: Forward response stanzas to sasl.lua and some other stuff.

---
 plugins/mod_saslauth.lua | 79 +++++++++++++++++++++++++-----------------------
 util/sasl.lua            | 10 +++---
 2 files changed, 48 insertions(+), 41 deletions(-)

diff --git a/plugins/mod_saslauth.lua b/plugins/mod_saslauth.lua
index 24c82a1c..4f4f29d4 100644
--- a/plugins/mod_saslauth.lua
+++ b/plugins/mod_saslauth.lua
@@ -15,50 +15,55 @@ local xmlns_stanzas ='urn:ietf:params:xml:ns:xmpp-stanzas';
 
 local new_sasl = require "util.sasl".new;
 
-add_handler("c2s_unauthed", "auth", xmlns_sasl,
-		function (session, stanza)
-			if not session.sasl_handler then
-				session.sasl_handler = new_sasl(stanza.attr.mechanism, 
-					function (username, password)
-						-- onAuth
-						require "core.usermanager"
-						if usermanager_validate_credentials(session.host, username, password) then
-							return true;
-						end
-						return false;
-					end,
-					function (username)
-						-- onSuccess
-						local success, err = sessionmanager.make_authenticated(session, username);
-						if not success then
-							sessionmanager.destroy_session(session);
-							return;
-						end
-						session.sasl_handler = nil;
-						session:reset_stream();
-					end,
-					function (reason)
-						-- onFail
-						log("debug", "SASL failure, reason: %s", reason);
-					end,
-					function (stanza)
-						-- onWrite
-						log("debug", "SASL writes: %s", tostring(stanza));
-						send(session, stanza);
-					end
-				);
-				session.sasl_handler:feed(stanza);	
-			else
-				error("Client tried to negotiate SASL again", 0);
+add_handler("c2s_unauthed", "auth", xmlns_sasl, function (session, stanza)
+	if not session.sasl_handler then
+		session.sasl_handler = new_sasl(stanza.attr.mechanism, 
+			function (username, password)
+				-- onAuth
+				require "core.usermanager"
+				if usermanager_validate_credentials(session.host, username, password) then
+					return true;
+				end
+				return false;
+			end,
+			function (username)
+				-- onSuccess
+				local success, err = sessionmanager.make_authenticated(session, username);
+				if not success then
+					sessionmanager.destroy_session(session);
+					return;
+				end
+				session.sasl_handler = nil;
+				session:reset_stream();
+			end,
+			function (reason)
+				-- onFail
+				log("debug", "SASL failure, reason: %s", reason);
+			end,
+			function (stanza)
+				-- onWrite
+				log("debug", "SASL writes: %s", tostring(stanza));
+				send(session, stanza);
 			end
-			
-		end);
+		);
+		session.sasl_handler:feed(stanza);	
+	else
+		error("Client tried to negotiate SASL again", 0);
+	end	
+end);
+
+add_handler("c2s_unauthed", "response", xmlns_sasl, function (session, stanza)
+	if session.sasl_handler then
+		session.sasl_handler:feed(stanza);	
+	end	
+end);
 		
 add_event_hook("stream-features", 
 					function (session, features)												
 						if not session.username then
 							t_insert(features, "<mechanisms xmlns='urn:ietf:params:xml:ns:xmpp-sasl'>");
 								t_insert(features, "<mechanism>PLAIN</mechanism>");
+								t_insert(features, "<mechanism>DIGEST-MD5</mechanism>");
 							t_insert(features, "</mechanisms>");
 						else
 							t_insert(features, "<bind xmlns='urn:ietf:params:xml:ns:xmpp-bind'><required/></bind>");
diff --git a/util/sasl.lua b/util/sasl.lua
index 7a0e47b8..f2ff6592 100644
--- a/util/sasl.lua
+++ b/util/sasl.lua
@@ -139,11 +139,13 @@ local function new_digest_md5(onAuth, onSuccess, onFail, onWrite)
 							end
 														
 							-- compare response_value with own calculation
-							local A1-- = H(response["username"]..":"..realm-value, ":", passwd } ),
-							        --   ":", nonce-value, ":", cnonce-value)
-							local A2
+							--local A1 = usermanager.get_md5(response["username"], hostname)..":"..response["nonce"]..response["cnonce"]
+							local A1 = H("tobias:luaetta.ath.cx:tobias")..":"..response["nonce"]..response["cnonce"]
+							local A2 = "AUTHENTICATE:"..response["digest-uri"]
 							
-							--local response_value = HEX(KD(HEX(H(A1)), response["nonce"]..":"..response["nonce-count"]..":"..response["cnonce-value"]..":"..response["qop"]..":"..HEX(H(A2))))
+							local response_value = HEX(KD(HEX(H(A1)), response["nonce"]..":"..response["nonce-count"]..":"..response["cnonce-value"]..":"..response["qop"]..":"..HEX(H(A2))))
+							
+							log("debug", "response_value: "..response_value);
 							
 							if response["qop"] == "auth" then
 							
-- 
cgit v1.2.3


From 18e785078a2edf69bf4ec728290a18de2ed28cd7 Mon Sep 17 00:00:00 2001
From: Tobias Markmann <tm@ayena.de>
Date: Wed, 12 Nov 2008 21:38:46 +0100
Subject: Rewrote SASL Digest-MD5 responce generating code, fixed some realm
 related issue and tested it successfully with Psi. Thanks to dwd, remko and
 jake.

---
 util/sasl.lua | 105 ++++++++++++++++++++++++++++------------------------------
 1 file changed, 50 insertions(+), 55 deletions(-)

diff --git a/util/sasl.lua b/util/sasl.lua
index f2ff6592..1f4eff54 100644
--- a/util/sasl.lua
+++ b/util/sasl.lua
@@ -8,6 +8,7 @@ local st = require "util.stanza";
 local generate_uuid = require "util.uuid".generate;
 local s_match = string.match;
 local gmatch = string.gmatch
+local string = string
 local math = require "math"
 local type = type
 local error = error
@@ -32,39 +33,14 @@ local function new_plain(onAuth, onSuccess, onFail, onWrite)
 							self.onSuccess(authentication)
 						else
 							self.onWrite(st.stanza("failure", {xmlns = "urn:ietf:params:xml:ns:xmpp-sasl"}):tag("temporary-auth-failure"));
+							self.onFail("Wrong password.")
 						end
 					end
 	return object
 end
 
-
---[[
-SERVER:
-nonce="3145176401",qop="auth",charset=utf-8,algorithm=md5-sess
-
-CLIENT: username="tobiasfar",nonce="3145176401",cnonce="pJiW7hzeZLvOSAf7gBzwTzLWe4obYOVDlnNESzQCzGg=",nc=00000001,digest-uri="xmpp/jabber.org",qop=auth,response=99a93ba75235136e6403c3a2ba37089d,charset=utf-8	
-
-username="tobias",nonce="4406697386",cnonce="wUnT7vYrOB0V8D/lKd5bhpaNCk+hLJwc8T4CBCqp7WM=",nc=00000001,digest-uri="xmpp/luaetta.ath.cx",qop=auth,response=d202b8a1bdf8204816fb23c5f87b6b63,charset=utf-8
-
-SERVER:
-rspauth=ab66d28c260e97da577ce3aac46a8991
-]]--
 local function new_digest_md5(onAuth, onSuccess, onFail, onWrite)
-	local function H(s)
-		return md5.sum(s)
-	end
-	
-	local function KD(k, s)
-		return H(k..":"..s)
-	end
-	
-	local function HEX(n)
-		return md5.sumhexa(n)
-	end
-
-	local function HMAC(k, s)
-		return crypto.hmac.digest("md5", s, k, true)
-	end
+	--TODO maybe support for authzid
 
 	local function serialize(message)
 		local data = ""
@@ -76,15 +52,18 @@ local function new_digest_md5(onAuth, onSuccess, onFail, onWrite)
 		if message["qop"] then data = data..[[qop="]]..message.qop..[[",]] end
 		if message["charset"] then data = data..[[charset=]]..message.charset.."," end
 		if message["algorithm"] then data = data..[[algorithm=]]..message.algorithm.."," end
-		if message["rspauth"] then data = data..[[rspauth=]]..message.algorith.."," end
+		if message["realm"] then data = data..[[realm="]]..message.realm..[[",]] end
+		if message["rspauth"] then data = data..[[rspauth=]]..message.rspauth.."," end
 		data = data:gsub(",$", "")
 		return data
 	end
 	
 	local function parse(data)
 		message = {}
-		for k, v in gmatch(data, [[([%w%-]+)="?([%w%-%/%.]+)"?,?]]) do
+		log("debug", "parse-message: "..data)
+		for k, v in gmatch(data, [[([%w%-]+)="?([%w%-%/%.%+=]+)"?,?]]) do
 			message[k] = v
+		log("debug", "               "..k.." = "..v)
 		end
 		return message
 	end
@@ -93,8 +72,8 @@ local function new_digest_md5(onAuth, onSuccess, onFail, onWrite)
 	 				onWrite = onWrite }
 	
 	--TODO: something better than math.random would be nice, maybe OpenSSL's random number generator
-	object.nonce = math.random(0, 9)
-	for i = 1, 9 do object.nonce = object.nonce..math.random(0, 9) end
+	object.nonce = generate_uuid()
+	log("debug", "SASL nonce: "..object.nonce)
 	object.step = 1
 	object.nonce_count = {}
 	local challenge = base64.encode(serialize({	nonce = object.nonce, 
@@ -103,6 +82,7 @@ local function new_digest_md5(onAuth, onSuccess, onFail, onWrite)
 												algorithm = "md5-sess"} ));
 	object.onWrite(st.stanza("challenge", {xmlns = "urn:ietf:params:xml:ns:xmpp-sasl"}):text(challenge))
 	object.feed = 	function(self, stanza)
+						log("debug", "SASL step: "..self.step)
 						if stanza.name ~= "response" and stanza.name ~= "auth" then self.onFail("invalid-stanza-tag") end
 						if stanza.attr.xmlns ~= "urn:ietf:params:xml:ns:xmpp-sasl" then self.onFail("invalid-stanza-namespace") end
 						if stanza.name == "auth" then return end
@@ -110,62 +90,77 @@ local function new_digest_md5(onAuth, onSuccess, onFail, onWrite)
 						if (self.step == 2) then
 							local response = parse(base64.decode(stanza[1]))
 							-- check for replay attack
-							if response["nonce-count"] then
-								if self.nonce_count[response["nonce-count"]] then self.onFail("not-authorized") end
+							if response["nc"] then
+								if self.nonce_count[response["nc"]] then self.onFail("not-authorized") end
 							end
 							
 							-- check for username, it's REQUIRED by RFC 2831
 							if not response["username"] then
 								self.onFail("malformed-request")
 							end
+							self["username"] = response["username"] 
 							
 							-- check for nonce, ...
 							if not response["nonce"] then
 								self.onFail("malformed-request")
 							else
 								-- check if it's the right nonce
-								if response["nonce"] ~= self.nonce then self.onFail("malformed-request") end
+								if response["nonce"] ~= tostring(self.nonce) then self.onFail("malformed-request") end
 							end
 							
 							if not response["cnonce"] then self.onFail("malformed-request") end
 							if not response["qop"] then response["qop"] = "auth" end
 							
-							local hostname = ""
+							if response["realm"] == nil then response["realm"] = "" end
+							
+							local domain = ""
 							local protocol = ""
 							if response["digest-uri"] then
-								protocol, hostname = response["digest-uri"]:match("(%w+)/(.*)$")
+								protocol, domain = response["digest-uri"]:match("(%w+)/(.*)$")
 							else
 								error("No digest-uri")
 							end
 														
 							-- compare response_value with own calculation
 							--local A1 = usermanager.get_md5(response["username"], hostname)..":"..response["nonce"]..response["cnonce"]
-							local A1 = H("tobias:luaetta.ath.cx:tobias")..":"..response["nonce"]..response["cnonce"]
-							local A2 = "AUTHENTICATE:"..response["digest-uri"]
 							
-							local response_value = HEX(KD(HEX(H(A1)), response["nonce"]..":"..response["nonce-count"]..":"..response["cnonce-value"]..":"..response["qop"]..":"..HEX(H(A2))))
+							--FIXME actual username and password here :P
+							local X = "tobias:"..response["realm"]..":tobias"
+							local Y = md5.sum(X)
+							local A1 = Y..":"..response["nonce"]..":"..response["cnonce"]--:authzid
+							local A2 = "AUTHENTICATE:"..protocol.."/"..domain
 							
-							log("debug", "response_value: "..response_value);
+							local HA1 = md5.sumhexa(A1)
+							local HA2 = md5.sumhexa(A2)
 							
-							if response["qop"] == "auth" then
+							local KD = HA1..":"..response["nonce"]..":"..response["nc"]..":"..response["cnonce"]..":"..response["qop"]..":"..HA2
+							local response_value = md5.sumhexa(KD)
 							
+							log("debug", "response_value: "..response_value);
+							log("debug", "response:       "..response["response"]);
+							if response_value == response["response"] then
+								-- calculate rspauth
+								A2 = ":"..protocol.."/"..domain
+								
+								HA1 = md5.sumhexa(A1)
+								HA2 = md5.sumhexa(A2)
+
+								KD = HA1..":"..response["nonce"]..":"..response["nc"]..":"..response["cnonce"]..":"..response["qop"]..":"..HA2
+								local rspauth = md5.sumhexa(KD)
+								
+								self.onWrite(st.stanza("challenge", {xmlns = "urn:ietf:params:xml:ns:xmpp-sasl"}):text(base64.encode(serialize({rspauth = rspauth}))))
 							else
-							
+								self.onWrite(st.stanza("response", {xmlns = "urn:ietf:params:xml:ns:xmpp-sasl"}))
+								self.onFail()
+							end							
+						elseif self.step == 3 then
+							if stanza.name == "response" then 
+								self.onWrite(st.stanza("success", {xmlns = "urn:ietf:params:xml:ns:xmpp-sasl"}))
+								self.onSuccess(self.username)
+							else 
+								self.onFail("Third step isn't a response stanza.")
 							end
-							
-							--local response_value = HEX(KD(HEX(H(A1)), response["nonce"]..":"..response["nonce-count"]..":"..response["cnonce-value"]..":"..response["qop"]..":"..HEX(H(A2))))
-							
 						end
-						--[[
-						local authorization = s_match(response, "([^&%z]+)")
-						local authentication = s_match(response, "%z([^&%z]+)%z")
-						local password = s_match(response, "%z[^&%z]+%z([^&%z]+)")
-						if self.onAuth(authentication, password) == true then
-							self.onWrite(st.stanza("success", {xmlns = "urn:ietf:params:xml:ns:xmpp-sasl"}))
-							self.onSuccess(authentication)
-						else
-							self.onWrite(st.stanza("failure", {xmlns = "urn:ietf:params:xml:ns:xmpp-sasl"}):tag("temporary-auth-failure"));
-						end]]--
 					end
 	return object
 end
-- 
cgit v1.2.3


From aefcb845c34c7bf15a370812b28b5da27fbc983b Mon Sep 17 00:00:00 2001
From: Waqas Hussain <waqas20@gmail.com>
Date: Sat, 15 Nov 2008 12:21:04 +0500
Subject: mod_saslauth updated for digest-md5

---
 plugins/mod_saslauth.lua | 63 +++++++++++++++++++++++++++++++++++++++++++++---
 1 file changed, 60 insertions(+), 3 deletions(-)

diff --git a/plugins/mod_saslauth.lua b/plugins/mod_saslauth.lua
index 24c82a1c..d8e27c4f 100644
--- a/plugins/mod_saslauth.lua
+++ b/plugins/mod_saslauth.lua
@@ -2,6 +2,7 @@
 local st = require "util.stanza";
 local send = require "core.sessionmanager".send_to_session;
 local sm_bind_resource = require "core.sessionmanager".bind_resource;
+local jid
 
 local usermanager_validate_credentials = require "core.usermanager".validate_credentials;
 local t_concat, t_insert = table.concat, table.insert;
@@ -15,10 +16,51 @@ local xmlns_stanzas ='urn:ietf:params:xml:ns:xmpp-stanzas';
 
 local new_sasl = require "util.sasl".new;
 
+local function build_reply(status, ret)
+	local reply = st.stanza(status, {xmlns = xmlns_sasl});
+	if status == "challenge" then
+		reply:text(ret or "");
+	elseif status == "failure" then
+		reply:tag(ret):up();
+	elseif status == "success" then
+		reply:text(ret or "");
+	else
+		error("Unknown sasl status: "..status);
+	end
+	return reply;
+end
+
+local function handle_status(session, status)
+	if status == "failure" then
+		session.sasl_handler = nil;
+	elseif status == "success" then
+		session.sasl_handler = nil;
+		session:reset_stream();
+	end
+end
+
+local function password_callback(jid, mechanism)
+	local node, host = jid_split(jid);
+	local password = (datamanager.load(node, host, "accounts") or {}).password; -- FIXME handle hashed passwords
+	local func = function(x) return x; end;
+	if password then
+		if mechanism == "PLAIN" then
+			return func, password;
+		elseif mechanism == "DIGEST-MD5" then
+			return func, require "hashes".md5(node.."::"..password);
+		end
+	end
+	return func, nil;
+end
+
 add_handler("c2s_unauthed", "auth", xmlns_sasl,
 		function (session, stanza)
 			if not session.sasl_handler then
-				session.sasl_handler = new_sasl(stanza.attr.mechanism, 
+				session.sasl_handler = new_sasl(stanza.attr.mechanism, session.host, password_callback);
+				local status, ret = session.sasl_handler:feed(stanza[1]);
+				handle_status(session, status);
+				session.send(build_reply(status, ret));
+				--[[session.sasl_handler = new_sasl(stanza.attr.mechanism, 
 					function (username, password)
 						-- onAuth
 						require "core.usermanager"
@@ -47,12 +89,27 @@ add_handler("c2s_unauthed", "auth", xmlns_sasl,
 						send(session, stanza);
 					end
 				);
-				session.sasl_handler:feed(stanza);	
+				session.sasl_handler:feed(stanza);	]]
 			else
 				error("Client tried to negotiate SASL again", 0);
 			end
-			
 		end);
+
+add_handler("c2s_unauthed", "abort", xmlns_sasl,
+	function(session, stanza)
+		if not session.sasl_handler then error("Attempt to abort when sasl has not started"); end
+		local status, ret = session.sasl_handler:feed(stanza[1]);
+		handle_status(session, status);
+		session.send(build_reply(status, ret));
+	end);
+
+add_handler("c2s_unauthed", "response", xmlns_sasl,
+	function(session, stanza)
+		if not session.sasl_handler then error("Attempt to respond when sasl has not started"); end
+		local status, ret = session.sasl_handler:feed(stanza[1]);
+		handle_status(session, status);
+		session.send(build_reply(status, ret));
+	end);
 		
 add_event_hook("stream-features", 
 					function (session, features)												
-- 
cgit v1.2.3


From 72e415f8233f2a67f2296b6061618ca5269df593 Mon Sep 17 00:00:00 2001
From: Tobias Markmann <tm@ayena.de>
Date: Sat, 15 Nov 2008 19:12:05 +0100
Subject: Adding some TODO for some security issue.

---
 plugins/mod_saslauth.lua | 1 +
 1 file changed, 1 insertion(+)

diff --git a/plugins/mod_saslauth.lua b/plugins/mod_saslauth.lua
index dd268555..6b945bfc 100644
--- a/plugins/mod_saslauth.lua
+++ b/plugins/mod_saslauth.lua
@@ -115,6 +115,7 @@ add_event_hook("stream-features",
 					function (session, features)												
 						if not session.username then
 							t_insert(features, "<mechanisms xmlns='urn:ietf:params:xml:ns:xmpp-sasl'>");
+							-- TODO: Provide PLAIN only if TLS is active, this is a SHOULD from the introduction of RFC 4616. This behavior could be overridden via configuration but will issuing a warning or so.
 								t_insert(features, "<mechanism>PLAIN</mechanism>");
 								t_insert(features, "<mechanism>DIGEST-MD5</mechanism>");
 							t_insert(features, "</mechanisms>");
-- 
cgit v1.2.3


From 9245e20027736cfdd2d53fa78502f25fe4205eb8 Mon Sep 17 00:00:00 2001
From: Waqas Hussain <waqas20@gmail.com>
Date: Sat, 15 Nov 2008 23:20:07 +0500
Subject: mod_saslauth: Added base64 decoding, encoding check, and cleaned the
 code up.

---
 plugins/mod_saslauth.lua | 59 ++++++++++++++++--------------------------------
 1 file changed, 19 insertions(+), 40 deletions(-)

diff --git a/plugins/mod_saslauth.lua b/plugins/mod_saslauth.lua
index d8e27c4f..75af5eb6 100644
--- a/plugins/mod_saslauth.lua
+++ b/plugins/mod_saslauth.lua
@@ -53,43 +53,26 @@ local function password_callback(jid, mechanism)
 	return func, nil;
 end
 
+function do_sasl(session, stanza)
+	local text = stanza[1];
+	if text then
+		text = base64.decode(text);
+		if not text then
+			session.sasl_handler = nil;
+			session.send(build_reply("failure", "incorrect-encoding"));
+			return;
+		end
+	end
+	local status, ret = session.sasl_handler:feed(text);
+	handle_status(session, status);
+	session.send(build_reply(status, ret));
+end
+
 add_handler("c2s_unauthed", "auth", xmlns_sasl,
 		function (session, stanza)
 			if not session.sasl_handler then
 				session.sasl_handler = new_sasl(stanza.attr.mechanism, session.host, password_callback);
-				local status, ret = session.sasl_handler:feed(stanza[1]);
-				handle_status(session, status);
-				session.send(build_reply(status, ret));
-				--[[session.sasl_handler = new_sasl(stanza.attr.mechanism, 
-					function (username, password)
-						-- onAuth
-						require "core.usermanager"
-						if usermanager_validate_credentials(session.host, username, password) then
-							return true;
-						end
-						return false;
-					end,
-					function (username)
-						-- onSuccess
-						local success, err = sessionmanager.make_authenticated(session, username);
-						if not success then
-							sessionmanager.destroy_session(session);
-							return;
-						end
-						session.sasl_handler = nil;
-						session:reset_stream();
-					end,
-					function (reason)
-						-- onFail
-						log("debug", "SASL failure, reason: %s", reason);
-					end,
-					function (stanza)
-						-- onWrite
-						log("debug", "SASL writes: %s", tostring(stanza));
-						send(session, stanza);
-					end
-				);
-				session.sasl_handler:feed(stanza);	]]
+				do_sasl(session, stanza);
 			else
 				error("Client tried to negotiate SASL again", 0);
 			end
@@ -98,19 +81,15 @@ add_handler("c2s_unauthed", "auth", xmlns_sasl,
 add_handler("c2s_unauthed", "abort", xmlns_sasl,
 	function(session, stanza)
 		if not session.sasl_handler then error("Attempt to abort when sasl has not started"); end
-		local status, ret = session.sasl_handler:feed(stanza[1]);
-		handle_status(session, status);
-		session.send(build_reply(status, ret));
+		do_sasl(session, stanza);
 	end);
 
 add_handler("c2s_unauthed", "response", xmlns_sasl,
 	function(session, stanza)
 		if not session.sasl_handler then error("Attempt to respond when sasl has not started"); end
-		local status, ret = session.sasl_handler:feed(stanza[1]);
-		handle_status(session, status);
-		session.send(build_reply(status, ret));
+		do_sasl(session, stanza);
 	end);
-		
+
 add_event_hook("stream-features", 
 					function (session, features)												
 						if not session.username then
-- 
cgit v1.2.3


From ffae5a07131ddc38aeafa54d1f50fcadcdb97549 Mon Sep 17 00:00:00 2001
From: Tobias Markmann <tm@ayena.de>
Date: Sat, 15 Nov 2008 19:23:55 +0100
Subject: Made PLAIN method in sasl.lua module follow new interface.

---
 util/sasl.lua | 37 +++++++++++++++++++------------------
 1 file changed, 19 insertions(+), 18 deletions(-)

diff --git a/util/sasl.lua b/util/sasl.lua
index 1f4eff54..8750ce98 100644
--- a/util/sasl.lua
+++ b/util/sasl.lua
@@ -16,24 +16,25 @@ local print = print
 
 module "sasl"
 
-local function new_plain(onAuth, onSuccess, onFail, onWrite)
-	local object = { mechanism = "PLAIN", onAuth = onAuth, onSuccess = onSuccess, onFail = onFail,
-	 				onWrite = onWrite}
-	local challenge = base64.encode("");
-	--onWrite(st.stanza("challenge", {xmlns = "urn:ietf:params:xml:ns:xmpp-sasl"}):text(challenge))
-	object.feed = 	function(self, stanza)
-						if stanza.name ~= "response" and stanza.name ~= "auth" then self.onFail("invalid-stanza-tag") end
-						if stanza.attr.xmlns ~= "urn:ietf:params:xml:ns:xmpp-sasl" then self.onFail("invalid-stanza-namespace") end
-						local response = base64.decode(stanza[1])
+local function new_plain(realm, password_handler)
+	local object = { mechanism = "PLAIN", realm = realm, password_handler = password_handler}
+	object.feed = 	function(self, message)
+						log("debug", "feed: "..message)
+						local response = message
 						local authorization = s_match(response, "([^&%z]+)")
 						local authentication = s_match(response, "%z([^&%z]+)%z")
 						local password = s_match(response, "%z[^&%z]+%z([^&%z]+)")
-						if self.onAuth(authentication, password) == true then
-							self.onWrite(st.stanza("success", {xmlns = "urn:ietf:params:xml:ns:xmpp-sasl"}))
-							self.onSuccess(authentication)
+						
+						local password_encoding, correct_password = self.password_handler(authentication.."@"..self.realm, "PLAIN")
+						
+						local claimed_password = ""
+						if password_encoding == nil then claimed_password = password
+						else claimed_password = password_encoding(password) end
+						
+						if claimed_password == correct_password then
+							return "success", nil
 						else
-							self.onWrite(st.stanza("failure", {xmlns = "urn:ietf:params:xml:ns:xmpp-sasl"}):tag("temporary-auth-failure"));
-							self.onFail("Wrong password.")
+							return "failure", "not-authorized"
 						end
 					end
 	return object
@@ -165,13 +166,13 @@ local function new_digest_md5(onAuth, onSuccess, onFail, onWrite)
 	return object
 end
 
-function new(mechanism, onAuth, onSuccess, onFail, onWrite)
+function new(mechanism, realm, password)
 	local object
-	if mechanism == "PLAIN" then object = new_plain(onAuth, onSuccess, onFail, onWrite)
-	elseif mechanism == "DIGEST-MD5" then object = new_digest_md5(onAuth, onSuccess, onFail, onWrite)
+	if mechanism == "PLAIN" then object = new_plain(realm, password)
+	--elseif mechanism == "DIGEST-MD5" then object = new_digest_md5(ream, password)
 	else
 		log("debug", "Unsupported SASL mechanism: "..tostring(mechanism));
-		onFail("unsupported-mechanism")
+		return nil
 	end
 	return object
 end
-- 
cgit v1.2.3


From 1b6b09a27d981017e4678235f54b6871a6dde7ca Mon Sep 17 00:00:00 2001
From: Waqas Hussain <waqas20@gmail.com>
Date: Sun, 16 Nov 2008 00:25:28 +0500
Subject: Set username on SASL success

---
 plugins/mod_saslauth.lua | 2 ++
 1 file changed, 2 insertions(+)

diff --git a/plugins/mod_saslauth.lua b/plugins/mod_saslauth.lua
index 75af5eb6..24b19cfb 100644
--- a/plugins/mod_saslauth.lua
+++ b/plugins/mod_saslauth.lua
@@ -34,6 +34,8 @@ local function handle_status(session, status)
 	if status == "failure" then
 		session.sasl_handler = nil;
 	elseif status == "success" then
+		if not session.sasl_handler.username then error("SASL succeeded but we didn't get a username!"); end -- TODO move this to sessionmanager
+		sessionmanager.make_authenticated(session, session.sasl_handler.username);
 		session.sasl_handler = nil;
 		session:reset_stream();
 	end
-- 
cgit v1.2.3


From 0d8a36b732987a9cf82437acd513280c9faa4b08 Mon Sep 17 00:00:00 2001
From: Tobias Markmann <tm@ayena.de>
Date: Sat, 15 Nov 2008 20:28:09 +0100
Subject: Set username in a SASL object.

---
 plugins/mod_saslauth.lua | 5 ++++-
 util/sasl.lua            | 7 ++++++-
 2 files changed, 10 insertions(+), 2 deletions(-)

diff --git a/plugins/mod_saslauth.lua b/plugins/mod_saslauth.lua
index b95d160d..314d2502 100644
--- a/plugins/mod_saslauth.lua
+++ b/plugins/mod_saslauth.lua
@@ -7,6 +7,7 @@ local jid
 local usermanager_validate_credentials = require "core.usermanager".validate_credentials;
 local t_concat, t_insert = table.concat, table.insert;
 local tostring = tostring;
+local jid_split = require "util.jid".split
 
 local log = require "util.logger".init("mod_saslauth");
 
@@ -65,7 +66,9 @@ function do_sasl(session, stanza)
 	end
 	local status, ret = session.sasl_handler:feed(text);
 	handle_status(session, status);
-	session.send(build_reply(status, ret));
+	local s = build_reply(status, ret); 
+	log("debug", "sasl reply: "..tostring(s));
+	session.send(s);
 end
 
 add_handler("c2s_unauthed", "auth", xmlns_sasl,
diff --git a/util/sasl.lua b/util/sasl.lua
index 8750ce98..430bfe5c 100644
--- a/util/sasl.lua
+++ b/util/sasl.lua
@@ -19,7 +19,9 @@ module "sasl"
 local function new_plain(realm, password_handler)
 	local object = { mechanism = "PLAIN", realm = realm, password_handler = password_handler}
 	object.feed = 	function(self, message)
-						log("debug", "feed: "..message)
+						--print(message:gsub("%W", function (c) return string.format("\\%d", string.byte(c)) end));
+
+						if message == "" or message == nil then return "failure", "malformed-request" end
 						local response = message
 						local authorization = s_match(response, "([^&%z]+)")
 						local authentication = s_match(response, "%z([^&%z]+)%z")
@@ -31,9 +33,12 @@ local function new_plain(realm, password_handler)
 						if password_encoding == nil then claimed_password = password
 						else claimed_password = password_encoding(password) end
 						
+						self.username = authentication
 						if claimed_password == correct_password then
+							log("debug", "success")
 							return "success", nil
 						else
+							log("debug", "failure")
 							return "failure", "not-authorized"
 						end
 					end
-- 
cgit v1.2.3