diff --git a/nselib/omp2.lua b/nselib/omp2.lua
index 6b2c3af88..d31c1029a 100644
--- a/nselib/omp2.lua
+++ b/nselib/omp2.lua
@@ -32,8 +32,23 @@
local nmap = require "nmap"
local stdnse = require "stdnse"
local table = require "table"
+local unittest = require "unittest"
_ENV = stdnse.module("omp2", stdnse.seeall)
+--- Escape the five XML special characters in text used as element content.
+-- OMP credentials are interpolated into an XML request, so unescaped
+-- characters can produce malformed XML or alter the meaning of the request.
+-- @param s String to escape.
+-- @return The escaped string.
+local function xml_escape(s)
+ local escaped = s:gsub("&", "&")
+ escaped = escaped:gsub("<", "<")
+ escaped = escaped:gsub(">", ">")
+ escaped = escaped:gsub('"', """)
+ escaped = escaped:gsub("'", "'")
+ return escaped
+end
+
local HAVE_SSL = false
if pcall(require,'openssl') then
@@ -75,10 +90,9 @@ Session = {
authenticate = function(self, username, password)
local status, err, xmldata
- -- TODO escape credentials
status, err = self.socket:send(""
- .. "" .. username .. ""
- .. "" .. password .. ""
+ .. "" .. xml_escape(username) .. ""
+ .. "" .. xml_escape(password) .. ""
.. "")
if not status then
@@ -174,5 +188,36 @@ function get_accounts(host)
return nil
end
+if not unittest.testing() then
+ return _ENV
+end
+
+test_suite = unittest.TestSuite:new()
+local equal = unittest.equal
+
+test_suite:add_test(equal(xml_escape("plain"), "plain"), "plain text unchanged")
+test_suite:add_test(equal(xml_escape("a&b"), "a&b"), "ampersand escaped")
+test_suite:add_test(equal(xml_escape("ab"), "a>b"), "greater-than escaped")
+test_suite:add_test(equal(xml_escape('a"b'), "a"b"), "double quote escaped")
+test_suite:add_test(equal(xml_escape("a'b"), "a'b"), "apostrophe escaped")
+test_suite:add_test(equal(xml_escape("&<>'\""), "&<>'""),
+ "all special characters escaped")
+test_suite:add_test(equal(xml_escape("&"), "&"),
+ "pre-escaped entity is escaped again")
+
+-- Verify the actual request built by authenticate() uses the escaped values.
+local sent
+local mock_socket = {
+ send = function(self, data) sent = data; return true end,
+ receive = function(self) return true, '' end,
+}
+local session = setmetatable({socket = mock_socket}, Session)
+test_suite:add_test(equal(session:authenticate("user&x", "p") and true, true),
+ "authenticate succeeds with special characters")
+test_suite:add_test(equal(sent,
+ "user&x"
+ .. "p<ass>"),
+ "authenticate escapes credentials in the request")
return _ENV;